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
sequencelengths 21
1.41k
| docstring
stringlengths 6
2.61k
| docstring_tokens
sequencelengths 3
215
| sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
152,600 | Azure/go-autorest | autorest/adal/token.go | NewServicePrincipalTokenFromMSI | func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) {
return newServicePrincipalTokenFromMSI(msiEndpoint, resource, nil, callbacks...)
} | go | func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) {
return newServicePrincipalTokenFromMSI(msiEndpoint, resource, nil, callbacks...)
} | [
"func",
"NewServicePrincipalTokenFromMSI",
"(",
"msiEndpoint",
",",
"resource",
"string",
",",
"callbacks",
"...",
"TokenRefreshCallback",
")",
"(",
"*",
"ServicePrincipalToken",
",",
"error",
")",
"{",
"return",
"newServicePrincipalTokenFromMSI",
"(",
"msiEndpoint",
",",
"resource",
",",
"nil",
",",
"callbacks",
"...",
")",
"\n",
"}"
] | // NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension.
// It will use the system assigned identity when creating the token. | [
"NewServicePrincipalTokenFromMSI",
"creates",
"a",
"ServicePrincipalToken",
"via",
"the",
"MSI",
"VM",
"Extension",
".",
"It",
"will",
"use",
"the",
"system",
"assigned",
"identity",
"when",
"creating",
"the",
"token",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L634-L636 |
152,601 | Azure/go-autorest | autorest/adal/token.go | NewServicePrincipalTokenFromMSIWithUserAssignedID | func NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource string, userAssignedID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) {
return newServicePrincipalTokenFromMSI(msiEndpoint, resource, &userAssignedID, callbacks...)
} | go | func NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource string, userAssignedID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) {
return newServicePrincipalTokenFromMSI(msiEndpoint, resource, &userAssignedID, callbacks...)
} | [
"func",
"NewServicePrincipalTokenFromMSIWithUserAssignedID",
"(",
"msiEndpoint",
",",
"resource",
"string",
",",
"userAssignedID",
"string",
",",
"callbacks",
"...",
"TokenRefreshCallback",
")",
"(",
"*",
"ServicePrincipalToken",
",",
"error",
")",
"{",
"return",
"newServicePrincipalTokenFromMSI",
"(",
"msiEndpoint",
",",
"resource",
",",
"&",
"userAssignedID",
",",
"callbacks",
"...",
")",
"\n",
"}"
] | // NewServicePrincipalTokenFromMSIWithUserAssignedID creates a ServicePrincipalToken via the MSI VM Extension.
// It will use the specified user assigned identity when creating the token. | [
"NewServicePrincipalTokenFromMSIWithUserAssignedID",
"creates",
"a",
"ServicePrincipalToken",
"via",
"the",
"MSI",
"VM",
"Extension",
".",
"It",
"will",
"use",
"the",
"specified",
"user",
"assigned",
"identity",
"when",
"creating",
"the",
"token",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L640-L642 |
152,602 | Azure/go-autorest | autorest/adal/token.go | InvokeRefreshCallbacks | func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error {
if spt.refreshCallbacks != nil {
for _, callback := range spt.refreshCallbacks {
err := callback(spt.inner.Token)
if err != nil {
return fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err)
}
}
}
return nil
} | go | func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error {
if spt.refreshCallbacks != nil {
for _, callback := range spt.refreshCallbacks {
err := callback(spt.inner.Token)
if err != nil {
return fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err)
}
}
}
return nil
} | [
"func",
"(",
"spt",
"*",
"ServicePrincipalToken",
")",
"InvokeRefreshCallbacks",
"(",
"token",
"Token",
")",
"error",
"{",
"if",
"spt",
".",
"refreshCallbacks",
"!=",
"nil",
"{",
"for",
"_",
",",
"callback",
":=",
"range",
"spt",
".",
"refreshCallbacks",
"{",
"err",
":=",
"callback",
"(",
"spt",
".",
"inner",
".",
"Token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization | [
"InvokeRefreshCallbacks",
"calls",
"any",
"TokenRefreshCallbacks",
"that",
"were",
"added",
"to",
"the",
"SPT",
"during",
"initialization"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L735-L745 |
152,603 | Azure/go-autorest | autorest/adal/token.go | RefreshWithContext | func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error {
spt.refreshLock.Lock()
defer spt.refreshLock.Unlock()
return spt.refreshInternal(ctx, spt.inner.Resource)
} | go | func (spt *ServicePrincipalToken) RefreshWithContext(ctx context.Context) error {
spt.refreshLock.Lock()
defer spt.refreshLock.Unlock()
return spt.refreshInternal(ctx, spt.inner.Resource)
} | [
"func",
"(",
"spt",
"*",
"ServicePrincipalToken",
")",
"RefreshWithContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"spt",
".",
"refreshLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"spt",
".",
"refreshLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"spt",
".",
"refreshInternal",
"(",
"ctx",
",",
"spt",
".",
"inner",
".",
"Resource",
")",
"\n",
"}"
] | // RefreshWithContext obtains a fresh token for the Service Principal.
// This method is not safe for concurrent use and should be syncrhonized. | [
"RefreshWithContext",
"obtains",
"a",
"fresh",
"token",
"for",
"the",
"Service",
"Principal",
".",
"This",
"method",
"is",
"not",
"safe",
"for",
"concurrent",
"use",
"and",
"should",
"be",
"syncrhonized",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L755-L759 |
152,604 | Azure/go-autorest | autorest/adal/token.go | RefreshExchange | func (spt *ServicePrincipalToken) RefreshExchange(resource string) error {
return spt.RefreshExchangeWithContext(context.Background(), resource)
} | go | func (spt *ServicePrincipalToken) RefreshExchange(resource string) error {
return spt.RefreshExchangeWithContext(context.Background(), resource)
} | [
"func",
"(",
"spt",
"*",
"ServicePrincipalToken",
")",
"RefreshExchange",
"(",
"resource",
"string",
")",
"error",
"{",
"return",
"spt",
".",
"RefreshExchangeWithContext",
"(",
"context",
".",
"Background",
"(",
")",
",",
"resource",
")",
"\n",
"}"
] | // RefreshExchange refreshes the token, but for a different resource.
// This method is not safe for concurrent use and should be syncrhonized. | [
"RefreshExchange",
"refreshes",
"the",
"token",
"but",
"for",
"a",
"different",
"resource",
".",
"This",
"method",
"is",
"not",
"safe",
"for",
"concurrent",
"use",
"and",
"should",
"be",
"syncrhonized",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L763-L765 |
152,605 | Azure/go-autorest | autorest/adal/token.go | RefreshExchangeWithContext | func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error {
spt.refreshLock.Lock()
defer spt.refreshLock.Unlock()
return spt.refreshInternal(ctx, resource)
} | go | func (spt *ServicePrincipalToken) RefreshExchangeWithContext(ctx context.Context, resource string) error {
spt.refreshLock.Lock()
defer spt.refreshLock.Unlock()
return spt.refreshInternal(ctx, resource)
} | [
"func",
"(",
"spt",
"*",
"ServicePrincipalToken",
")",
"RefreshExchangeWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"resource",
"string",
")",
"error",
"{",
"spt",
".",
"refreshLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"spt",
".",
"refreshLock",
".",
"Unlock",
"(",
")",
"\n",
"return",
"spt",
".",
"refreshInternal",
"(",
"ctx",
",",
"resource",
")",
"\n",
"}"
] | // RefreshExchangeWithContext refreshes the token, but for a different resource.
// This method is not safe for concurrent use and should be syncrhonized. | [
"RefreshExchangeWithContext",
"refreshes",
"the",
"token",
"but",
"for",
"a",
"different",
"resource",
".",
"This",
"method",
"is",
"not",
"safe",
"for",
"concurrent",
"use",
"and",
"should",
"be",
"syncrhonized",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L769-L773 |
152,606 | Azure/go-autorest | autorest/adal/token.go | retryForIMDS | func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http.Response, err error) {
// copied from client.go due to circular dependency
retries := []int{
http.StatusRequestTimeout, // 408
http.StatusTooManyRequests, // 429
http.StatusInternalServerError, // 500
http.StatusBadGateway, // 502
http.StatusServiceUnavailable, // 503
http.StatusGatewayTimeout, // 504
}
// extra retry status codes specific to IMDS
retries = append(retries,
http.StatusNotFound,
http.StatusGone,
// all remaining 5xx
http.StatusNotImplemented,
http.StatusHTTPVersionNotSupported,
http.StatusVariantAlsoNegotiates,
http.StatusInsufficientStorage,
http.StatusLoopDetected,
http.StatusNotExtended,
http.StatusNetworkAuthenticationRequired)
// see https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-token#retry-guidance
const maxDelay time.Duration = 60 * time.Second
attempt := 0
delay := time.Duration(0)
for attempt < maxAttempts {
resp, err = sender.Do(req)
// retry on temporary network errors, e.g. transient network failures.
// if we don't receive a response then assume we can't connect to the
// endpoint so we're likely not running on an Azure VM so don't retry.
if (err != nil && !isTemporaryNetworkError(err)) || resp == nil || resp.StatusCode == http.StatusOK || !containsInt(retries, resp.StatusCode) {
return
}
// perform exponential backoff with a cap.
// must increment attempt before calculating delay.
attempt++
// the base value of 2 is the "delta backoff" as specified in the guidance doc
delay += (time.Duration(math.Pow(2, float64(attempt))) * time.Second)
if delay > maxDelay {
delay = maxDelay
}
select {
case <-time.After(delay):
// intentionally left blank
case <-req.Context().Done():
err = req.Context().Err()
return
}
}
return
} | go | func retryForIMDS(sender Sender, req *http.Request, maxAttempts int) (resp *http.Response, err error) {
// copied from client.go due to circular dependency
retries := []int{
http.StatusRequestTimeout, // 408
http.StatusTooManyRequests, // 429
http.StatusInternalServerError, // 500
http.StatusBadGateway, // 502
http.StatusServiceUnavailable, // 503
http.StatusGatewayTimeout, // 504
}
// extra retry status codes specific to IMDS
retries = append(retries,
http.StatusNotFound,
http.StatusGone,
// all remaining 5xx
http.StatusNotImplemented,
http.StatusHTTPVersionNotSupported,
http.StatusVariantAlsoNegotiates,
http.StatusInsufficientStorage,
http.StatusLoopDetected,
http.StatusNotExtended,
http.StatusNetworkAuthenticationRequired)
// see https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-token#retry-guidance
const maxDelay time.Duration = 60 * time.Second
attempt := 0
delay := time.Duration(0)
for attempt < maxAttempts {
resp, err = sender.Do(req)
// retry on temporary network errors, e.g. transient network failures.
// if we don't receive a response then assume we can't connect to the
// endpoint so we're likely not running on an Azure VM so don't retry.
if (err != nil && !isTemporaryNetworkError(err)) || resp == nil || resp.StatusCode == http.StatusOK || !containsInt(retries, resp.StatusCode) {
return
}
// perform exponential backoff with a cap.
// must increment attempt before calculating delay.
attempt++
// the base value of 2 is the "delta backoff" as specified in the guidance doc
delay += (time.Duration(math.Pow(2, float64(attempt))) * time.Second)
if delay > maxDelay {
delay = maxDelay
}
select {
case <-time.After(delay):
// intentionally left blank
case <-req.Context().Done():
err = req.Context().Err()
return
}
}
return
} | [
"func",
"retryForIMDS",
"(",
"sender",
"Sender",
",",
"req",
"*",
"http",
".",
"Request",
",",
"maxAttempts",
"int",
")",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"{",
"// copied from client.go due to circular dependency",
"retries",
":=",
"[",
"]",
"int",
"{",
"http",
".",
"StatusRequestTimeout",
",",
"// 408",
"http",
".",
"StatusTooManyRequests",
",",
"// 429",
"http",
".",
"StatusInternalServerError",
",",
"// 500",
"http",
".",
"StatusBadGateway",
",",
"// 502",
"http",
".",
"StatusServiceUnavailable",
",",
"// 503",
"http",
".",
"StatusGatewayTimeout",
",",
"// 504",
"}",
"\n",
"// extra retry status codes specific to IMDS",
"retries",
"=",
"append",
"(",
"retries",
",",
"http",
".",
"StatusNotFound",
",",
"http",
".",
"StatusGone",
",",
"// all remaining 5xx",
"http",
".",
"StatusNotImplemented",
",",
"http",
".",
"StatusHTTPVersionNotSupported",
",",
"http",
".",
"StatusVariantAlsoNegotiates",
",",
"http",
".",
"StatusInsufficientStorage",
",",
"http",
".",
"StatusLoopDetected",
",",
"http",
".",
"StatusNotExtended",
",",
"http",
".",
"StatusNetworkAuthenticationRequired",
")",
"\n\n",
"// see https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/how-to-use-vm-token#retry-guidance",
"const",
"maxDelay",
"time",
".",
"Duration",
"=",
"60",
"*",
"time",
".",
"Second",
"\n\n",
"attempt",
":=",
"0",
"\n",
"delay",
":=",
"time",
".",
"Duration",
"(",
"0",
")",
"\n\n",
"for",
"attempt",
"<",
"maxAttempts",
"{",
"resp",
",",
"err",
"=",
"sender",
".",
"Do",
"(",
"req",
")",
"\n",
"// retry on temporary network errors, e.g. transient network failures.",
"// if we don't receive a response then assume we can't connect to the",
"// endpoint so we're likely not running on an Azure VM so don't retry.",
"if",
"(",
"err",
"!=",
"nil",
"&&",
"!",
"isTemporaryNetworkError",
"(",
"err",
")",
")",
"||",
"resp",
"==",
"nil",
"||",
"resp",
".",
"StatusCode",
"==",
"http",
".",
"StatusOK",
"||",
"!",
"containsInt",
"(",
"retries",
",",
"resp",
".",
"StatusCode",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"// perform exponential backoff with a cap.",
"// must increment attempt before calculating delay.",
"attempt",
"++",
"\n",
"// the base value of 2 is the \"delta backoff\" as specified in the guidance doc",
"delay",
"+=",
"(",
"time",
".",
"Duration",
"(",
"math",
".",
"Pow",
"(",
"2",
",",
"float64",
"(",
"attempt",
")",
")",
")",
"*",
"time",
".",
"Second",
")",
"\n",
"if",
"delay",
">",
"maxDelay",
"{",
"delay",
"=",
"maxDelay",
"\n",
"}",
"\n\n",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"delay",
")",
":",
"// intentionally left blank",
"case",
"<-",
"req",
".",
"Context",
"(",
")",
".",
"Done",
"(",
")",
":",
"err",
"=",
"req",
".",
"Context",
"(",
")",
".",
"Err",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // retry logic specific to retrieving a token from the IMDS endpoint | [
"retry",
"logic",
"specific",
"to",
"retrieving",
"a",
"token",
"from",
"the",
"IMDS",
"endpoint"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L879-L936 |
152,607 | Azure/go-autorest | autorest/adal/token.go | isTemporaryNetworkError | func isTemporaryNetworkError(err error) bool {
if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) {
return true
}
return false
} | go | func isTemporaryNetworkError(err error) bool {
if netErr, ok := err.(net.Error); !ok || (ok && netErr.Temporary()) {
return true
}
return false
} | [
"func",
"isTemporaryNetworkError",
"(",
"err",
"error",
")",
"bool",
"{",
"if",
"netErr",
",",
"ok",
":=",
"err",
".",
"(",
"net",
".",
"Error",
")",
";",
"!",
"ok",
"||",
"(",
"ok",
"&&",
"netErr",
".",
"Temporary",
"(",
")",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // returns true if the specified error is a temporary network error or false if it's not.
// if the error doesn't implement the net.Error interface the return value is true. | [
"returns",
"true",
"if",
"the",
"specified",
"error",
"is",
"a",
"temporary",
"network",
"error",
"or",
"false",
"if",
"it",
"s",
"not",
".",
"if",
"the",
"error",
"doesn",
"t",
"implement",
"the",
"net",
".",
"Error",
"interface",
"the",
"return",
"value",
"is",
"true",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L940-L945 |
152,608 | Azure/go-autorest | autorest/adal/token.go | SetRefreshWithin | func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) {
spt.inner.RefreshWithin = d
return
} | go | func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) {
spt.inner.RefreshWithin = d
return
} | [
"func",
"(",
"spt",
"*",
"ServicePrincipalToken",
")",
"SetRefreshWithin",
"(",
"d",
"time",
".",
"Duration",
")",
"{",
"spt",
".",
"inner",
".",
"RefreshWithin",
"=",
"d",
"\n",
"return",
"\n",
"}"
] | // SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will
// refresh the token. | [
"SetRefreshWithin",
"sets",
"the",
"interval",
"within",
"which",
"if",
"the",
"token",
"will",
"expire",
"EnsureFresh",
"will",
"refresh",
"the",
"token",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L964-L967 |
152,609 | Azure/go-autorest | autorest/adal/token.go | OAuthToken | func (spt *ServicePrincipalToken) OAuthToken() string {
spt.refreshLock.RLock()
defer spt.refreshLock.RUnlock()
return spt.inner.Token.OAuthToken()
} | go | func (spt *ServicePrincipalToken) OAuthToken() string {
spt.refreshLock.RLock()
defer spt.refreshLock.RUnlock()
return spt.inner.Token.OAuthToken()
} | [
"func",
"(",
"spt",
"*",
"ServicePrincipalToken",
")",
"OAuthToken",
"(",
")",
"string",
"{",
"spt",
".",
"refreshLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"spt",
".",
"refreshLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"spt",
".",
"inner",
".",
"Token",
".",
"OAuthToken",
"(",
")",
"\n",
"}"
] | // OAuthToken implements the OAuthTokenProvider interface. It returns the current access token. | [
"OAuthToken",
"implements",
"the",
"OAuthTokenProvider",
"interface",
".",
"It",
"returns",
"the",
"current",
"access",
"token",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L974-L978 |
152,610 | Azure/go-autorest | autorest/adal/token.go | Token | func (spt *ServicePrincipalToken) Token() Token {
spt.refreshLock.RLock()
defer spt.refreshLock.RUnlock()
return spt.inner.Token
} | go | func (spt *ServicePrincipalToken) Token() Token {
spt.refreshLock.RLock()
defer spt.refreshLock.RUnlock()
return spt.inner.Token
} | [
"func",
"(",
"spt",
"*",
"ServicePrincipalToken",
")",
"Token",
"(",
")",
"Token",
"{",
"spt",
".",
"refreshLock",
".",
"RLock",
"(",
")",
"\n",
"defer",
"spt",
".",
"refreshLock",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"spt",
".",
"inner",
".",
"Token",
"\n",
"}"
] | // Token returns a copy of the current token. | [
"Token",
"returns",
"a",
"copy",
"of",
"the",
"current",
"token",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/token.go#L981-L985 |
152,611 | Azure/go-autorest | autorest/mocks/mocks.go | Read | func (body *Body) Read(b []byte) (n int, err error) {
if !body.IsOpen() {
return 0, fmt.Errorf("ERROR: Body has been closed")
}
if len(body.b) == 0 {
return 0, io.EOF
}
n = copy(b, body.b)
body.b = body.b[n:]
return n, nil
} | go | func (body *Body) Read(b []byte) (n int, err error) {
if !body.IsOpen() {
return 0, fmt.Errorf("ERROR: Body has been closed")
}
if len(body.b) == 0 {
return 0, io.EOF
}
n = copy(b, body.b)
body.b = body.b[n:]
return n, nil
} | [
"func",
"(",
"body",
"*",
"Body",
")",
"Read",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"if",
"!",
"body",
".",
"IsOpen",
"(",
")",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"body",
".",
"b",
")",
"==",
"0",
"{",
"return",
"0",
",",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"n",
"=",
"copy",
"(",
"b",
",",
"body",
".",
"b",
")",
"\n",
"body",
".",
"b",
"=",
"body",
".",
"b",
"[",
"n",
":",
"]",
"\n",
"return",
"n",
",",
"nil",
"\n",
"}"
] | // Read reads into the passed byte slice and returns the bytes read. | [
"Read",
"reads",
"into",
"the",
"passed",
"byte",
"slice",
"and",
"returns",
"the",
"bytes",
"read",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L46-L56 |
152,612 | Azure/go-autorest | autorest/mocks/mocks.go | Close | func (body *Body) Close() error {
if body.isOpen {
body.isOpen = false
body.closeAttempts++
}
return nil
} | go | func (body *Body) Close() error {
if body.isOpen {
body.isOpen = false
body.closeAttempts++
}
return nil
} | [
"func",
"(",
"body",
"*",
"Body",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"body",
".",
"isOpen",
"{",
"body",
".",
"isOpen",
"=",
"false",
"\n",
"body",
".",
"closeAttempts",
"++",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close closes the body. | [
"Close",
"closes",
"the",
"body",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L59-L65 |
152,613 | Azure/go-autorest | autorest/mocks/mocks.go | Length | func (body *Body) Length() int64 {
if body == nil {
return 0
}
return int64(len(body.b))
} | go | func (body *Body) Length() int64 {
if body == nil {
return 0
}
return int64(len(body.b))
} | [
"func",
"(",
"body",
"*",
"Body",
")",
"Length",
"(",
")",
"int64",
"{",
"if",
"body",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"int64",
"(",
"len",
"(",
"body",
".",
"b",
")",
")",
"\n",
"}"
] | // Length returns the number of bytes in the body. | [
"Length",
"returns",
"the",
"number",
"of",
"bytes",
"in",
"the",
"body",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L84-L89 |
152,614 | Azure/go-autorest | autorest/mocks/mocks.go | Do | func (c *Sender) Do(r *http.Request) (resp *http.Response, err error) {
c.attempts++
if len(c.responses) > 0 {
resp = c.responses[0].r
if resp != nil {
if b, ok := resp.Body.(*Body); ok {
b.reset()
}
} else {
err = c.responses[0].e
}
time.Sleep(c.responses[0].d)
c.repeatResponse[0]--
if c.repeatResponse[0] == 0 {
c.responses = c.responses[1:]
c.repeatResponse = c.repeatResponse[1:]
}
} else {
resp = NewResponse()
}
if resp != nil {
resp.Request = r
}
if c.emitErrorAfter > 0 {
c.emitErrorAfter--
} else if c.err != nil {
err = c.err
c.repeatError--
if c.repeatError == 0 {
c.err = nil
}
}
return
} | go | func (c *Sender) Do(r *http.Request) (resp *http.Response, err error) {
c.attempts++
if len(c.responses) > 0 {
resp = c.responses[0].r
if resp != nil {
if b, ok := resp.Body.(*Body); ok {
b.reset()
}
} else {
err = c.responses[0].e
}
time.Sleep(c.responses[0].d)
c.repeatResponse[0]--
if c.repeatResponse[0] == 0 {
c.responses = c.responses[1:]
c.repeatResponse = c.repeatResponse[1:]
}
} else {
resp = NewResponse()
}
if resp != nil {
resp.Request = r
}
if c.emitErrorAfter > 0 {
c.emitErrorAfter--
} else if c.err != nil {
err = c.err
c.repeatError--
if c.repeatError == 0 {
c.err = nil
}
}
return
} | [
"func",
"(",
"c",
"*",
"Sender",
")",
"Do",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"err",
"error",
")",
"{",
"c",
".",
"attempts",
"++",
"\n\n",
"if",
"len",
"(",
"c",
".",
"responses",
")",
">",
"0",
"{",
"resp",
"=",
"c",
".",
"responses",
"[",
"0",
"]",
".",
"r",
"\n",
"if",
"resp",
"!=",
"nil",
"{",
"if",
"b",
",",
"ok",
":=",
"resp",
".",
"Body",
".",
"(",
"*",
"Body",
")",
";",
"ok",
"{",
"b",
".",
"reset",
"(",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"err",
"=",
"c",
".",
"responses",
"[",
"0",
"]",
".",
"e",
"\n",
"}",
"\n",
"time",
".",
"Sleep",
"(",
"c",
".",
"responses",
"[",
"0",
"]",
".",
"d",
")",
"\n",
"c",
".",
"repeatResponse",
"[",
"0",
"]",
"--",
"\n",
"if",
"c",
".",
"repeatResponse",
"[",
"0",
"]",
"==",
"0",
"{",
"c",
".",
"responses",
"=",
"c",
".",
"responses",
"[",
"1",
":",
"]",
"\n",
"c",
".",
"repeatResponse",
"=",
"c",
".",
"repeatResponse",
"[",
"1",
":",
"]",
"\n",
"}",
"\n",
"}",
"else",
"{",
"resp",
"=",
"NewResponse",
"(",
")",
"\n",
"}",
"\n",
"if",
"resp",
"!=",
"nil",
"{",
"resp",
".",
"Request",
"=",
"r",
"\n",
"}",
"\n\n",
"if",
"c",
".",
"emitErrorAfter",
">",
"0",
"{",
"c",
".",
"emitErrorAfter",
"--",
"\n",
"}",
"else",
"if",
"c",
".",
"err",
"!=",
"nil",
"{",
"err",
"=",
"c",
".",
"err",
"\n",
"c",
".",
"repeatError",
"--",
"\n",
"if",
"c",
".",
"repeatError",
"==",
"0",
"{",
"c",
".",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Do accepts the passed request and, based on settings, emits a response and possible error. | [
"Do",
"accepts",
"the",
"passed",
"request",
"and",
"based",
"on",
"settings",
"emits",
"a",
"response",
"and",
"possible",
"error",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L114-L150 |
152,615 | Azure/go-autorest | autorest/mocks/mocks.go | AppendResponseWithDelay | func (c *Sender) AppendResponseWithDelay(resp *http.Response, delay time.Duration) {
c.AppendAndRepeatResponseWithDelay(resp, delay, 1)
} | go | func (c *Sender) AppendResponseWithDelay(resp *http.Response, delay time.Duration) {
c.AppendAndRepeatResponseWithDelay(resp, delay, 1)
} | [
"func",
"(",
"c",
"*",
"Sender",
")",
"AppendResponseWithDelay",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"delay",
"time",
".",
"Duration",
")",
"{",
"c",
".",
"AppendAndRepeatResponseWithDelay",
"(",
"resp",
",",
"delay",
",",
"1",
")",
"\n",
"}"
] | // AppendResponseWithDelay adds the passed http.Response to the response stack with the specified delay. | [
"AppendResponseWithDelay",
"adds",
"the",
"passed",
"http",
".",
"Response",
"to",
"the",
"response",
"stack",
"with",
"the",
"specified",
"delay",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L158-L160 |
152,616 | Azure/go-autorest | autorest/mocks/mocks.go | AppendAndRepeatResponse | func (c *Sender) AppendAndRepeatResponse(resp *http.Response, repeat int) {
c.appendAndRepeat(response{r: resp}, repeat)
} | go | func (c *Sender) AppendAndRepeatResponse(resp *http.Response, repeat int) {
c.appendAndRepeat(response{r: resp}, repeat)
} | [
"func",
"(",
"c",
"*",
"Sender",
")",
"AppendAndRepeatResponse",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"repeat",
"int",
")",
"{",
"c",
".",
"appendAndRepeat",
"(",
"response",
"{",
"r",
":",
"resp",
"}",
",",
"repeat",
")",
"\n",
"}"
] | // AppendAndRepeatResponse adds the passed http.Response to the response stack along with a
// repeat count. A negative repeat count will return the response for all remaining calls to Do. | [
"AppendAndRepeatResponse",
"adds",
"the",
"passed",
"http",
".",
"Response",
"to",
"the",
"response",
"stack",
"along",
"with",
"a",
"repeat",
"count",
".",
"A",
"negative",
"repeat",
"count",
"will",
"return",
"the",
"response",
"for",
"all",
"remaining",
"calls",
"to",
"Do",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L164-L166 |
152,617 | Azure/go-autorest | autorest/mocks/mocks.go | AppendAndRepeatResponseWithDelay | func (c *Sender) AppendAndRepeatResponseWithDelay(resp *http.Response, delay time.Duration, repeat int) {
c.appendAndRepeat(response{r: resp, d: delay}, repeat)
} | go | func (c *Sender) AppendAndRepeatResponseWithDelay(resp *http.Response, delay time.Duration, repeat int) {
c.appendAndRepeat(response{r: resp, d: delay}, repeat)
} | [
"func",
"(",
"c",
"*",
"Sender",
")",
"AppendAndRepeatResponseWithDelay",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"delay",
"time",
".",
"Duration",
",",
"repeat",
"int",
")",
"{",
"c",
".",
"appendAndRepeat",
"(",
"response",
"{",
"r",
":",
"resp",
",",
"d",
":",
"delay",
"}",
",",
"repeat",
")",
"\n",
"}"
] | // AppendAndRepeatResponseWithDelay adds the passed http.Response to the response stack with the specified
// delay along with a repeat count. A negative repeat count will return the response for all remaining calls to Do. | [
"AppendAndRepeatResponseWithDelay",
"adds",
"the",
"passed",
"http",
".",
"Response",
"to",
"the",
"response",
"stack",
"with",
"the",
"specified",
"delay",
"along",
"with",
"a",
"repeat",
"count",
".",
"A",
"negative",
"repeat",
"count",
"will",
"return",
"the",
"response",
"for",
"all",
"remaining",
"calls",
"to",
"Do",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L170-L172 |
152,618 | Azure/go-autorest | autorest/mocks/mocks.go | AppendAndRepeatError | func (c *Sender) AppendAndRepeatError(err error, repeat int) {
c.appendAndRepeat(response{e: err}, repeat)
} | go | func (c *Sender) AppendAndRepeatError(err error, repeat int) {
c.appendAndRepeat(response{e: err}, repeat)
} | [
"func",
"(",
"c",
"*",
"Sender",
")",
"AppendAndRepeatError",
"(",
"err",
"error",
",",
"repeat",
"int",
")",
"{",
"c",
".",
"appendAndRepeat",
"(",
"response",
"{",
"e",
":",
"err",
"}",
",",
"repeat",
")",
"\n",
"}"
] | // AppendAndRepeatError adds the passed error to the response stack along with a repeat
// count. A negative repeat count will return the response for all remaining calls to Do. | [
"AppendAndRepeatError",
"adds",
"the",
"passed",
"error",
"to",
"the",
"response",
"stack",
"along",
"with",
"a",
"repeat",
"count",
".",
"A",
"negative",
"repeat",
"count",
"will",
"return",
"the",
"response",
"for",
"all",
"remaining",
"calls",
"to",
"Do",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L181-L183 |
152,619 | Azure/go-autorest | autorest/mocks/mocks.go | SetAndRepeatError | func (c *Sender) SetAndRepeatError(err error, repeat int) {
c.err = err
c.repeatError = repeat
} | go | func (c *Sender) SetAndRepeatError(err error, repeat int) {
c.err = err
c.repeatError = repeat
} | [
"func",
"(",
"c",
"*",
"Sender",
")",
"SetAndRepeatError",
"(",
"err",
"error",
",",
"repeat",
"int",
")",
"{",
"c",
".",
"err",
"=",
"err",
"\n",
"c",
".",
"repeatError",
"=",
"repeat",
"\n",
"}"
] | // SetAndRepeatError sets the error Do should return and how many calls to Do will return the error.
// A negative repeat value will return the error for all remaining calls to Do. | [
"SetAndRepeatError",
"sets",
"the",
"error",
"Do",
"should",
"return",
"and",
"how",
"many",
"calls",
"to",
"Do",
"will",
"return",
"the",
"error",
".",
"A",
"negative",
"repeat",
"value",
"will",
"return",
"the",
"error",
"for",
"all",
"remaining",
"calls",
"to",
"Do",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/mocks/mocks.go#L208-L211 |
152,620 | Azure/go-autorest | autorest/azure/cli/profile.go | ProfilePath | func ProfilePath() (string, error) {
if cfgDir := os.Getenv("AZURE_CONFIG_DIR"); cfgDir != "" {
return filepath.Join(cfgDir, azureProfileJSON), nil
}
return homedir.Expand("~/.azure/" + azureProfileJSON)
} | go | func ProfilePath() (string, error) {
if cfgDir := os.Getenv("AZURE_CONFIG_DIR"); cfgDir != "" {
return filepath.Join(cfgDir, azureProfileJSON), nil
}
return homedir.Expand("~/.azure/" + azureProfileJSON)
} | [
"func",
"ProfilePath",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"cfgDir",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
";",
"cfgDir",
"!=",
"\"",
"\"",
"{",
"return",
"filepath",
".",
"Join",
"(",
"cfgDir",
",",
"azureProfileJSON",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"homedir",
".",
"Expand",
"(",
"\"",
"\"",
"+",
"azureProfileJSON",
")",
"\n",
"}"
] | // ProfilePath returns the path where the Azure Profile is stored from the Azure CLI | [
"ProfilePath",
"returns",
"the",
"path",
"where",
"the",
"Azure",
"Profile",
"is",
"stored",
"from",
"the",
"Azure",
"CLI"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/profile.go#L55-L60 |
152,621 | Azure/go-autorest | autorest/azure/cli/profile.go | LoadProfile | func LoadProfile(path string) (result Profile, err error) {
var contents []byte
contents, err = ioutil.ReadFile(path)
if err != nil {
err = fmt.Errorf("failed to open file (%s) while loading token: %v", path, err)
return
}
reader := utfbom.SkipOnly(bytes.NewReader(contents))
dec := json.NewDecoder(reader)
if err = dec.Decode(&result); err != nil {
err = fmt.Errorf("failed to decode contents of file (%s) into a Profile representation: %v", path, err)
return
}
return
} | go | func LoadProfile(path string) (result Profile, err error) {
var contents []byte
contents, err = ioutil.ReadFile(path)
if err != nil {
err = fmt.Errorf("failed to open file (%s) while loading token: %v", path, err)
return
}
reader := utfbom.SkipOnly(bytes.NewReader(contents))
dec := json.NewDecoder(reader)
if err = dec.Decode(&result); err != nil {
err = fmt.Errorf("failed to decode contents of file (%s) into a Profile representation: %v", path, err)
return
}
return
} | [
"func",
"LoadProfile",
"(",
"path",
"string",
")",
"(",
"result",
"Profile",
",",
"err",
"error",
")",
"{",
"var",
"contents",
"[",
"]",
"byte",
"\n",
"contents",
",",
"err",
"=",
"ioutil",
".",
"ReadFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"reader",
":=",
"utfbom",
".",
"SkipOnly",
"(",
"bytes",
".",
"NewReader",
"(",
"contents",
")",
")",
"\n\n",
"dec",
":=",
"json",
".",
"NewDecoder",
"(",
"reader",
")",
"\n",
"if",
"err",
"=",
"dec",
".",
"Decode",
"(",
"&",
"result",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // LoadProfile restores a Profile object from a file located at 'path'. | [
"LoadProfile",
"restores",
"a",
"Profile",
"object",
"from",
"a",
"file",
"located",
"at",
"path",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/profile.go#L63-L79 |
152,622 | Azure/go-autorest | autorest/autorest.go | ResponseHasStatusCode | func ResponseHasStatusCode(resp *http.Response, codes ...int) bool {
if resp == nil {
return false
}
return containsInt(codes, resp.StatusCode)
} | go | func ResponseHasStatusCode(resp *http.Response, codes ...int) bool {
if resp == nil {
return false
}
return containsInt(codes, resp.StatusCode)
} | [
"func",
"ResponseHasStatusCode",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"codes",
"...",
"int",
")",
"bool",
"{",
"if",
"resp",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"containsInt",
"(",
"codes",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}"
] | // ResponseHasStatusCode returns true if the status code in the HTTP Response is in the passed set
// and false otherwise. | [
"ResponseHasStatusCode",
"returns",
"true",
"if",
"the",
"status",
"code",
"in",
"the",
"HTTP",
"Response",
"is",
"in",
"the",
"passed",
"set",
"and",
"false",
"otherwise",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/autorest.go#L90-L95 |
152,623 | Azure/go-autorest | autorest/autorest.go | GetRetryAfter | func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration {
retry := resp.Header.Get(HeaderRetryAfter)
if retry == "" {
return defaultDelay
}
d, err := time.ParseDuration(retry + "s")
if err != nil {
return defaultDelay
}
return d
} | go | func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration {
retry := resp.Header.Get(HeaderRetryAfter)
if retry == "" {
return defaultDelay
}
d, err := time.ParseDuration(retry + "s")
if err != nil {
return defaultDelay
}
return d
} | [
"func",
"GetRetryAfter",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"defaultDelay",
"time",
".",
"Duration",
")",
"time",
".",
"Duration",
"{",
"retry",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"HeaderRetryAfter",
")",
"\n",
"if",
"retry",
"==",
"\"",
"\"",
"{",
"return",
"defaultDelay",
"\n",
"}",
"\n\n",
"d",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"retry",
"+",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"defaultDelay",
"\n",
"}",
"\n\n",
"return",
"d",
"\n",
"}"
] | // GetRetryAfter extracts the retry delay from the Retry-After header of the passed response. If
// the header is absent or is malformed, it will return the supplied default delay time.Duration. | [
"GetRetryAfter",
"extracts",
"the",
"retry",
"delay",
"from",
"the",
"Retry",
"-",
"After",
"header",
"of",
"the",
"passed",
"response",
".",
"If",
"the",
"header",
"is",
"absent",
"or",
"is",
"malformed",
"it",
"will",
"return",
"the",
"supplied",
"default",
"delay",
"time",
".",
"Duration",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/autorest.go#L104-L116 |
152,624 | Azure/go-autorest | autorest/autorest.go | NewPollingRequest | func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) {
location := GetLocation(resp)
if location == "" {
return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling")
}
req, err := Prepare(&http.Request{Cancel: cancel},
AsGet(),
WithBaseURL(location))
if err != nil {
return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location)
}
return req, nil
} | go | func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) {
location := GetLocation(resp)
if location == "" {
return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling")
}
req, err := Prepare(&http.Request{Cancel: cancel},
AsGet(),
WithBaseURL(location))
if err != nil {
return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location)
}
return req, nil
} | [
"func",
"NewPollingRequest",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"cancel",
"<-",
"chan",
"struct",
"{",
"}",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"location",
":=",
"GetLocation",
"(",
"resp",
")",
"\n",
"if",
"location",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"NewErrorWithResponse",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"resp",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"Prepare",
"(",
"&",
"http",
".",
"Request",
"{",
"Cancel",
":",
"cancel",
"}",
",",
"AsGet",
"(",
")",
",",
"WithBaseURL",
"(",
"location",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"NewErrorWithError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
",",
"\"",
"\"",
",",
"location",
")",
"\n",
"}",
"\n\n",
"return",
"req",
",",
"nil",
"\n",
"}"
] | // NewPollingRequest allocates and returns a new http.Request to poll for the passed response. | [
"NewPollingRequest",
"allocates",
"and",
"returns",
"a",
"new",
"http",
".",
"Request",
"to",
"poll",
"for",
"the",
"passed",
"response",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/autorest.go#L119-L133 |
152,625 | Azure/go-autorest | autorest/autorest.go | NewPollingRequestWithContext | func NewPollingRequestWithContext(ctx context.Context, resp *http.Response) (*http.Request, error) {
location := GetLocation(resp)
if location == "" {
return nil, NewErrorWithResponse("autorest", "NewPollingRequestWithContext", resp, "Location header missing from response that requires polling")
}
req, err := Prepare((&http.Request{}).WithContext(ctx),
AsGet(),
WithBaseURL(location))
if err != nil {
return nil, NewErrorWithError(err, "autorest", "NewPollingRequestWithContext", nil, "Failure creating poll request to %s", location)
}
return req, nil
} | go | func NewPollingRequestWithContext(ctx context.Context, resp *http.Response) (*http.Request, error) {
location := GetLocation(resp)
if location == "" {
return nil, NewErrorWithResponse("autorest", "NewPollingRequestWithContext", resp, "Location header missing from response that requires polling")
}
req, err := Prepare((&http.Request{}).WithContext(ctx),
AsGet(),
WithBaseURL(location))
if err != nil {
return nil, NewErrorWithError(err, "autorest", "NewPollingRequestWithContext", nil, "Failure creating poll request to %s", location)
}
return req, nil
} | [
"func",
"NewPollingRequestWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"*",
"http",
".",
"Request",
",",
"error",
")",
"{",
"location",
":=",
"GetLocation",
"(",
"resp",
")",
"\n",
"if",
"location",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"NewErrorWithResponse",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"resp",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"Prepare",
"(",
"(",
"&",
"http",
".",
"Request",
"{",
"}",
")",
".",
"WithContext",
"(",
"ctx",
")",
",",
"AsGet",
"(",
")",
",",
"WithBaseURL",
"(",
"location",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"NewErrorWithError",
"(",
"err",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
",",
"\"",
"\"",
",",
"location",
")",
"\n",
"}",
"\n\n",
"return",
"req",
",",
"nil",
"\n",
"}"
] | // NewPollingRequestWithContext allocates and returns a new http.Request with the specified context to poll for the passed response. | [
"NewPollingRequestWithContext",
"allocates",
"and",
"returns",
"a",
"new",
"http",
".",
"Request",
"with",
"the",
"specified",
"context",
"to",
"poll",
"for",
"the",
"passed",
"response",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/autorest.go#L136-L150 |
152,626 | Azure/go-autorest | autorest/error.go | NewError | func NewError(packageType string, method string, message string, args ...interface{}) DetailedError {
return NewErrorWithError(nil, packageType, method, nil, message, args...)
} | go | func NewError(packageType string, method string, message string, args ...interface{}) DetailedError {
return NewErrorWithError(nil, packageType, method, nil, message, args...)
} | [
"func",
"NewError",
"(",
"packageType",
"string",
",",
"method",
"string",
",",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"DetailedError",
"{",
"return",
"NewErrorWithError",
"(",
"nil",
",",
"packageType",
",",
"method",
",",
"nil",
",",
"message",
",",
"args",
"...",
")",
"\n",
"}"
] | // NewError creates a new Error conforming object from the passed packageType, method, and
// message. message is treated as a format string to which the optional args apply. | [
"NewError",
"creates",
"a",
"new",
"Error",
"conforming",
"object",
"from",
"the",
"passed",
"packageType",
"method",
"and",
"message",
".",
"message",
"is",
"treated",
"as",
"a",
"format",
"string",
"to",
"which",
"the",
"optional",
"args",
"apply",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/error.go#L55-L57 |
152,627 | Azure/go-autorest | autorest/date/utility.go | ParseTime | func ParseTime(format string, t string) (d time.Time, err error) {
return time.Parse(format, strings.ToUpper(t))
} | go | func ParseTime(format string, t string) (d time.Time, err error) {
return time.Parse(format, strings.ToUpper(t))
} | [
"func",
"ParseTime",
"(",
"format",
"string",
",",
"t",
"string",
")",
"(",
"d",
"time",
".",
"Time",
",",
"err",
"error",
")",
"{",
"return",
"time",
".",
"Parse",
"(",
"format",
",",
"strings",
".",
"ToUpper",
"(",
"t",
")",
")",
"\n",
"}"
] | // ParseTime to parse Time string to specified format. | [
"ParseTime",
"to",
"parse",
"Time",
"string",
"to",
"specified",
"format",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/utility.go#L23-L25 |
152,628 | Azure/go-autorest | autorest/adal/config.go | NewOAuthConfig | func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) {
apiVer := "1.0"
return NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID, &apiVer)
} | go | func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) {
apiVer := "1.0"
return NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID, &apiVer)
} | [
"func",
"NewOAuthConfig",
"(",
"activeDirectoryEndpoint",
",",
"tenantID",
"string",
")",
"(",
"*",
"OAuthConfig",
",",
"error",
")",
"{",
"apiVer",
":=",
"\"",
"\"",
"\n",
"return",
"NewOAuthConfigWithAPIVersion",
"(",
"activeDirectoryEndpoint",
",",
"tenantID",
",",
"&",
"apiVer",
")",
"\n",
"}"
] | // NewOAuthConfig returns an OAuthConfig with tenant specific urls | [
"NewOAuthConfig",
"returns",
"an",
"OAuthConfig",
"with",
"tenant",
"specific",
"urls"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/config.go#L44-L47 |
152,629 | Azure/go-autorest | autorest/adal/config.go | NewOAuthConfigWithAPIVersion | func NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID string, apiVersion *string) (*OAuthConfig, error) {
if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil {
return nil, err
}
api := ""
// it's legal for tenantID to be empty so don't validate it
if apiVersion != nil {
if err := validateStringParam(*apiVersion, "apiVersion"); err != nil {
return nil, err
}
api = fmt.Sprintf("?api-version=%s", *apiVersion)
}
const activeDirectoryEndpointTemplate = "%s/oauth2/%s%s"
u, err := url.Parse(activeDirectoryEndpoint)
if err != nil {
return nil, err
}
authorityURL, err := u.Parse(tenantID)
if err != nil {
return nil, err
}
authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", api))
if err != nil {
return nil, err
}
tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", api))
if err != nil {
return nil, err
}
deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", api))
if err != nil {
return nil, err
}
return &OAuthConfig{
AuthorityEndpoint: *authorityURL,
AuthorizeEndpoint: *authorizeURL,
TokenEndpoint: *tokenURL,
DeviceCodeEndpoint: *deviceCodeURL,
}, nil
} | go | func NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID string, apiVersion *string) (*OAuthConfig, error) {
if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil {
return nil, err
}
api := ""
// it's legal for tenantID to be empty so don't validate it
if apiVersion != nil {
if err := validateStringParam(*apiVersion, "apiVersion"); err != nil {
return nil, err
}
api = fmt.Sprintf("?api-version=%s", *apiVersion)
}
const activeDirectoryEndpointTemplate = "%s/oauth2/%s%s"
u, err := url.Parse(activeDirectoryEndpoint)
if err != nil {
return nil, err
}
authorityURL, err := u.Parse(tenantID)
if err != nil {
return nil, err
}
authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", api))
if err != nil {
return nil, err
}
tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", api))
if err != nil {
return nil, err
}
deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", api))
if err != nil {
return nil, err
}
return &OAuthConfig{
AuthorityEndpoint: *authorityURL,
AuthorizeEndpoint: *authorizeURL,
TokenEndpoint: *tokenURL,
DeviceCodeEndpoint: *deviceCodeURL,
}, nil
} | [
"func",
"NewOAuthConfigWithAPIVersion",
"(",
"activeDirectoryEndpoint",
",",
"tenantID",
"string",
",",
"apiVersion",
"*",
"string",
")",
"(",
"*",
"OAuthConfig",
",",
"error",
")",
"{",
"if",
"err",
":=",
"validateStringParam",
"(",
"activeDirectoryEndpoint",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"api",
":=",
"\"",
"\"",
"\n",
"// it's legal for tenantID to be empty so don't validate it",
"if",
"apiVersion",
"!=",
"nil",
"{",
"if",
"err",
":=",
"validateStringParam",
"(",
"*",
"apiVersion",
",",
"\"",
"\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"api",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"*",
"apiVersion",
")",
"\n",
"}",
"\n",
"const",
"activeDirectoryEndpointTemplate",
"=",
"\"",
"\"",
"\n",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"activeDirectoryEndpoint",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"authorityURL",
",",
"err",
":=",
"u",
".",
"Parse",
"(",
"tenantID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"authorizeURL",
",",
"err",
":=",
"u",
".",
"Parse",
"(",
"fmt",
".",
"Sprintf",
"(",
"activeDirectoryEndpointTemplate",
",",
"tenantID",
",",
"\"",
"\"",
",",
"api",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"tokenURL",
",",
"err",
":=",
"u",
".",
"Parse",
"(",
"fmt",
".",
"Sprintf",
"(",
"activeDirectoryEndpointTemplate",
",",
"tenantID",
",",
"\"",
"\"",
",",
"api",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"deviceCodeURL",
",",
"err",
":=",
"u",
".",
"Parse",
"(",
"fmt",
".",
"Sprintf",
"(",
"activeDirectoryEndpointTemplate",
",",
"tenantID",
",",
"\"",
"\"",
",",
"api",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"OAuthConfig",
"{",
"AuthorityEndpoint",
":",
"*",
"authorityURL",
",",
"AuthorizeEndpoint",
":",
"*",
"authorizeURL",
",",
"TokenEndpoint",
":",
"*",
"tokenURL",
",",
"DeviceCodeEndpoint",
":",
"*",
"deviceCodeURL",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewOAuthConfigWithAPIVersion returns an OAuthConfig with tenant specific urls.
// If apiVersion is not nil the "api-version" query parameter will be appended to the endpoint URLs with the specified value. | [
"NewOAuthConfigWithAPIVersion",
"returns",
"an",
"OAuthConfig",
"with",
"tenant",
"specific",
"urls",
".",
"If",
"apiVersion",
"is",
"not",
"nil",
"the",
"api",
"-",
"version",
"query",
"parameter",
"will",
"be",
"appended",
"to",
"the",
"endpoint",
"URLs",
"with",
"the",
"specified",
"value",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/config.go#L51-L91 |
152,630 | Azure/go-autorest | autorest/adal/devicetoken.go | InitiateDeviceAuth | func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) {
v := url.Values{
"client_id": []string{clientID},
"resource": []string{resource},
}
s := v.Encode()
body := ioutil.NopCloser(strings.NewReader(s))
req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error())
}
req.ContentLength = int64(len(s))
req.Header.Set(contentType, mimeTypeFormPost)
resp, err := sender.Do(req)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error())
}
defer resp.Body.Close()
rb, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error())
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK)
}
if len(strings.Trim(string(rb), " ")) == 0 {
return nil, ErrDeviceCodeEmpty
}
var code DeviceCode
err = json.Unmarshal(rb, &code)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error())
}
code.ClientID = clientID
code.Resource = resource
code.OAuthConfig = oauthConfig
return &code, nil
} | go | func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) {
v := url.Values{
"client_id": []string{clientID},
"resource": []string{resource},
}
s := v.Encode()
body := ioutil.NopCloser(strings.NewReader(s))
req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error())
}
req.ContentLength = int64(len(s))
req.Header.Set(contentType, mimeTypeFormPost)
resp, err := sender.Do(req)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error())
}
defer resp.Body.Close()
rb, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error())
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK)
}
if len(strings.Trim(string(rb), " ")) == 0 {
return nil, ErrDeviceCodeEmpty
}
var code DeviceCode
err = json.Unmarshal(rb, &code)
if err != nil {
return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error())
}
code.ClientID = clientID
code.Resource = resource
code.OAuthConfig = oauthConfig
return &code, nil
} | [
"func",
"InitiateDeviceAuth",
"(",
"sender",
"Sender",
",",
"oauthConfig",
"OAuthConfig",
",",
"clientID",
",",
"resource",
"string",
")",
"(",
"*",
"DeviceCode",
",",
"error",
")",
"{",
"v",
":=",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"clientID",
"}",
",",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"resource",
"}",
",",
"}",
"\n\n",
"s",
":=",
"v",
".",
"Encode",
"(",
")",
"\n",
"body",
":=",
"ioutil",
".",
"NopCloser",
"(",
"strings",
".",
"NewReader",
"(",
"s",
")",
")",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"http",
".",
"MethodPost",
",",
"oauthConfig",
".",
"DeviceCodeEndpoint",
".",
"String",
"(",
")",
",",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"logPrefix",
",",
"errCodeSendingFails",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"req",
".",
"ContentLength",
"=",
"int64",
"(",
"len",
"(",
"s",
")",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"contentType",
",",
"mimeTypeFormPost",
")",
"\n",
"resp",
",",
"err",
":=",
"sender",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"logPrefix",
",",
"errCodeSendingFails",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"rb",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"logPrefix",
",",
"errCodeHandlingFails",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"logPrefix",
",",
"errCodeHandlingFails",
",",
"errStatusNotOK",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"strings",
".",
"Trim",
"(",
"string",
"(",
"rb",
")",
",",
"\"",
"\"",
")",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"ErrDeviceCodeEmpty",
"\n",
"}",
"\n\n",
"var",
"code",
"DeviceCode",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"rb",
",",
"&",
"code",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"logPrefix",
",",
"errCodeHandlingFails",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"code",
".",
"ClientID",
"=",
"clientID",
"\n",
"code",
".",
"Resource",
"=",
"resource",
"\n",
"code",
".",
"OAuthConfig",
"=",
"oauthConfig",
"\n\n",
"return",
"&",
"code",
",",
"nil",
"\n",
"}"
] | // InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode
// that can be used with CheckForUserCompletion or WaitForUserCompletion. | [
"InitiateDeviceAuth",
"initiates",
"a",
"device",
"auth",
"flow",
".",
"It",
"returns",
"a",
"DeviceCode",
"that",
"can",
"be",
"used",
"with",
"CheckForUserCompletion",
"or",
"WaitForUserCompletion",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/devicetoken.go#L104-L150 |
152,631 | Azure/go-autorest | autorest/adal/devicetoken.go | WaitForUserCompletion | func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) {
intervalDuration := time.Duration(*code.Interval) * time.Second
waitDuration := intervalDuration
for {
token, err := CheckForUserCompletion(sender, code)
if err == nil {
return token, nil
}
switch err {
case ErrDeviceSlowDown:
waitDuration += waitDuration
case ErrDeviceAuthorizationPending:
// noop
default: // everything else is "fatal" to us
return nil, err
}
if waitDuration > (intervalDuration * 3) {
return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix)
}
time.Sleep(waitDuration)
}
} | go | func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) {
intervalDuration := time.Duration(*code.Interval) * time.Second
waitDuration := intervalDuration
for {
token, err := CheckForUserCompletion(sender, code)
if err == nil {
return token, nil
}
switch err {
case ErrDeviceSlowDown:
waitDuration += waitDuration
case ErrDeviceAuthorizationPending:
// noop
default: // everything else is "fatal" to us
return nil, err
}
if waitDuration > (intervalDuration * 3) {
return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix)
}
time.Sleep(waitDuration)
}
} | [
"func",
"WaitForUserCompletion",
"(",
"sender",
"Sender",
",",
"code",
"*",
"DeviceCode",
")",
"(",
"*",
"Token",
",",
"error",
")",
"{",
"intervalDuration",
":=",
"time",
".",
"Duration",
"(",
"*",
"code",
".",
"Interval",
")",
"*",
"time",
".",
"Second",
"\n",
"waitDuration",
":=",
"intervalDuration",
"\n\n",
"for",
"{",
"token",
",",
"err",
":=",
"CheckForUserCompletion",
"(",
"sender",
",",
"code",
")",
"\n\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"token",
",",
"nil",
"\n",
"}",
"\n\n",
"switch",
"err",
"{",
"case",
"ErrDeviceSlowDown",
":",
"waitDuration",
"+=",
"waitDuration",
"\n",
"case",
"ErrDeviceAuthorizationPending",
":",
"// noop",
"default",
":",
"// everything else is \"fatal\" to us",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"waitDuration",
">",
"(",
"intervalDuration",
"*",
"3",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"logPrefix",
")",
"\n",
"}",
"\n\n",
"time",
".",
"Sleep",
"(",
"waitDuration",
")",
"\n",
"}",
"\n",
"}"
] | // WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs.
// This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. | [
"WaitForUserCompletion",
"calls",
"CheckForUserCompletion",
"repeatedly",
"until",
"a",
"token",
"is",
"granted",
"or",
"an",
"error",
"state",
"occurs",
".",
"This",
"prevents",
"the",
"user",
"from",
"looping",
"and",
"checking",
"against",
"ErrDeviceAuthorizationPending",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/adal/devicetoken.go#L216-L242 |
152,632 | Azure/go-autorest | autorest/date/unixtime.go | Duration | func (t UnixTime) Duration() time.Duration {
return time.Time(t).Sub(unixEpoch)
} | go | func (t UnixTime) Duration() time.Duration {
return time.Time(t).Sub(unixEpoch)
} | [
"func",
"(",
"t",
"UnixTime",
")",
"Duration",
"(",
")",
"time",
".",
"Duration",
"{",
"return",
"time",
".",
"Time",
"(",
"t",
")",
".",
"Sub",
"(",
"unixEpoch",
")",
"\n",
"}"
] | // Duration returns the time as a Duration since the UnixEpoch. | [
"Duration",
"returns",
"the",
"time",
"as",
"a",
"Duration",
"since",
"the",
"UnixEpoch",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L32-L34 |
152,633 | Azure/go-autorest | autorest/date/unixtime.go | NewUnixTimeFromSeconds | func NewUnixTimeFromSeconds(seconds float64) UnixTime {
return NewUnixTimeFromDuration(time.Duration(seconds * float64(time.Second)))
} | go | func NewUnixTimeFromSeconds(seconds float64) UnixTime {
return NewUnixTimeFromDuration(time.Duration(seconds * float64(time.Second)))
} | [
"func",
"NewUnixTimeFromSeconds",
"(",
"seconds",
"float64",
")",
"UnixTime",
"{",
"return",
"NewUnixTimeFromDuration",
"(",
"time",
".",
"Duration",
"(",
"seconds",
"*",
"float64",
"(",
"time",
".",
"Second",
")",
")",
")",
"\n",
"}"
] | // NewUnixTimeFromSeconds creates a UnixTime as a number of seconds from the UnixEpoch. | [
"NewUnixTimeFromSeconds",
"creates",
"a",
"UnixTime",
"as",
"a",
"number",
"of",
"seconds",
"from",
"the",
"UnixEpoch",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L37-L39 |
152,634 | Azure/go-autorest | autorest/date/unixtime.go | UnmarshalJSON | func (t *UnixTime) UnmarshalJSON(text []byte) error {
dec := json.NewDecoder(bytes.NewReader(text))
var secondsSinceEpoch float64
if err := dec.Decode(&secondsSinceEpoch); err != nil {
return err
}
*t = NewUnixTimeFromSeconds(secondsSinceEpoch)
return nil
} | go | func (t *UnixTime) UnmarshalJSON(text []byte) error {
dec := json.NewDecoder(bytes.NewReader(text))
var secondsSinceEpoch float64
if err := dec.Decode(&secondsSinceEpoch); err != nil {
return err
}
*t = NewUnixTimeFromSeconds(secondsSinceEpoch)
return nil
} | [
"func",
"(",
"t",
"*",
"UnixTime",
")",
"UnmarshalJSON",
"(",
"text",
"[",
"]",
"byte",
")",
"error",
"{",
"dec",
":=",
"json",
".",
"NewDecoder",
"(",
"bytes",
".",
"NewReader",
"(",
"text",
")",
")",
"\n\n",
"var",
"secondsSinceEpoch",
"float64",
"\n",
"if",
"err",
":=",
"dec",
".",
"Decode",
"(",
"&",
"secondsSinceEpoch",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"*",
"t",
"=",
"NewUnixTimeFromSeconds",
"(",
"secondsSinceEpoch",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON reconstitures a UnixTime saved as a JSON number of the number of seconds since
// midnight January 1st, 1970. | [
"UnmarshalJSON",
"reconstitures",
"a",
"UnixTime",
"saved",
"as",
"a",
"JSON",
"number",
"of",
"the",
"number",
"of",
"seconds",
"since",
"midnight",
"January",
"1st",
"1970",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L70-L81 |
152,635 | Azure/go-autorest | autorest/date/unixtime.go | MarshalText | func (t UnixTime) MarshalText() ([]byte, error) {
cast := time.Time(t)
return cast.MarshalText()
} | go | func (t UnixTime) MarshalText() ([]byte, error) {
cast := time.Time(t)
return cast.MarshalText()
} | [
"func",
"(",
"t",
"UnixTime",
")",
"MarshalText",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"cast",
":=",
"time",
".",
"Time",
"(",
"t",
")",
"\n",
"return",
"cast",
".",
"MarshalText",
"(",
")",
"\n",
"}"
] | // MarshalText stores the number of seconds since the Unix Epoch as a textual floating point number. | [
"MarshalText",
"stores",
"the",
"number",
"of",
"seconds",
"since",
"the",
"Unix",
"Epoch",
"as",
"a",
"textual",
"floating",
"point",
"number",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L84-L87 |
152,636 | Azure/go-autorest | autorest/date/unixtime.go | UnmarshalText | func (t *UnixTime) UnmarshalText(raw []byte) error {
var unmarshaled time.Time
if err := unmarshaled.UnmarshalText(raw); err != nil {
return err
}
*t = UnixTime(unmarshaled)
return nil
} | go | func (t *UnixTime) UnmarshalText(raw []byte) error {
var unmarshaled time.Time
if err := unmarshaled.UnmarshalText(raw); err != nil {
return err
}
*t = UnixTime(unmarshaled)
return nil
} | [
"func",
"(",
"t",
"*",
"UnixTime",
")",
"UnmarshalText",
"(",
"raw",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"unmarshaled",
"time",
".",
"Time",
"\n\n",
"if",
"err",
":=",
"unmarshaled",
".",
"UnmarshalText",
"(",
"raw",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"*",
"t",
"=",
"UnixTime",
"(",
"unmarshaled",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalText populates a UnixTime with a value stored textually as a floating point number of seconds since the Unix Epoch. | [
"UnmarshalText",
"populates",
"a",
"UnixTime",
"with",
"a",
"value",
"stored",
"textually",
"as",
"a",
"floating",
"point",
"number",
"of",
"seconds",
"since",
"the",
"Unix",
"Epoch",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L90-L99 |
152,637 | Azure/go-autorest | autorest/date/unixtime.go | MarshalBinary | func (t UnixTime) MarshalBinary() ([]byte, error) {
buf := &bytes.Buffer{}
payload := int64(t.Duration())
if err := binary.Write(buf, binary.LittleEndian, &payload); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | go | func (t UnixTime) MarshalBinary() ([]byte, error) {
buf := &bytes.Buffer{}
payload := int64(t.Duration())
if err := binary.Write(buf, binary.LittleEndian, &payload); err != nil {
return nil, err
}
return buf.Bytes(), nil
} | [
"func",
"(",
"t",
"UnixTime",
")",
"MarshalBinary",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n\n",
"payload",
":=",
"int64",
"(",
"t",
".",
"Duration",
"(",
")",
")",
"\n\n",
"if",
"err",
":=",
"binary",
".",
"Write",
"(",
"buf",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"payload",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // MarshalBinary converts a UnixTime into a binary.LittleEndian float64 of nanoseconds since the epoch. | [
"MarshalBinary",
"converts",
"a",
"UnixTime",
"into",
"a",
"binary",
".",
"LittleEndian",
"float64",
"of",
"nanoseconds",
"since",
"the",
"epoch",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L102-L112 |
152,638 | Azure/go-autorest | autorest/date/unixtime.go | UnmarshalBinary | func (t *UnixTime) UnmarshalBinary(raw []byte) error {
var nanosecondsSinceEpoch int64
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &nanosecondsSinceEpoch); err != nil {
return err
}
*t = NewUnixTimeFromNanoseconds(nanosecondsSinceEpoch)
return nil
} | go | func (t *UnixTime) UnmarshalBinary(raw []byte) error {
var nanosecondsSinceEpoch int64
if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &nanosecondsSinceEpoch); err != nil {
return err
}
*t = NewUnixTimeFromNanoseconds(nanosecondsSinceEpoch)
return nil
} | [
"func",
"(",
"t",
"*",
"UnixTime",
")",
"UnmarshalBinary",
"(",
"raw",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"nanosecondsSinceEpoch",
"int64",
"\n\n",
"if",
"err",
":=",
"binary",
".",
"Read",
"(",
"bytes",
".",
"NewReader",
"(",
"raw",
")",
",",
"binary",
".",
"LittleEndian",
",",
"&",
"nanosecondsSinceEpoch",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"*",
"t",
"=",
"NewUnixTimeFromNanoseconds",
"(",
"nanosecondsSinceEpoch",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalBinary converts a from a binary.LittleEndian float64 of nanoseconds since the epoch into a UnixTime. | [
"UnmarshalBinary",
"converts",
"a",
"from",
"a",
"binary",
".",
"LittleEndian",
"float64",
"of",
"nanoseconds",
"since",
"the",
"epoch",
"into",
"a",
"UnixTime",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/unixtime.go#L115-L123 |
152,639 | Azure/go-autorest | autorest/to/convert.go | StringMap | func StringMap(msp map[string]*string) map[string]string {
ms := make(map[string]string, len(msp))
for k, sp := range msp {
if sp != nil {
ms[k] = *sp
} else {
ms[k] = ""
}
}
return ms
} | go | func StringMap(msp map[string]*string) map[string]string {
ms := make(map[string]string, len(msp))
for k, sp := range msp {
if sp != nil {
ms[k] = *sp
} else {
ms[k] = ""
}
}
return ms
} | [
"func",
"StringMap",
"(",
"msp",
"map",
"[",
"string",
"]",
"*",
"string",
")",
"map",
"[",
"string",
"]",
"string",
"{",
"ms",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"len",
"(",
"msp",
")",
")",
"\n",
"for",
"k",
",",
"sp",
":=",
"range",
"msp",
"{",
"if",
"sp",
"!=",
"nil",
"{",
"ms",
"[",
"k",
"]",
"=",
"*",
"sp",
"\n",
"}",
"else",
"{",
"ms",
"[",
"k",
"]",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ms",
"\n",
"}"
] | // StringMap returns a map of strings built from the map of string pointers. The empty string is
// used for nil pointers. | [
"StringMap",
"returns",
"a",
"map",
"of",
"strings",
"built",
"from",
"the",
"map",
"of",
"string",
"pointers",
".",
"The",
"empty",
"string",
"is",
"used",
"for",
"nil",
"pointers",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/to/convert.go#L50-L60 |
152,640 | Azure/go-autorest | autorest/to/convert.go | StringMapPtr | func StringMapPtr(ms map[string]string) *map[string]*string {
msp := make(map[string]*string, len(ms))
for k, s := range ms {
msp[k] = StringPtr(s)
}
return &msp
} | go | func StringMapPtr(ms map[string]string) *map[string]*string {
msp := make(map[string]*string, len(ms))
for k, s := range ms {
msp[k] = StringPtr(s)
}
return &msp
} | [
"func",
"StringMapPtr",
"(",
"ms",
"map",
"[",
"string",
"]",
"string",
")",
"*",
"map",
"[",
"string",
"]",
"*",
"string",
"{",
"msp",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"string",
",",
"len",
"(",
"ms",
")",
")",
"\n",
"for",
"k",
",",
"s",
":=",
"range",
"ms",
"{",
"msp",
"[",
"k",
"]",
"=",
"StringPtr",
"(",
"s",
")",
"\n",
"}",
"\n",
"return",
"&",
"msp",
"\n",
"}"
] | // StringMapPtr returns a pointer to a map of string pointers built from the passed map of strings. | [
"StringMapPtr",
"returns",
"a",
"pointer",
"to",
"a",
"map",
"of",
"string",
"pointers",
"built",
"from",
"the",
"passed",
"map",
"of",
"strings",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/to/convert.go#L63-L69 |
152,641 | Azure/go-autorest | autorest/azure/cli/token.go | ToADALToken | func (t Token) ToADALToken() (converted adal.Token, err error) {
tokenExpirationDate, err := ParseExpirationDate(t.ExpiresOn)
if err != nil {
err = fmt.Errorf("Error parsing Token Expiration Date %q: %+v", t.ExpiresOn, err)
return
}
difference := tokenExpirationDate.Sub(date.UnixEpoch())
converted = adal.Token{
AccessToken: t.AccessToken,
Type: t.TokenType,
ExpiresIn: "3600",
ExpiresOn: json.Number(strconv.Itoa(int(difference.Seconds()))),
RefreshToken: t.RefreshToken,
Resource: t.Resource,
}
return
} | go | func (t Token) ToADALToken() (converted adal.Token, err error) {
tokenExpirationDate, err := ParseExpirationDate(t.ExpiresOn)
if err != nil {
err = fmt.Errorf("Error parsing Token Expiration Date %q: %+v", t.ExpiresOn, err)
return
}
difference := tokenExpirationDate.Sub(date.UnixEpoch())
converted = adal.Token{
AccessToken: t.AccessToken,
Type: t.TokenType,
ExpiresIn: "3600",
ExpiresOn: json.Number(strconv.Itoa(int(difference.Seconds()))),
RefreshToken: t.RefreshToken,
Resource: t.Resource,
}
return
} | [
"func",
"(",
"t",
"Token",
")",
"ToADALToken",
"(",
")",
"(",
"converted",
"adal",
".",
"Token",
",",
"err",
"error",
")",
"{",
"tokenExpirationDate",
",",
"err",
":=",
"ParseExpirationDate",
"(",
"t",
".",
"ExpiresOn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
".",
"ExpiresOn",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"difference",
":=",
"tokenExpirationDate",
".",
"Sub",
"(",
"date",
".",
"UnixEpoch",
"(",
")",
")",
"\n\n",
"converted",
"=",
"adal",
".",
"Token",
"{",
"AccessToken",
":",
"t",
".",
"AccessToken",
",",
"Type",
":",
"t",
".",
"TokenType",
",",
"ExpiresIn",
":",
"\"",
"\"",
",",
"ExpiresOn",
":",
"json",
".",
"Number",
"(",
"strconv",
".",
"Itoa",
"(",
"int",
"(",
"difference",
".",
"Seconds",
"(",
")",
")",
")",
")",
",",
"RefreshToken",
":",
"t",
".",
"RefreshToken",
",",
"Resource",
":",
"t",
".",
"Resource",
",",
"}",
"\n",
"return",
"\n",
"}"
] | // ToADALToken converts an Azure CLI `Token`` to an `adal.Token`` | [
"ToADALToken",
"converts",
"an",
"Azure",
"CLI",
"Token",
"to",
"an",
"adal",
".",
"Token"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/token.go#L48-L66 |
152,642 | Azure/go-autorest | autorest/azure/cli/token.go | ParseExpirationDate | func ParseExpirationDate(input string) (*time.Time, error) {
// CloudShell (and potentially the Azure CLI in future)
expirationDate, cloudShellErr := time.Parse(time.RFC3339, input)
if cloudShellErr != nil {
// Azure CLI (Python) e.g. 2017-08-31 19:48:57.998857 (plus the local timezone)
const cliFormat = "2006-01-02 15:04:05.999999"
expirationDate, cliErr := time.ParseInLocation(cliFormat, input, time.Local)
if cliErr == nil {
return &expirationDate, nil
}
return nil, fmt.Errorf("Error parsing expiration date %q.\n\nCloudShell Error: \n%+v\n\nCLI Error:\n%+v", input, cloudShellErr, cliErr)
}
return &expirationDate, nil
} | go | func ParseExpirationDate(input string) (*time.Time, error) {
// CloudShell (and potentially the Azure CLI in future)
expirationDate, cloudShellErr := time.Parse(time.RFC3339, input)
if cloudShellErr != nil {
// Azure CLI (Python) e.g. 2017-08-31 19:48:57.998857 (plus the local timezone)
const cliFormat = "2006-01-02 15:04:05.999999"
expirationDate, cliErr := time.ParseInLocation(cliFormat, input, time.Local)
if cliErr == nil {
return &expirationDate, nil
}
return nil, fmt.Errorf("Error parsing expiration date %q.\n\nCloudShell Error: \n%+v\n\nCLI Error:\n%+v", input, cloudShellErr, cliErr)
}
return &expirationDate, nil
} | [
"func",
"ParseExpirationDate",
"(",
"input",
"string",
")",
"(",
"*",
"time",
".",
"Time",
",",
"error",
")",
"{",
"// CloudShell (and potentially the Azure CLI in future)",
"expirationDate",
",",
"cloudShellErr",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"input",
")",
"\n",
"if",
"cloudShellErr",
"!=",
"nil",
"{",
"// Azure CLI (Python) e.g. 2017-08-31 19:48:57.998857 (plus the local timezone)",
"const",
"cliFormat",
"=",
"\"",
"\"",
"\n",
"expirationDate",
",",
"cliErr",
":=",
"time",
".",
"ParseInLocation",
"(",
"cliFormat",
",",
"input",
",",
"time",
".",
"Local",
")",
"\n",
"if",
"cliErr",
"==",
"nil",
"{",
"return",
"&",
"expirationDate",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\n",
"\\n",
"\\n",
"\\n",
"\\n",
"\\n",
"\"",
",",
"input",
",",
"cloudShellErr",
",",
"cliErr",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"expirationDate",
",",
"nil",
"\n",
"}"
] | // ParseExpirationDate parses either a Azure CLI or CloudShell date into a time object | [
"ParseExpirationDate",
"parses",
"either",
"a",
"Azure",
"CLI",
"or",
"CloudShell",
"date",
"into",
"a",
"time",
"object"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/token.go#L85-L100 |
152,643 | Azure/go-autorest | autorest/azure/cli/token.go | LoadTokens | func LoadTokens(path string) ([]Token, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err)
}
defer file.Close()
var tokens []Token
dec := json.NewDecoder(file)
if err = dec.Decode(&tokens); err != nil {
return nil, fmt.Errorf("failed to decode contents of file (%s) into a `cli.Token` representation: %v", path, err)
}
return tokens, nil
} | go | func LoadTokens(path string) ([]Token, error) {
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err)
}
defer file.Close()
var tokens []Token
dec := json.NewDecoder(file)
if err = dec.Decode(&tokens); err != nil {
return nil, fmt.Errorf("failed to decode contents of file (%s) into a `cli.Token` representation: %v", path, err)
}
return tokens, nil
} | [
"func",
"LoadTokens",
"(",
"path",
"string",
")",
"(",
"[",
"]",
"Token",
",",
"error",
")",
"{",
"file",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n\n",
"var",
"tokens",
"[",
"]",
"Token",
"\n\n",
"dec",
":=",
"json",
".",
"NewDecoder",
"(",
"file",
")",
"\n",
"if",
"err",
"=",
"dec",
".",
"Decode",
"(",
"&",
"tokens",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"tokens",
",",
"nil",
"\n",
"}"
] | // LoadTokens restores a set of Token objects from a file located at 'path'. | [
"LoadTokens",
"restores",
"a",
"set",
"of",
"Token",
"objects",
"from",
"a",
"file",
"located",
"at",
"path",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/token.go#L103-L118 |
152,644 | Azure/go-autorest | autorest/azure/cli/token.go | GetTokenFromCLI | func GetTokenFromCLI(resource string) (*Token, error) {
// This is the path that a developer can set to tell this class what the install path for Azure CLI is.
const azureCLIPath = "AzureCLIPath"
// The default install paths are used to find Azure CLI. This is for security, so that any path in the calling program's Path environment is not used to execute Azure CLI.
azureCLIDefaultPathWindows := fmt.Sprintf("%s\\Microsoft SDKs\\Azure\\CLI2\\wbin; %s\\Microsoft SDKs\\Azure\\CLI2\\wbin", os.Getenv("ProgramFiles(x86)"), os.Getenv("ProgramFiles"))
// Default path for non-Windows.
const azureCLIDefaultPath = "/bin:/sbin:/usr/bin:/usr/local/bin"
// Validate resource, since it gets sent as a command line argument to Azure CLI
const invalidResourceErrorTemplate = "Resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed."
match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource)
if err != nil {
return nil, err
}
if !match {
return nil, fmt.Errorf(invalidResourceErrorTemplate, resource)
}
// Execute Azure CLI to get token
var cliCmd *exec.Cmd
if runtime.GOOS == "windows" {
cliCmd = exec.Command(fmt.Sprintf("%s\\system32\\cmd.exe", os.Getenv("windir")))
cliCmd.Env = os.Environ()
cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s;%s", os.Getenv(azureCLIPath), azureCLIDefaultPathWindows))
cliCmd.Args = append(cliCmd.Args, "/c", "az")
} else {
cliCmd = exec.Command("az")
cliCmd.Env = os.Environ()
cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s:%s", os.Getenv(azureCLIPath), azureCLIDefaultPath))
}
cliCmd.Args = append(cliCmd.Args, "account", "get-access-token", "-o", "json", "--resource", resource)
var stderr bytes.Buffer
cliCmd.Stderr = &stderr
output, err := cliCmd.Output()
if err != nil {
return nil, fmt.Errorf("Invoking Azure CLI failed with the following error: %s", stderr.String())
}
tokenResponse := Token{}
err = json.Unmarshal(output, &tokenResponse)
if err != nil {
return nil, err
}
return &tokenResponse, err
} | go | func GetTokenFromCLI(resource string) (*Token, error) {
// This is the path that a developer can set to tell this class what the install path for Azure CLI is.
const azureCLIPath = "AzureCLIPath"
// The default install paths are used to find Azure CLI. This is for security, so that any path in the calling program's Path environment is not used to execute Azure CLI.
azureCLIDefaultPathWindows := fmt.Sprintf("%s\\Microsoft SDKs\\Azure\\CLI2\\wbin; %s\\Microsoft SDKs\\Azure\\CLI2\\wbin", os.Getenv("ProgramFiles(x86)"), os.Getenv("ProgramFiles"))
// Default path for non-Windows.
const azureCLIDefaultPath = "/bin:/sbin:/usr/bin:/usr/local/bin"
// Validate resource, since it gets sent as a command line argument to Azure CLI
const invalidResourceErrorTemplate = "Resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed."
match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource)
if err != nil {
return nil, err
}
if !match {
return nil, fmt.Errorf(invalidResourceErrorTemplate, resource)
}
// Execute Azure CLI to get token
var cliCmd *exec.Cmd
if runtime.GOOS == "windows" {
cliCmd = exec.Command(fmt.Sprintf("%s\\system32\\cmd.exe", os.Getenv("windir")))
cliCmd.Env = os.Environ()
cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s;%s", os.Getenv(azureCLIPath), azureCLIDefaultPathWindows))
cliCmd.Args = append(cliCmd.Args, "/c", "az")
} else {
cliCmd = exec.Command("az")
cliCmd.Env = os.Environ()
cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s:%s", os.Getenv(azureCLIPath), azureCLIDefaultPath))
}
cliCmd.Args = append(cliCmd.Args, "account", "get-access-token", "-o", "json", "--resource", resource)
var stderr bytes.Buffer
cliCmd.Stderr = &stderr
output, err := cliCmd.Output()
if err != nil {
return nil, fmt.Errorf("Invoking Azure CLI failed with the following error: %s", stderr.String())
}
tokenResponse := Token{}
err = json.Unmarshal(output, &tokenResponse)
if err != nil {
return nil, err
}
return &tokenResponse, err
} | [
"func",
"GetTokenFromCLI",
"(",
"resource",
"string",
")",
"(",
"*",
"Token",
",",
"error",
")",
"{",
"// This is the path that a developer can set to tell this class what the install path for Azure CLI is.",
"const",
"azureCLIPath",
"=",
"\"",
"\"",
"\n\n",
"// The default install paths are used to find Azure CLI. This is for security, so that any path in the calling program's Path environment is not used to execute Azure CLI.",
"azureCLIDefaultPathWindows",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\"",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"\n\n",
"// Default path for non-Windows.",
"const",
"azureCLIDefaultPath",
"=",
"\"",
"\"",
"\n\n",
"// Validate resource, since it gets sent as a command line argument to Azure CLI",
"const",
"invalidResourceErrorTemplate",
"=",
"\"",
"\"",
"\n",
"match",
",",
"err",
":=",
"regexp",
".",
"MatchString",
"(",
"\"",
"\"",
",",
"resource",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"match",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"invalidResourceErrorTemplate",
",",
"resource",
")",
"\n",
"}",
"\n\n",
"// Execute Azure CLI to get token",
"var",
"cliCmd",
"*",
"exec",
".",
"Cmd",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
"{",
"cliCmd",
"=",
"exec",
".",
"Command",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\\\",
"\\\\",
"\"",
",",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
")",
"\n",
"cliCmd",
".",
"Env",
"=",
"os",
".",
"Environ",
"(",
")",
"\n",
"cliCmd",
".",
"Env",
"=",
"append",
"(",
"cliCmd",
".",
"Env",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"os",
".",
"Getenv",
"(",
"azureCLIPath",
")",
",",
"azureCLIDefaultPathWindows",
")",
")",
"\n",
"cliCmd",
".",
"Args",
"=",
"append",
"(",
"cliCmd",
".",
"Args",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"cliCmd",
"=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
")",
"\n",
"cliCmd",
".",
"Env",
"=",
"os",
".",
"Environ",
"(",
")",
"\n",
"cliCmd",
".",
"Env",
"=",
"append",
"(",
"cliCmd",
".",
"Env",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"os",
".",
"Getenv",
"(",
"azureCLIPath",
")",
",",
"azureCLIDefaultPath",
")",
")",
"\n",
"}",
"\n",
"cliCmd",
".",
"Args",
"=",
"append",
"(",
"cliCmd",
".",
"Args",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"resource",
")",
"\n\n",
"var",
"stderr",
"bytes",
".",
"Buffer",
"\n",
"cliCmd",
".",
"Stderr",
"=",
"&",
"stderr",
"\n\n",
"output",
",",
"err",
":=",
"cliCmd",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"stderr",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n\n",
"tokenResponse",
":=",
"Token",
"{",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"output",
",",
"&",
"tokenResponse",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"tokenResponse",
",",
"err",
"\n",
"}"
] | // GetTokenFromCLI gets a token using Azure CLI 2.0 for local development scenarios. | [
"GetTokenFromCLI",
"gets",
"a",
"token",
"using",
"Azure",
"CLI",
"2",
".",
"0",
"for",
"local",
"development",
"scenarios",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/cli/token.go#L121-L170 |
152,645 | Azure/go-autorest | autorest/date/date.go | ParseDate | func ParseDate(date string) (d Date, err error) {
return parseDate(date, fullDate)
} | go | func ParseDate(date string) (d Date, err error) {
return parseDate(date, fullDate)
} | [
"func",
"ParseDate",
"(",
"date",
"string",
")",
"(",
"d",
"Date",
",",
"err",
"error",
")",
"{",
"return",
"parseDate",
"(",
"date",
",",
"fullDate",
")",
"\n",
"}"
] | // ParseDate create a new Date from the passed string. | [
"ParseDate",
"create",
"a",
"new",
"Date",
"from",
"the",
"passed",
"string",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/date/date.go#L41-L43 |
152,646 | Azure/go-autorest | autorest/azure/metadata_environment.go | EnvironmentFromURL | func EnvironmentFromURL(resourceManagerEndpoint string, properties ...OverrideProperty) (environment Environment, err error) {
var metadataEnvProperties environmentMetadataInfo
if resourceManagerEndpoint == "" {
return environment, fmt.Errorf("Metadata resource manager endpoint is empty")
}
if metadataEnvProperties, err = retrieveMetadataEnvironment(resourceManagerEndpoint); err != nil {
return environment, err
}
// Give priority to user's override values
overrideProperties(&environment, properties)
if environment.Name == "" {
environment.Name = "HybridEnvironment"
}
stampDNSSuffix := environment.StorageEndpointSuffix
if stampDNSSuffix == "" {
stampDNSSuffix = strings.TrimSuffix(strings.TrimPrefix(strings.Replace(resourceManagerEndpoint, strings.Split(resourceManagerEndpoint, ".")[0], "", 1), "."), "/")
environment.StorageEndpointSuffix = stampDNSSuffix
}
if environment.KeyVaultDNSSuffix == "" {
environment.KeyVaultDNSSuffix = fmt.Sprintf("%s.%s", "vault", stampDNSSuffix)
}
if environment.KeyVaultEndpoint == "" {
environment.KeyVaultEndpoint = fmt.Sprintf("%s%s", "https://", environment.KeyVaultDNSSuffix)
}
if environment.TokenAudience == "" {
environment.TokenAudience = metadataEnvProperties.Authentication.Audiences[0]
}
if environment.ActiveDirectoryEndpoint == "" {
environment.ActiveDirectoryEndpoint = metadataEnvProperties.Authentication.LoginEndpoint
}
if environment.ResourceManagerEndpoint == "" {
environment.ResourceManagerEndpoint = resourceManagerEndpoint
}
if environment.GalleryEndpoint == "" {
environment.GalleryEndpoint = metadataEnvProperties.GalleryEndpoint
}
if environment.GraphEndpoint == "" {
environment.GraphEndpoint = metadataEnvProperties.GraphEndpoint
}
return environment, nil
} | go | func EnvironmentFromURL(resourceManagerEndpoint string, properties ...OverrideProperty) (environment Environment, err error) {
var metadataEnvProperties environmentMetadataInfo
if resourceManagerEndpoint == "" {
return environment, fmt.Errorf("Metadata resource manager endpoint is empty")
}
if metadataEnvProperties, err = retrieveMetadataEnvironment(resourceManagerEndpoint); err != nil {
return environment, err
}
// Give priority to user's override values
overrideProperties(&environment, properties)
if environment.Name == "" {
environment.Name = "HybridEnvironment"
}
stampDNSSuffix := environment.StorageEndpointSuffix
if stampDNSSuffix == "" {
stampDNSSuffix = strings.TrimSuffix(strings.TrimPrefix(strings.Replace(resourceManagerEndpoint, strings.Split(resourceManagerEndpoint, ".")[0], "", 1), "."), "/")
environment.StorageEndpointSuffix = stampDNSSuffix
}
if environment.KeyVaultDNSSuffix == "" {
environment.KeyVaultDNSSuffix = fmt.Sprintf("%s.%s", "vault", stampDNSSuffix)
}
if environment.KeyVaultEndpoint == "" {
environment.KeyVaultEndpoint = fmt.Sprintf("%s%s", "https://", environment.KeyVaultDNSSuffix)
}
if environment.TokenAudience == "" {
environment.TokenAudience = metadataEnvProperties.Authentication.Audiences[0]
}
if environment.ActiveDirectoryEndpoint == "" {
environment.ActiveDirectoryEndpoint = metadataEnvProperties.Authentication.LoginEndpoint
}
if environment.ResourceManagerEndpoint == "" {
environment.ResourceManagerEndpoint = resourceManagerEndpoint
}
if environment.GalleryEndpoint == "" {
environment.GalleryEndpoint = metadataEnvProperties.GalleryEndpoint
}
if environment.GraphEndpoint == "" {
environment.GraphEndpoint = metadataEnvProperties.GraphEndpoint
}
return environment, nil
} | [
"func",
"EnvironmentFromURL",
"(",
"resourceManagerEndpoint",
"string",
",",
"properties",
"...",
"OverrideProperty",
")",
"(",
"environment",
"Environment",
",",
"err",
"error",
")",
"{",
"var",
"metadataEnvProperties",
"environmentMetadataInfo",
"\n\n",
"if",
"resourceManagerEndpoint",
"==",
"\"",
"\"",
"{",
"return",
"environment",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"metadataEnvProperties",
",",
"err",
"=",
"retrieveMetadataEnvironment",
"(",
"resourceManagerEndpoint",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"environment",
",",
"err",
"\n",
"}",
"\n\n",
"// Give priority to user's override values",
"overrideProperties",
"(",
"&",
"environment",
",",
"properties",
")",
"\n\n",
"if",
"environment",
".",
"Name",
"==",
"\"",
"\"",
"{",
"environment",
".",
"Name",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"stampDNSSuffix",
":=",
"environment",
".",
"StorageEndpointSuffix",
"\n",
"if",
"stampDNSSuffix",
"==",
"\"",
"\"",
"{",
"stampDNSSuffix",
"=",
"strings",
".",
"TrimSuffix",
"(",
"strings",
".",
"TrimPrefix",
"(",
"strings",
".",
"Replace",
"(",
"resourceManagerEndpoint",
",",
"strings",
".",
"Split",
"(",
"resourceManagerEndpoint",
",",
"\"",
"\"",
")",
"[",
"0",
"]",
",",
"\"",
"\"",
",",
"1",
")",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"environment",
".",
"StorageEndpointSuffix",
"=",
"stampDNSSuffix",
"\n",
"}",
"\n",
"if",
"environment",
".",
"KeyVaultDNSSuffix",
"==",
"\"",
"\"",
"{",
"environment",
".",
"KeyVaultDNSSuffix",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"stampDNSSuffix",
")",
"\n",
"}",
"\n",
"if",
"environment",
".",
"KeyVaultEndpoint",
"==",
"\"",
"\"",
"{",
"environment",
".",
"KeyVaultEndpoint",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"environment",
".",
"KeyVaultDNSSuffix",
")",
"\n",
"}",
"\n",
"if",
"environment",
".",
"TokenAudience",
"==",
"\"",
"\"",
"{",
"environment",
".",
"TokenAudience",
"=",
"metadataEnvProperties",
".",
"Authentication",
".",
"Audiences",
"[",
"0",
"]",
"\n",
"}",
"\n",
"if",
"environment",
".",
"ActiveDirectoryEndpoint",
"==",
"\"",
"\"",
"{",
"environment",
".",
"ActiveDirectoryEndpoint",
"=",
"metadataEnvProperties",
".",
"Authentication",
".",
"LoginEndpoint",
"\n",
"}",
"\n",
"if",
"environment",
".",
"ResourceManagerEndpoint",
"==",
"\"",
"\"",
"{",
"environment",
".",
"ResourceManagerEndpoint",
"=",
"resourceManagerEndpoint",
"\n",
"}",
"\n",
"if",
"environment",
".",
"GalleryEndpoint",
"==",
"\"",
"\"",
"{",
"environment",
".",
"GalleryEndpoint",
"=",
"metadataEnvProperties",
".",
"GalleryEndpoint",
"\n",
"}",
"\n",
"if",
"environment",
".",
"GraphEndpoint",
"==",
"\"",
"\"",
"{",
"environment",
".",
"GraphEndpoint",
"=",
"metadataEnvProperties",
".",
"GraphEndpoint",
"\n",
"}",
"\n\n",
"return",
"environment",
",",
"nil",
"\n",
"}"
] | // EnvironmentFromURL loads an Environment from a URL
// This function is particularly useful in the Hybrid Cloud model, where one may define their own
// endpoints. | [
"EnvironmentFromURL",
"loads",
"an",
"Environment",
"from",
"a",
"URL",
"This",
"function",
"is",
"particularly",
"useful",
"in",
"the",
"Hybrid",
"Cloud",
"model",
"where",
"one",
"may",
"define",
"their",
"own",
"endpoints",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/metadata_environment.go#L96-L141 |
152,647 | Azure/go-autorest | autorest/azure/async.go | NewFutureFromResponse | func NewFutureFromResponse(resp *http.Response) (Future, error) {
pt, err := createPollingTracker(resp)
return Future{pt: pt}, err
} | go | func NewFutureFromResponse(resp *http.Response) (Future, error) {
pt, err := createPollingTracker(resp)
return Future{pt: pt}, err
} | [
"func",
"NewFutureFromResponse",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"Future",
",",
"error",
")",
"{",
"pt",
",",
"err",
":=",
"createPollingTracker",
"(",
"resp",
")",
"\n",
"return",
"Future",
"{",
"pt",
":",
"pt",
"}",
",",
"err",
"\n",
"}"
] | // NewFutureFromResponse returns a new Future object initialized
// with the initial response from an asynchronous operation. | [
"NewFutureFromResponse",
"returns",
"a",
"new",
"Future",
"object",
"initialized",
"with",
"the",
"initial",
"response",
"from",
"an",
"asynchronous",
"operation",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L53-L56 |
152,648 | Azure/go-autorest | autorest/azure/async.go | Response | func (f Future) Response() *http.Response {
if f.pt == nil {
return nil
}
return f.pt.latestResponse()
} | go | func (f Future) Response() *http.Response {
if f.pt == nil {
return nil
}
return f.pt.latestResponse()
} | [
"func",
"(",
"f",
"Future",
")",
"Response",
"(",
")",
"*",
"http",
".",
"Response",
"{",
"if",
"f",
".",
"pt",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"f",
".",
"pt",
".",
"latestResponse",
"(",
")",
"\n",
"}"
] | // Response returns the last HTTP response. | [
"Response",
"returns",
"the",
"last",
"HTTP",
"response",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L59-L64 |
152,649 | Azure/go-autorest | autorest/azure/async.go | Status | func (f Future) Status() string {
if f.pt == nil {
return ""
}
return f.pt.pollingStatus()
} | go | func (f Future) Status() string {
if f.pt == nil {
return ""
}
return f.pt.pollingStatus()
} | [
"func",
"(",
"f",
"Future",
")",
"Status",
"(",
")",
"string",
"{",
"if",
"f",
".",
"pt",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"f",
".",
"pt",
".",
"pollingStatus",
"(",
")",
"\n",
"}"
] | // Status returns the last status message of the operation. | [
"Status",
"returns",
"the",
"last",
"status",
"message",
"of",
"the",
"operation",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L67-L72 |
152,650 | Azure/go-autorest | autorest/azure/async.go | PollingMethod | func (f Future) PollingMethod() PollingMethodType {
if f.pt == nil {
return PollingUnknown
}
return f.pt.pollingMethod()
} | go | func (f Future) PollingMethod() PollingMethodType {
if f.pt == nil {
return PollingUnknown
}
return f.pt.pollingMethod()
} | [
"func",
"(",
"f",
"Future",
")",
"PollingMethod",
"(",
")",
"PollingMethodType",
"{",
"if",
"f",
".",
"pt",
"==",
"nil",
"{",
"return",
"PollingUnknown",
"\n",
"}",
"\n",
"return",
"f",
".",
"pt",
".",
"pollingMethod",
"(",
")",
"\n",
"}"
] | // PollingMethod returns the method used to monitor the status of the asynchronous operation. | [
"PollingMethod",
"returns",
"the",
"method",
"used",
"to",
"monitor",
"the",
"status",
"of",
"the",
"asynchronous",
"operation",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L75-L80 |
152,651 | Azure/go-autorest | autorest/azure/async.go | DoneWithContext | func (f *Future) DoneWithContext(ctx context.Context, sender autorest.Sender) (done bool, err error) {
ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.DoneWithContext")
defer func() {
sc := -1
resp := f.Response()
if resp != nil {
sc = resp.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
if f.pt == nil {
return false, autorest.NewError("Future", "Done", "future is not initialized")
}
if f.pt.hasTerminated() {
return true, f.pt.pollingError()
}
if err := f.pt.pollForStatus(ctx, sender); err != nil {
return false, err
}
if err := f.pt.checkForErrors(); err != nil {
return f.pt.hasTerminated(), err
}
if err := f.pt.updatePollingState(f.pt.provisioningStateApplicable()); err != nil {
return false, err
}
if err := f.pt.initPollingMethod(); err != nil {
return false, err
}
if err := f.pt.updatePollingMethod(); err != nil {
return false, err
}
return f.pt.hasTerminated(), f.pt.pollingError()
} | go | func (f *Future) DoneWithContext(ctx context.Context, sender autorest.Sender) (done bool, err error) {
ctx = tracing.StartSpan(ctx, "github.com/Azure/go-autorest/autorest/azure/async.DoneWithContext")
defer func() {
sc := -1
resp := f.Response()
if resp != nil {
sc = resp.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
if f.pt == nil {
return false, autorest.NewError("Future", "Done", "future is not initialized")
}
if f.pt.hasTerminated() {
return true, f.pt.pollingError()
}
if err := f.pt.pollForStatus(ctx, sender); err != nil {
return false, err
}
if err := f.pt.checkForErrors(); err != nil {
return f.pt.hasTerminated(), err
}
if err := f.pt.updatePollingState(f.pt.provisioningStateApplicable()); err != nil {
return false, err
}
if err := f.pt.initPollingMethod(); err != nil {
return false, err
}
if err := f.pt.updatePollingMethod(); err != nil {
return false, err
}
return f.pt.hasTerminated(), f.pt.pollingError()
} | [
"func",
"(",
"f",
"*",
"Future",
")",
"DoneWithContext",
"(",
"ctx",
"context",
".",
"Context",
",",
"sender",
"autorest",
".",
"Sender",
")",
"(",
"done",
"bool",
",",
"err",
"error",
")",
"{",
"ctx",
"=",
"tracing",
".",
"StartSpan",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"sc",
":=",
"-",
"1",
"\n",
"resp",
":=",
"f",
".",
"Response",
"(",
")",
"\n",
"if",
"resp",
"!=",
"nil",
"{",
"sc",
"=",
"resp",
".",
"StatusCode",
"\n",
"}",
"\n",
"tracing",
".",
"EndSpan",
"(",
"ctx",
",",
"sc",
",",
"err",
")",
"\n",
"}",
"(",
")",
"\n\n",
"if",
"f",
".",
"pt",
"==",
"nil",
"{",
"return",
"false",
",",
"autorest",
".",
"NewError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"f",
".",
"pt",
".",
"hasTerminated",
"(",
")",
"{",
"return",
"true",
",",
"f",
".",
"pt",
".",
"pollingError",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"pt",
".",
"pollForStatus",
"(",
"ctx",
",",
"sender",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"pt",
".",
"checkForErrors",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"f",
".",
"pt",
".",
"hasTerminated",
"(",
")",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"pt",
".",
"updatePollingState",
"(",
"f",
".",
"pt",
".",
"provisioningStateApplicable",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"pt",
".",
"initPollingMethod",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"f",
".",
"pt",
".",
"updatePollingMethod",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"f",
".",
"pt",
".",
"hasTerminated",
"(",
")",
",",
"f",
".",
"pt",
".",
"pollingError",
"(",
")",
"\n",
"}"
] | // DoneWithContext queries the service to see if the operation has completed. | [
"DoneWithContext",
"queries",
"the",
"service",
"to",
"see",
"if",
"the",
"operation",
"has",
"completed",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L83-L116 |
152,652 | Azure/go-autorest | autorest/azure/async.go | GetPollingDelay | func (f Future) GetPollingDelay() (time.Duration, bool) {
if f.pt == nil {
return 0, false
}
resp := f.pt.latestResponse()
if resp == nil {
return 0, false
}
retry := resp.Header.Get(autorest.HeaderRetryAfter)
if retry == "" {
return 0, false
}
d, err := time.ParseDuration(retry + "s")
if err != nil {
panic(err)
}
return d, true
} | go | func (f Future) GetPollingDelay() (time.Duration, bool) {
if f.pt == nil {
return 0, false
}
resp := f.pt.latestResponse()
if resp == nil {
return 0, false
}
retry := resp.Header.Get(autorest.HeaderRetryAfter)
if retry == "" {
return 0, false
}
d, err := time.ParseDuration(retry + "s")
if err != nil {
panic(err)
}
return d, true
} | [
"func",
"(",
"f",
"Future",
")",
"GetPollingDelay",
"(",
")",
"(",
"time",
".",
"Duration",
",",
"bool",
")",
"{",
"if",
"f",
".",
"pt",
"==",
"nil",
"{",
"return",
"0",
",",
"false",
"\n",
"}",
"\n",
"resp",
":=",
"f",
".",
"pt",
".",
"latestResponse",
"(",
")",
"\n",
"if",
"resp",
"==",
"nil",
"{",
"return",
"0",
",",
"false",
"\n",
"}",
"\n\n",
"retry",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"autorest",
".",
"HeaderRetryAfter",
")",
"\n",
"if",
"retry",
"==",
"\"",
"\"",
"{",
"return",
"0",
",",
"false",
"\n",
"}",
"\n\n",
"d",
",",
"err",
":=",
"time",
".",
"ParseDuration",
"(",
"retry",
"+",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"d",
",",
"true",
"\n",
"}"
] | // GetPollingDelay returns a duration the application should wait before checking
// the status of the asynchronous request and true; this value is returned from
// the service via the Retry-After response header. If the header wasn't returned
// then the function returns the zero-value time.Duration and false. | [
"GetPollingDelay",
"returns",
"a",
"duration",
"the",
"application",
"should",
"wait",
"before",
"checking",
"the",
"status",
"of",
"the",
"asynchronous",
"request",
"and",
"true",
";",
"this",
"value",
"is",
"returned",
"from",
"the",
"service",
"via",
"the",
"Retry",
"-",
"After",
"response",
"header",
".",
"If",
"the",
"header",
"wasn",
"t",
"returned",
"then",
"the",
"function",
"returns",
"the",
"zero",
"-",
"value",
"time",
".",
"Duration",
"and",
"false",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L122-L142 |
152,653 | Azure/go-autorest | autorest/azure/async.go | PollingURL | func (f Future) PollingURL() string {
if f.pt == nil {
return ""
}
return f.pt.pollingURL()
} | go | func (f Future) PollingURL() string {
if f.pt == nil {
return ""
}
return f.pt.pollingURL()
} | [
"func",
"(",
"f",
"Future",
")",
"PollingURL",
"(",
")",
"string",
"{",
"if",
"f",
".",
"pt",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"f",
".",
"pt",
".",
"pollingURL",
"(",
")",
"\n",
"}"
] | // PollingURL returns the URL used for retrieving the status of the long-running operation. | [
"PollingURL",
"returns",
"the",
"URL",
"used",
"for",
"retrieving",
"the",
"status",
"of",
"the",
"long",
"-",
"running",
"operation",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L238-L243 |
152,654 | Azure/go-autorest | autorest/azure/async.go | GetResult | func (f Future) GetResult(sender autorest.Sender) (*http.Response, error) {
if f.pt.finalGetURL() == "" {
// we can end up in this situation if the async operation returns a 200
// with no polling URLs. in that case return the response which should
// contain the JSON payload (only do this for successful terminal cases).
if lr := f.pt.latestResponse(); lr != nil && f.pt.hasSucceeded() {
return lr, nil
}
return nil, autorest.NewError("Future", "GetResult", "missing URL for retrieving result")
}
req, err := http.NewRequest(http.MethodGet, f.pt.finalGetURL(), nil)
if err != nil {
return nil, err
}
return sender.Do(req)
} | go | func (f Future) GetResult(sender autorest.Sender) (*http.Response, error) {
if f.pt.finalGetURL() == "" {
// we can end up in this situation if the async operation returns a 200
// with no polling URLs. in that case return the response which should
// contain the JSON payload (only do this for successful terminal cases).
if lr := f.pt.latestResponse(); lr != nil && f.pt.hasSucceeded() {
return lr, nil
}
return nil, autorest.NewError("Future", "GetResult", "missing URL for retrieving result")
}
req, err := http.NewRequest(http.MethodGet, f.pt.finalGetURL(), nil)
if err != nil {
return nil, err
}
return sender.Do(req)
} | [
"func",
"(",
"f",
"Future",
")",
"GetResult",
"(",
"sender",
"autorest",
".",
"Sender",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"f",
".",
"pt",
".",
"finalGetURL",
"(",
")",
"==",
"\"",
"\"",
"{",
"// we can end up in this situation if the async operation returns a 200",
"// with no polling URLs. in that case return the response which should",
"// contain the JSON payload (only do this for successful terminal cases).",
"if",
"lr",
":=",
"f",
".",
"pt",
".",
"latestResponse",
"(",
")",
";",
"lr",
"!=",
"nil",
"&&",
"f",
".",
"pt",
".",
"hasSucceeded",
"(",
")",
"{",
"return",
"lr",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"autorest",
".",
"NewError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"http",
".",
"MethodGet",
",",
"f",
".",
"pt",
".",
"finalGetURL",
"(",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"sender",
".",
"Do",
"(",
"req",
")",
"\n",
"}"
] | // GetResult should be called once polling has completed successfully.
// It makes the final GET call to retrieve the resultant payload. | [
"GetResult",
"should",
"be",
"called",
"once",
"polling",
"has",
"completed",
"successfully",
".",
"It",
"makes",
"the",
"final",
"GET",
"call",
"to",
"retrieve",
"the",
"resultant",
"payload",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L247-L262 |
152,655 | Azure/go-autorest | autorest/azure/async.go | baseCheckForErrors | func (pt pollingTrackerBase) baseCheckForErrors() error {
// for Azure-AsyncOperations the response body cannot be nil or empty
if pt.Pm == PollingAsyncOperation {
if pt.resp.Body == nil || pt.resp.ContentLength == 0 {
return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "for Azure-AsyncOperation response body cannot be nil")
}
if pt.rawBody["status"] == nil {
return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "missing status property in Azure-AsyncOperation response body")
}
}
return nil
} | go | func (pt pollingTrackerBase) baseCheckForErrors() error {
// for Azure-AsyncOperations the response body cannot be nil or empty
if pt.Pm == PollingAsyncOperation {
if pt.resp.Body == nil || pt.resp.ContentLength == 0 {
return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "for Azure-AsyncOperation response body cannot be nil")
}
if pt.rawBody["status"] == nil {
return autorest.NewError("pollingTrackerBase", "baseCheckForErrors", "missing status property in Azure-AsyncOperation response body")
}
}
return nil
} | [
"func",
"(",
"pt",
"pollingTrackerBase",
")",
"baseCheckForErrors",
"(",
")",
"error",
"{",
"// for Azure-AsyncOperations the response body cannot be nil or empty",
"if",
"pt",
".",
"Pm",
"==",
"PollingAsyncOperation",
"{",
"if",
"pt",
".",
"resp",
".",
"Body",
"==",
"nil",
"||",
"pt",
".",
"resp",
".",
"ContentLength",
"==",
"0",
"{",
"return",
"autorest",
".",
"NewError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"pt",
".",
"rawBody",
"[",
"\"",
"\"",
"]",
"==",
"nil",
"{",
"return",
"autorest",
".",
"NewError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // error checking common to all trackers | [
"error",
"checking",
"common",
"to",
"all",
"trackers"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L550-L561 |
152,656 | Azure/go-autorest | autorest/azure/async.go | createPollingTracker | func createPollingTracker(resp *http.Response) (pollingTracker, error) {
var pt pollingTracker
switch strings.ToUpper(resp.Request.Method) {
case http.MethodDelete:
pt = &pollingTrackerDelete{pollingTrackerBase: pollingTrackerBase{resp: resp}}
case http.MethodPatch:
pt = &pollingTrackerPatch{pollingTrackerBase: pollingTrackerBase{resp: resp}}
case http.MethodPost:
pt = &pollingTrackerPost{pollingTrackerBase: pollingTrackerBase{resp: resp}}
case http.MethodPut:
pt = &pollingTrackerPut{pollingTrackerBase: pollingTrackerBase{resp: resp}}
default:
return nil, autorest.NewError("azure", "createPollingTracker", "unsupported HTTP method %s", resp.Request.Method)
}
if err := pt.initializeState(); err != nil {
return pt, err
}
// this initializes the polling header values, we do this during creation in case the
// initial response send us invalid values; this way the API call will return a non-nil
// error (not doing this means the error shows up in Future.Done)
return pt, pt.updatePollingMethod()
} | go | func createPollingTracker(resp *http.Response) (pollingTracker, error) {
var pt pollingTracker
switch strings.ToUpper(resp.Request.Method) {
case http.MethodDelete:
pt = &pollingTrackerDelete{pollingTrackerBase: pollingTrackerBase{resp: resp}}
case http.MethodPatch:
pt = &pollingTrackerPatch{pollingTrackerBase: pollingTrackerBase{resp: resp}}
case http.MethodPost:
pt = &pollingTrackerPost{pollingTrackerBase: pollingTrackerBase{resp: resp}}
case http.MethodPut:
pt = &pollingTrackerPut{pollingTrackerBase: pollingTrackerBase{resp: resp}}
default:
return nil, autorest.NewError("azure", "createPollingTracker", "unsupported HTTP method %s", resp.Request.Method)
}
if err := pt.initializeState(); err != nil {
return pt, err
}
// this initializes the polling header values, we do this during creation in case the
// initial response send us invalid values; this way the API call will return a non-nil
// error (not doing this means the error shows up in Future.Done)
return pt, pt.updatePollingMethod()
} | [
"func",
"createPollingTracker",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"pollingTracker",
",",
"error",
")",
"{",
"var",
"pt",
"pollingTracker",
"\n",
"switch",
"strings",
".",
"ToUpper",
"(",
"resp",
".",
"Request",
".",
"Method",
")",
"{",
"case",
"http",
".",
"MethodDelete",
":",
"pt",
"=",
"&",
"pollingTrackerDelete",
"{",
"pollingTrackerBase",
":",
"pollingTrackerBase",
"{",
"resp",
":",
"resp",
"}",
"}",
"\n",
"case",
"http",
".",
"MethodPatch",
":",
"pt",
"=",
"&",
"pollingTrackerPatch",
"{",
"pollingTrackerBase",
":",
"pollingTrackerBase",
"{",
"resp",
":",
"resp",
"}",
"}",
"\n",
"case",
"http",
".",
"MethodPost",
":",
"pt",
"=",
"&",
"pollingTrackerPost",
"{",
"pollingTrackerBase",
":",
"pollingTrackerBase",
"{",
"resp",
":",
"resp",
"}",
"}",
"\n",
"case",
"http",
".",
"MethodPut",
":",
"pt",
"=",
"&",
"pollingTrackerPut",
"{",
"pollingTrackerBase",
":",
"pollingTrackerBase",
"{",
"resp",
":",
"resp",
"}",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"autorest",
".",
"NewError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"resp",
".",
"Request",
".",
"Method",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"pt",
".",
"initializeState",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"pt",
",",
"err",
"\n",
"}",
"\n",
"// this initializes the polling header values, we do this during creation in case the",
"// initial response send us invalid values; this way the API call will return a non-nil",
"// error (not doing this means the error shows up in Future.Done)",
"return",
"pt",
",",
"pt",
".",
"updatePollingMethod",
"(",
")",
"\n",
"}"
] | // creates a polling tracker based on the verb of the original request | [
"creates",
"a",
"polling",
"tracker",
"based",
"on",
"the",
"verb",
"of",
"the",
"original",
"request"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L831-L852 |
152,657 | Azure/go-autorest | autorest/azure/async.go | getURLFromAsyncOpHeader | func getURLFromAsyncOpHeader(resp *http.Response) (string, error) {
s := resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation))
if s == "" {
return "", nil
}
if !isValidURL(s) {
return "", autorest.NewError("azure", "getURLFromAsyncOpHeader", "invalid polling URL '%s'", s)
}
return s, nil
} | go | func getURLFromAsyncOpHeader(resp *http.Response) (string, error) {
s := resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation))
if s == "" {
return "", nil
}
if !isValidURL(s) {
return "", autorest.NewError("azure", "getURLFromAsyncOpHeader", "invalid polling URL '%s'", s)
}
return s, nil
} | [
"func",
"getURLFromAsyncOpHeader",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"http",
".",
"CanonicalHeaderKey",
"(",
"headerAsyncOperation",
")",
")",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"isValidURL",
"(",
"s",
")",
"{",
"return",
"\"",
"\"",
",",
"autorest",
".",
"NewError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"s",
")",
"\n",
"}",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // gets the polling URL from the Azure-AsyncOperation header.
// ensures the URL is well-formed and absolute. | [
"gets",
"the",
"polling",
"URL",
"from",
"the",
"Azure",
"-",
"AsyncOperation",
"header",
".",
"ensures",
"the",
"URL",
"is",
"well",
"-",
"formed",
"and",
"absolute",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L856-L865 |
152,658 | Azure/go-autorest | autorest/azure/async.go | getURLFromLocationHeader | func getURLFromLocationHeader(resp *http.Response) (string, error) {
s := resp.Header.Get(http.CanonicalHeaderKey(autorest.HeaderLocation))
if s == "" {
return "", nil
}
if !isValidURL(s) {
return "", autorest.NewError("azure", "getURLFromLocationHeader", "invalid polling URL '%s'", s)
}
return s, nil
} | go | func getURLFromLocationHeader(resp *http.Response) (string, error) {
s := resp.Header.Get(http.CanonicalHeaderKey(autorest.HeaderLocation))
if s == "" {
return "", nil
}
if !isValidURL(s) {
return "", autorest.NewError("azure", "getURLFromLocationHeader", "invalid polling URL '%s'", s)
}
return s, nil
} | [
"func",
"getURLFromLocationHeader",
"(",
"resp",
"*",
"http",
".",
"Response",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"http",
".",
"CanonicalHeaderKey",
"(",
"autorest",
".",
"HeaderLocation",
")",
")",
"\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"isValidURL",
"(",
"s",
")",
"{",
"return",
"\"",
"\"",
",",
"autorest",
".",
"NewError",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"s",
")",
"\n",
"}",
"\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // gets the polling URL from the Location header.
// ensures the URL is well-formed and absolute. | [
"gets",
"the",
"polling",
"URL",
"from",
"the",
"Location",
"header",
".",
"ensures",
"the",
"URL",
"is",
"well",
"-",
"formed",
"and",
"absolute",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L869-L878 |
152,659 | Azure/go-autorest | autorest/azure/async.go | isValidURL | func isValidURL(s string) bool {
u, err := url.Parse(s)
return err == nil && u.IsAbs()
} | go | func isValidURL(s string) bool {
u, err := url.Parse(s)
return err == nil && u.IsAbs()
} | [
"func",
"isValidURL",
"(",
"s",
"string",
")",
"bool",
"{",
"u",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"s",
")",
"\n",
"return",
"err",
"==",
"nil",
"&&",
"u",
".",
"IsAbs",
"(",
")",
"\n",
"}"
] | // verify that the URL is valid and absolute | [
"verify",
"that",
"the",
"URL",
"is",
"valid",
"and",
"absolute"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/azure/async.go#L881-L884 |
152,660 | Azure/go-autorest | autorest/sender.go | Do | func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) {
return sf(r)
} | go | func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) {
return sf(r)
} | [
"func",
"(",
"sf",
"SenderFunc",
")",
"Do",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"return",
"sf",
"(",
"r",
")",
"\n",
"}"
] | // Do implements the Sender interface on SenderFunc. | [
"Do",
"implements",
"the",
"Sender",
"interface",
"on",
"SenderFunc",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L39-L41 |
152,661 | Azure/go-autorest | autorest/sender.go | SendWithSender | func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*http.Response, error) {
return DecorateSender(s, decorators...).Do(r)
} | go | func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*http.Response, error) {
return DecorateSender(s, decorators...).Do(r)
} | [
"func",
"SendWithSender",
"(",
"s",
"Sender",
",",
"r",
"*",
"http",
".",
"Request",
",",
"decorators",
"...",
"SendDecorator",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"return",
"DecorateSender",
"(",
"s",
",",
"decorators",
"...",
")",
".",
"Do",
"(",
"r",
")",
"\n",
"}"
] | // SendWithSender sends the passed http.Request, through the provided Sender, returning the
// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which
// it will apply the http.Client before invoking the Do method.
//
// SendWithSender will not poll or retry requests. | [
"SendWithSender",
"sends",
"the",
"passed",
"http",
".",
"Request",
"through",
"the",
"provided",
"Sender",
"returning",
"the",
"http",
".",
"Response",
"and",
"possible",
"error",
".",
"It",
"also",
"accepts",
"a",
"possibly",
"empty",
"set",
"of",
"SendDecorators",
"which",
"it",
"will",
"apply",
"the",
"http",
".",
"Client",
"before",
"invoking",
"the",
"Do",
"method",
".",
"SendWithSender",
"will",
"not",
"poll",
"or",
"retry",
"requests",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L81-L83 |
152,662 | Azure/go-autorest | autorest/sender.go | AfterDelay | func AfterDelay(d time.Duration) SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
if !DelayForBackoff(d, 0, r.Context().Done()) {
return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay")
}
return s.Do(r)
})
}
} | go | func AfterDelay(d time.Duration) SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
if !DelayForBackoff(d, 0, r.Context().Done()) {
return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay")
}
return s.Do(r)
})
}
} | [
"func",
"AfterDelay",
"(",
"d",
"time",
".",
"Duration",
")",
"SendDecorator",
"{",
"return",
"func",
"(",
"s",
"Sender",
")",
"Sender",
"{",
"return",
"SenderFunc",
"(",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"if",
"!",
"DelayForBackoff",
"(",
"d",
",",
"0",
",",
"r",
".",
"Context",
"(",
")",
".",
"Done",
"(",
")",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"s",
".",
"Do",
"(",
"r",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // AfterDelay returns a SendDecorator that delays for the passed time.Duration before
// invoking the Sender. The delay may be terminated by closing the optional channel on the
// http.Request. If canceled, no further Senders are invoked. | [
"AfterDelay",
"returns",
"a",
"SendDecorator",
"that",
"delays",
"for",
"the",
"passed",
"time",
".",
"Duration",
"before",
"invoking",
"the",
"Sender",
".",
"The",
"delay",
"may",
"be",
"terminated",
"by",
"closing",
"the",
"optional",
"channel",
"on",
"the",
"http",
".",
"Request",
".",
"If",
"canceled",
"no",
"further",
"Senders",
"are",
"invoked",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L88-L97 |
152,663 | Azure/go-autorest | autorest/sender.go | AsIs | func AsIs() SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
return s.Do(r)
})
}
} | go | func AsIs() SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
return s.Do(r)
})
}
} | [
"func",
"AsIs",
"(",
")",
"SendDecorator",
"{",
"return",
"func",
"(",
"s",
"Sender",
")",
"Sender",
"{",
"return",
"SenderFunc",
"(",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"return",
"s",
".",
"Do",
"(",
"r",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // AsIs returns a SendDecorator that invokes the passed Sender without modifying the http.Request. | [
"AsIs",
"returns",
"a",
"SendDecorator",
"that",
"invokes",
"the",
"passed",
"Sender",
"without",
"modifying",
"the",
"http",
".",
"Request",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L100-L106 |
152,664 | Azure/go-autorest | autorest/sender.go | DoCloseIfError | func DoCloseIfError() SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
resp, err := s.Do(r)
if err != nil {
Respond(resp, ByDiscardingBody(), ByClosing())
}
return resp, err
})
}
} | go | func DoCloseIfError() SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
resp, err := s.Do(r)
if err != nil {
Respond(resp, ByDiscardingBody(), ByClosing())
}
return resp, err
})
}
} | [
"func",
"DoCloseIfError",
"(",
")",
"SendDecorator",
"{",
"return",
"func",
"(",
"s",
"Sender",
")",
"Sender",
"{",
"return",
"SenderFunc",
"(",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"s",
".",
"Do",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"Respond",
"(",
"resp",
",",
"ByDiscardingBody",
"(",
")",
",",
"ByClosing",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"resp",
",",
"err",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // DoCloseIfError returns a SendDecorator that first invokes the passed Sender after which
// it closes the response if the passed Sender returns an error and the response body exists. | [
"DoCloseIfError",
"returns",
"a",
"SendDecorator",
"that",
"first",
"invokes",
"the",
"passed",
"Sender",
"after",
"which",
"it",
"closes",
"the",
"response",
"if",
"the",
"passed",
"Sender",
"returns",
"an",
"error",
"and",
"the",
"response",
"body",
"exists",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L110-L120 |
152,665 | Azure/go-autorest | autorest/sender.go | DoErrorUnlessStatusCode | func DoErrorUnlessStatusCode(codes ...int) SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
resp, err := s.Do(r)
if err == nil && !ResponseHasStatusCode(resp, codes...) {
err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s",
resp.Request.Method,
resp.Request.URL,
resp.Status)
}
return resp, err
})
}
} | go | func DoErrorUnlessStatusCode(codes ...int) SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
resp, err := s.Do(r)
if err == nil && !ResponseHasStatusCode(resp, codes...) {
err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s",
resp.Request.Method,
resp.Request.URL,
resp.Status)
}
return resp, err
})
}
} | [
"func",
"DoErrorUnlessStatusCode",
"(",
"codes",
"...",
"int",
")",
"SendDecorator",
"{",
"return",
"func",
"(",
"s",
"Sender",
")",
"Sender",
"{",
"return",
"SenderFunc",
"(",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"resp",
",",
"err",
":=",
"s",
".",
"Do",
"(",
"r",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"!",
"ResponseHasStatusCode",
"(",
"resp",
",",
"codes",
"...",
")",
"{",
"err",
"=",
"NewErrorWithResponse",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"resp",
",",
"\"",
"\"",
",",
"resp",
".",
"Request",
".",
"Method",
",",
"resp",
".",
"Request",
".",
"URL",
",",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n",
"return",
"resp",
",",
"err",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // DoErrorUnlessStatusCode returns a SendDecorator that emits an error unless the response
// StatusCode is among the set passed. Since these are artificial errors, the response body
// may still require closing. | [
"DoErrorUnlessStatusCode",
"returns",
"a",
"SendDecorator",
"that",
"emits",
"an",
"error",
"unless",
"the",
"response",
"StatusCode",
"is",
"among",
"the",
"set",
"passed",
".",
"Since",
"these",
"are",
"artificial",
"errors",
"the",
"response",
"body",
"may",
"still",
"require",
"closing",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L143-L156 |
152,666 | Azure/go-autorest | autorest/sender.go | DelayWithRetryAfter | func DelayWithRetryAfter(resp *http.Response, cancel <-chan struct{}) bool {
if resp == nil {
return false
}
retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After"))
if resp.StatusCode == http.StatusTooManyRequests && retryAfter > 0 {
select {
case <-time.After(time.Duration(retryAfter) * time.Second):
return true
case <-cancel:
return false
}
}
return false
} | go | func DelayWithRetryAfter(resp *http.Response, cancel <-chan struct{}) bool {
if resp == nil {
return false
}
retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After"))
if resp.StatusCode == http.StatusTooManyRequests && retryAfter > 0 {
select {
case <-time.After(time.Duration(retryAfter) * time.Second):
return true
case <-cancel:
return false
}
}
return false
} | [
"func",
"DelayWithRetryAfter",
"(",
"resp",
"*",
"http",
".",
"Response",
",",
"cancel",
"<-",
"chan",
"struct",
"{",
"}",
")",
"bool",
"{",
"if",
"resp",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"retryAfter",
",",
"_",
":=",
"strconv",
".",
"Atoi",
"(",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"==",
"http",
".",
"StatusTooManyRequests",
"&&",
"retryAfter",
">",
"0",
"{",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"time",
".",
"Duration",
"(",
"retryAfter",
")",
"*",
"time",
".",
"Second",
")",
":",
"return",
"true",
"\n",
"case",
"<-",
"cancel",
":",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // DelayWithRetryAfter invokes time.After for the duration specified in the "Retry-After" header in
// responses with status code 429 | [
"DelayWithRetryAfter",
"invokes",
"time",
".",
"After",
"for",
"the",
"duration",
"specified",
"in",
"the",
"Retry",
"-",
"After",
"header",
"in",
"responses",
"with",
"status",
"code",
"429"
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L253-L267 |
152,667 | Azure/go-autorest | autorest/sender.go | WithLogging | func WithLogging(logger *log.Logger) SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
logger.Printf("Sending %s %s", r.Method, r.URL)
resp, err := s.Do(r)
if err != nil {
logger.Printf("%s %s received error '%v'", r.Method, r.URL, err)
} else {
logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status)
}
return resp, err
})
}
} | go | func WithLogging(logger *log.Logger) SendDecorator {
return func(s Sender) Sender {
return SenderFunc(func(r *http.Request) (*http.Response, error) {
logger.Printf("Sending %s %s", r.Method, r.URL)
resp, err := s.Do(r)
if err != nil {
logger.Printf("%s %s received error '%v'", r.Method, r.URL, err)
} else {
logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status)
}
return resp, err
})
}
} | [
"func",
"WithLogging",
"(",
"logger",
"*",
"log",
".",
"Logger",
")",
"SendDecorator",
"{",
"return",
"func",
"(",
"s",
"Sender",
")",
"Sender",
"{",
"return",
"SenderFunc",
"(",
"func",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
",",
"r",
".",
"URL",
")",
"\n",
"resp",
",",
"err",
":=",
"s",
".",
"Do",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
",",
"r",
".",
"URL",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
",",
"r",
".",
"URL",
",",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n",
"return",
"resp",
",",
"err",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // WithLogging returns a SendDecorator that implements simple before and after logging of the
// request. | [
"WithLogging",
"returns",
"a",
"SendDecorator",
"that",
"implements",
"simple",
"before",
"and",
"after",
"logging",
"of",
"the",
"request",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/sender.go#L298-L311 |
152,668 | Azure/go-autorest | autorest/validation/error.go | Error | func (e Error) Error() string {
return fmt.Sprintf("%s#%s: Invalid input: %s", e.PackageType, e.Method, e.Message)
} | go | func (e Error) Error() string {
return fmt.Sprintf("%s#%s: Invalid input: %s", e.PackageType, e.Method, e.Message)
} | [
"func",
"(",
"e",
"Error",
")",
"Error",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"e",
".",
"PackageType",
",",
"e",
".",
"Method",
",",
"e",
".",
"Message",
")",
"\n",
"}"
] | // Error returns a string containing the details of the validation failure. | [
"Error",
"returns",
"a",
"string",
"containing",
"the",
"details",
"of",
"the",
"validation",
"failure",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/validation/error.go#L36-L38 |
152,669 | Azure/go-autorest | autorest/validation/error.go | NewError | func NewError(packageType string, method string, message string, args ...interface{}) Error {
return Error{
PackageType: packageType,
Method: method,
Message: fmt.Sprintf(message, args...),
}
} | go | func NewError(packageType string, method string, message string, args ...interface{}) Error {
return Error{
PackageType: packageType,
Method: method,
Message: fmt.Sprintf(message, args...),
}
} | [
"func",
"NewError",
"(",
"packageType",
"string",
",",
"method",
"string",
",",
"message",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"Error",
"{",
"return",
"Error",
"{",
"PackageType",
":",
"packageType",
",",
"Method",
":",
"method",
",",
"Message",
":",
"fmt",
".",
"Sprintf",
"(",
"message",
",",
"args",
"...",
")",
",",
"}",
"\n",
"}"
] | // NewError creates a new Error object with the specified parameters.
// message is treated as a format string to which the optional args apply. | [
"NewError",
"creates",
"a",
"new",
"Error",
"object",
"with",
"the",
"specified",
"parameters",
".",
"message",
"is",
"treated",
"as",
"a",
"format",
"string",
"to",
"which",
"the",
"optional",
"args",
"apply",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/validation/error.go#L42-L48 |
152,670 | Azure/go-autorest | autorest/validation/validation.go | Validate | func Validate(m []Validation) error {
for _, item := range m {
v := reflect.ValueOf(item.TargetValue)
for _, constraint := range item.Constraints {
var err error
switch v.Kind() {
case reflect.Ptr:
err = validatePtr(v, constraint)
case reflect.String:
err = validateString(v, constraint)
case reflect.Struct:
err = validateStruct(v, constraint)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
err = validateInt(v, constraint)
case reflect.Float32, reflect.Float64:
err = validateFloat(v, constraint)
case reflect.Array, reflect.Slice, reflect.Map:
err = validateArrayMap(v, constraint)
default:
err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind()))
}
if err != nil {
return err
}
}
}
return nil
} | go | func Validate(m []Validation) error {
for _, item := range m {
v := reflect.ValueOf(item.TargetValue)
for _, constraint := range item.Constraints {
var err error
switch v.Kind() {
case reflect.Ptr:
err = validatePtr(v, constraint)
case reflect.String:
err = validateString(v, constraint)
case reflect.Struct:
err = validateStruct(v, constraint)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
err = validateInt(v, constraint)
case reflect.Float32, reflect.Float64:
err = validateFloat(v, constraint)
case reflect.Array, reflect.Slice, reflect.Map:
err = validateArrayMap(v, constraint)
default:
err = createError(v, constraint, fmt.Sprintf("unknown type %v", v.Kind()))
}
if err != nil {
return err
}
}
}
return nil
} | [
"func",
"Validate",
"(",
"m",
"[",
"]",
"Validation",
")",
"error",
"{",
"for",
"_",
",",
"item",
":=",
"range",
"m",
"{",
"v",
":=",
"reflect",
".",
"ValueOf",
"(",
"item",
".",
"TargetValue",
")",
"\n",
"for",
"_",
",",
"constraint",
":=",
"range",
"item",
".",
"Constraints",
"{",
"var",
"err",
"error",
"\n",
"switch",
"v",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Ptr",
":",
"err",
"=",
"validatePtr",
"(",
"v",
",",
"constraint",
")",
"\n",
"case",
"reflect",
".",
"String",
":",
"err",
"=",
"validateString",
"(",
"v",
",",
"constraint",
")",
"\n",
"case",
"reflect",
".",
"Struct",
":",
"err",
"=",
"validateStruct",
"(",
"v",
",",
"constraint",
")",
"\n",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"err",
"=",
"validateInt",
"(",
"v",
",",
"constraint",
")",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"err",
"=",
"validateFloat",
"(",
"v",
",",
"constraint",
")",
"\n",
"case",
"reflect",
".",
"Array",
",",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
":",
"err",
"=",
"validateArrayMap",
"(",
"v",
",",
"constraint",
")",
"\n",
"default",
":",
"err",
"=",
"createError",
"(",
"v",
",",
"constraint",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
".",
"Kind",
"(",
")",
")",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Validate method validates constraints on parameter
// passed in validation array. | [
"Validate",
"method",
"validates",
"constraints",
"on",
"parameter",
"passed",
"in",
"validation",
"array",
"."
] | da8db3a19ec5aba5d01f6032407abf1bb1cc15d3 | https://github.com/Azure/go-autorest/blob/da8db3a19ec5aba5d01f6032407abf1bb1cc15d3/autorest/validation/validation.go#L70-L98 |
152,671 | alexedwards/scs | postgresstore/postgresstore.go | Find | func (p *PostgresStore) Find(token string) (b []byte, exists bool, err error) {
row := p.db.QueryRow("SELECT data FROM sessions WHERE token = $1 AND current_timestamp < expiry", token)
err = row.Scan(&b)
if err == sql.ErrNoRows {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | go | func (p *PostgresStore) Find(token string) (b []byte, exists bool, err error) {
row := p.db.QueryRow("SELECT data FROM sessions WHERE token = $1 AND current_timestamp < expiry", token)
err = row.Scan(&b)
if err == sql.ErrNoRows {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | [
"func",
"(",
"p",
"*",
"PostgresStore",
")",
"Find",
"(",
"token",
"string",
")",
"(",
"b",
"[",
"]",
"byte",
",",
"exists",
"bool",
",",
"err",
"error",
")",
"{",
"row",
":=",
"p",
".",
"db",
".",
"QueryRow",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"err",
"=",
"row",
".",
"Scan",
"(",
"&",
"b",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"nil",
",",
"false",
",",
"nil",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"b",
",",
"true",
",",
"nil",
"\n",
"}"
] | // Find returns the data for a given session token from the PostgresStore instance.
// If the session token is not found or is expired, the returned exists flag will
// be set to false. | [
"Find",
"returns",
"the",
"data",
"for",
"a",
"given",
"session",
"token",
"from",
"the",
"PostgresStore",
"instance",
".",
"If",
"the",
"session",
"token",
"is",
"not",
"found",
"or",
"is",
"expired",
"the",
"returned",
"exists",
"flag",
"will",
"be",
"set",
"to",
"false",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/postgresstore/postgresstore.go#L36-L45 |
152,672 | alexedwards/scs | postgresstore/postgresstore.go | Commit | func (p *PostgresStore) Commit(token string, b []byte, expiry time.Time) error {
_, err := p.db.Exec("INSERT INTO sessions (token, data, expiry) VALUES ($1, $2, $3) ON CONFLICT (token) DO UPDATE SET data = EXCLUDED.data, expiry = EXCLUDED.expiry", token, b, expiry)
if err != nil {
return err
}
return nil
} | go | func (p *PostgresStore) Commit(token string, b []byte, expiry time.Time) error {
_, err := p.db.Exec("INSERT INTO sessions (token, data, expiry) VALUES ($1, $2, $3) ON CONFLICT (token) DO UPDATE SET data = EXCLUDED.data, expiry = EXCLUDED.expiry", token, b, expiry)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"p",
"*",
"PostgresStore",
")",
"Commit",
"(",
"token",
"string",
",",
"b",
"[",
"]",
"byte",
",",
"expiry",
"time",
".",
"Time",
")",
"error",
"{",
"_",
",",
"err",
":=",
"p",
".",
"db",
".",
"Exec",
"(",
"\"",
"\"",
",",
"token",
",",
"b",
",",
"expiry",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Commit adds a session token and data to the PostgresStore instance with the
// given expiry time. If the session token already exists, then the data and expiry
// time are updated. | [
"Commit",
"adds",
"a",
"session",
"token",
"and",
"data",
"to",
"the",
"PostgresStore",
"instance",
"with",
"the",
"given",
"expiry",
"time",
".",
"If",
"the",
"session",
"token",
"already",
"exists",
"then",
"the",
"data",
"and",
"expiry",
"time",
"are",
"updated",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/postgresstore/postgresstore.go#L50-L56 |
152,673 | alexedwards/scs | postgresstore/postgresstore.go | Delete | func (p *PostgresStore) Delete(token string) error {
_, err := p.db.Exec("DELETE FROM sessions WHERE token = $1", token)
return err
} | go | func (p *PostgresStore) Delete(token string) error {
_, err := p.db.Exec("DELETE FROM sessions WHERE token = $1", token)
return err
} | [
"func",
"(",
"p",
"*",
"PostgresStore",
")",
"Delete",
"(",
"token",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"p",
".",
"db",
".",
"Exec",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Delete removes a session token and corresponding data from the PostgresStore
// instance. | [
"Delete",
"removes",
"a",
"session",
"token",
"and",
"corresponding",
"data",
"from",
"the",
"PostgresStore",
"instance",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/postgresstore/postgresstore.go#L60-L63 |
152,674 | alexedwards/scs | memstore/memstore.go | Find | func (m *MemStore) Find(token string) ([]byte, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
item, found := m.items[token]
if !found {
return nil, false, nil
}
if time.Now().UnixNano() > item.expiration {
return nil, false, nil
}
b, ok := item.object.([]byte)
if !ok {
return nil, true, errTypeAssertionFailed
}
return b, true, nil
} | go | func (m *MemStore) Find(token string) ([]byte, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
item, found := m.items[token]
if !found {
return nil, false, nil
}
if time.Now().UnixNano() > item.expiration {
return nil, false, nil
}
b, ok := item.object.([]byte)
if !ok {
return nil, true, errTypeAssertionFailed
}
return b, true, nil
} | [
"func",
"(",
"m",
"*",
"MemStore",
")",
"Find",
"(",
"token",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"bool",
",",
"error",
")",
"{",
"m",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\n",
"item",
",",
"found",
":=",
"m",
".",
"items",
"[",
"token",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"nil",
",",
"false",
",",
"nil",
"\n",
"}",
"\n",
"if",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
">",
"item",
".",
"expiration",
"{",
"return",
"nil",
",",
"false",
",",
"nil",
"\n",
"}",
"\n\n",
"b",
",",
"ok",
":=",
"item",
".",
"object",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"true",
",",
"errTypeAssertionFailed",
"\n",
"}",
"\n\n",
"return",
"b",
",",
"true",
",",
"nil",
"\n",
"}"
] | // Find returns the data for a given session token from the MemStore instance.
// If the session token is not found or is expired, the returned exists flag will
// be set to false. | [
"Find",
"returns",
"the",
"data",
"for",
"a",
"given",
"session",
"token",
"from",
"the",
"MemStore",
"instance",
".",
"If",
"the",
"session",
"token",
"is",
"not",
"found",
"or",
"is",
"expired",
"the",
"returned",
"exists",
"flag",
"will",
"be",
"set",
"to",
"false",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/memstore/memstore.go#L48-L66 |
152,675 | alexedwards/scs | memstore/memstore.go | Commit | func (m *MemStore) Commit(token string, b []byte, expiry time.Time) error {
m.mu.Lock()
m.items[token] = item{
object: b,
expiration: expiry.UnixNano(),
}
m.mu.Unlock()
return nil
} | go | func (m *MemStore) Commit(token string, b []byte, expiry time.Time) error {
m.mu.Lock()
m.items[token] = item{
object: b,
expiration: expiry.UnixNano(),
}
m.mu.Unlock()
return nil
} | [
"func",
"(",
"m",
"*",
"MemStore",
")",
"Commit",
"(",
"token",
"string",
",",
"b",
"[",
"]",
"byte",
",",
"expiry",
"time",
".",
"Time",
")",
"error",
"{",
"m",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"m",
".",
"items",
"[",
"token",
"]",
"=",
"item",
"{",
"object",
":",
"b",
",",
"expiration",
":",
"expiry",
".",
"UnixNano",
"(",
")",
",",
"}",
"\n",
"m",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Commit adds a session token and data to the MemStore instance with the given
// expiry time. If the session token already exists, then the data and expiry
// time are updated. | [
"Commit",
"adds",
"a",
"session",
"token",
"and",
"data",
"to",
"the",
"MemStore",
"instance",
"with",
"the",
"given",
"expiry",
"time",
".",
"If",
"the",
"session",
"token",
"already",
"exists",
"then",
"the",
"data",
"and",
"expiry",
"time",
"are",
"updated",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/memstore/memstore.go#L71-L80 |
152,676 | alexedwards/scs | memstore/memstore.go | Delete | func (m *MemStore) Delete(token string) error {
m.mu.Lock()
delete(m.items, token)
m.mu.Unlock()
return nil
} | go | func (m *MemStore) Delete(token string) error {
m.mu.Lock()
delete(m.items, token)
m.mu.Unlock()
return nil
} | [
"func",
"(",
"m",
"*",
"MemStore",
")",
"Delete",
"(",
"token",
"string",
")",
"error",
"{",
"m",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"m",
".",
"items",
",",
"token",
")",
"\n",
"m",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Delete removes a session token and corresponding data from the MemStore
// instance. | [
"Delete",
"removes",
"a",
"session",
"token",
"and",
"corresponding",
"data",
"from",
"the",
"MemStore",
"instance",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/memstore/memstore.go#L84-L90 |
152,677 | alexedwards/scs | redisstore/redisstore.go | NewWithPrefix | func NewWithPrefix(pool *redis.Pool, prefix string) *RedisStore {
return &RedisStore{
pool: pool,
prefix: prefix,
}
} | go | func NewWithPrefix(pool *redis.Pool, prefix string) *RedisStore {
return &RedisStore{
pool: pool,
prefix: prefix,
}
} | [
"func",
"NewWithPrefix",
"(",
"pool",
"*",
"redis",
".",
"Pool",
",",
"prefix",
"string",
")",
"*",
"RedisStore",
"{",
"return",
"&",
"RedisStore",
"{",
"pool",
":",
"pool",
",",
"prefix",
":",
"prefix",
",",
"}",
"\n",
"}"
] | // New returns a new RedisStore instance. The pool parameter should be a pointer
// to a redigo connection pool. The prefix parameter controls the Redis key
// prefix, which can be used to avoid naming clashes if necessary. | [
"New",
"returns",
"a",
"new",
"RedisStore",
"instance",
".",
"The",
"pool",
"parameter",
"should",
"be",
"a",
"pointer",
"to",
"a",
"redigo",
"connection",
"pool",
".",
"The",
"prefix",
"parameter",
"controls",
"the",
"Redis",
"key",
"prefix",
"which",
"can",
"be",
"used",
"to",
"avoid",
"naming",
"clashes",
"if",
"necessary",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/redisstore/redisstore.go#L24-L29 |
152,678 | alexedwards/scs | redisstore/redisstore.go | Find | func (r *RedisStore) Find(token string) (b []byte, exists bool, err error) {
conn := r.pool.Get()
defer conn.Close()
b, err = redis.Bytes(conn.Do("GET", r.prefix+token))
if err == redis.ErrNil {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | go | func (r *RedisStore) Find(token string) (b []byte, exists bool, err error) {
conn := r.pool.Get()
defer conn.Close()
b, err = redis.Bytes(conn.Do("GET", r.prefix+token))
if err == redis.ErrNil {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | [
"func",
"(",
"r",
"*",
"RedisStore",
")",
"Find",
"(",
"token",
"string",
")",
"(",
"b",
"[",
"]",
"byte",
",",
"exists",
"bool",
",",
"err",
"error",
")",
"{",
"conn",
":=",
"r",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"b",
",",
"err",
"=",
"redis",
".",
"Bytes",
"(",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"r",
".",
"prefix",
"+",
"token",
")",
")",
"\n",
"if",
"err",
"==",
"redis",
".",
"ErrNil",
"{",
"return",
"nil",
",",
"false",
",",
"nil",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"b",
",",
"true",
",",
"nil",
"\n",
"}"
] | // Find returns the data for a given session token from the RedisStore instance.
// If the session token is not found or is expired, the returned exists flag
// will be set to false. | [
"Find",
"returns",
"the",
"data",
"for",
"a",
"given",
"session",
"token",
"from",
"the",
"RedisStore",
"instance",
".",
"If",
"the",
"session",
"token",
"is",
"not",
"found",
"or",
"is",
"expired",
"the",
"returned",
"exists",
"flag",
"will",
"be",
"set",
"to",
"false",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/redisstore/redisstore.go#L34-L45 |
152,679 | alexedwards/scs | redisstore/redisstore.go | Commit | func (r *RedisStore) Commit(token string, b []byte, expiry time.Time) error {
conn := r.pool.Get()
defer conn.Close()
err := conn.Send("MULTI")
if err != nil {
return err
}
err = conn.Send("SET", r.prefix+token, b)
if err != nil {
return err
}
err = conn.Send("PEXPIREAT", r.prefix+token, makeMillisecondTimestamp(expiry))
if err != nil {
return err
}
_, err = conn.Do("EXEC")
return err
} | go | func (r *RedisStore) Commit(token string, b []byte, expiry time.Time) error {
conn := r.pool.Get()
defer conn.Close()
err := conn.Send("MULTI")
if err != nil {
return err
}
err = conn.Send("SET", r.prefix+token, b)
if err != nil {
return err
}
err = conn.Send("PEXPIREAT", r.prefix+token, makeMillisecondTimestamp(expiry))
if err != nil {
return err
}
_, err = conn.Do("EXEC")
return err
} | [
"func",
"(",
"r",
"*",
"RedisStore",
")",
"Commit",
"(",
"token",
"string",
",",
"b",
"[",
"]",
"byte",
",",
"expiry",
"time",
".",
"Time",
")",
"error",
"{",
"conn",
":=",
"r",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"err",
":=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"r",
".",
"prefix",
"+",
"token",
",",
"b",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"conn",
".",
"Send",
"(",
"\"",
"\"",
",",
"r",
".",
"prefix",
"+",
"token",
",",
"makeMillisecondTimestamp",
"(",
"expiry",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Commit adds a session token and data to the RedisStore instance with the
// given expiry time. If the session token already exists then the data and
// expiry time are updated. | [
"Commit",
"adds",
"a",
"session",
"token",
"and",
"data",
"to",
"the",
"RedisStore",
"instance",
"with",
"the",
"given",
"expiry",
"time",
".",
"If",
"the",
"session",
"token",
"already",
"exists",
"then",
"the",
"data",
"and",
"expiry",
"time",
"are",
"updated",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/redisstore/redisstore.go#L50-L68 |
152,680 | alexedwards/scs | redisstore/redisstore.go | Delete | func (r *RedisStore) Delete(token string) error {
conn := r.pool.Get()
defer conn.Close()
_, err := conn.Do("DEL", r.prefix+token)
return err
} | go | func (r *RedisStore) Delete(token string) error {
conn := r.pool.Get()
defer conn.Close()
_, err := conn.Do("DEL", r.prefix+token)
return err
} | [
"func",
"(",
"r",
"*",
"RedisStore",
")",
"Delete",
"(",
"token",
"string",
")",
"error",
"{",
"conn",
":=",
"r",
".",
"pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n\n",
"_",
",",
"err",
":=",
"conn",
".",
"Do",
"(",
"\"",
"\"",
",",
"r",
".",
"prefix",
"+",
"token",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Delete removes a session token and corresponding data from the RedisStore
// instance. | [
"Delete",
"removes",
"a",
"session",
"token",
"and",
"corresponding",
"data",
"from",
"the",
"RedisStore",
"instance",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/redisstore/redisstore.go#L72-L78 |
152,681 | alexedwards/scs | mysqlstore/mysqlstore.go | Find | func (m *MySQLStore) Find(token string) ([]byte, bool, error) {
var b []byte
var stmt string
if compareVersion("5.6.4", m.version) >= 0 {
stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP(6) < expiry"
} else {
stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP < expiry"
}
row := m.DB.QueryRow(stmt, token)
err := row.Scan(&b)
if err == sql.ErrNoRows {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | go | func (m *MySQLStore) Find(token string) ([]byte, bool, error) {
var b []byte
var stmt string
if compareVersion("5.6.4", m.version) >= 0 {
stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP(6) < expiry"
} else {
stmt = "SELECT data FROM sessions WHERE token = ? AND UTC_TIMESTAMP < expiry"
}
row := m.DB.QueryRow(stmt, token)
err := row.Scan(&b)
if err == sql.ErrNoRows {
return nil, false, nil
} else if err != nil {
return nil, false, err
}
return b, true, nil
} | [
"func",
"(",
"m",
"*",
"MySQLStore",
")",
"Find",
"(",
"token",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"bool",
",",
"error",
")",
"{",
"var",
"b",
"[",
"]",
"byte",
"\n",
"var",
"stmt",
"string",
"\n\n",
"if",
"compareVersion",
"(",
"\"",
"\"",
",",
"m",
".",
"version",
")",
">=",
"0",
"{",
"stmt",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"stmt",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"row",
":=",
"m",
".",
"DB",
".",
"QueryRow",
"(",
"stmt",
",",
"token",
")",
"\n",
"err",
":=",
"row",
".",
"Scan",
"(",
"&",
"b",
")",
"\n",
"if",
"err",
"==",
"sql",
".",
"ErrNoRows",
"{",
"return",
"nil",
",",
"false",
",",
"nil",
"\n",
"}",
"else",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"err",
"\n",
"}",
"\n",
"return",
"b",
",",
"true",
",",
"nil",
"\n",
"}"
] | // Find returns the data for a given session token from the MySQLStore instance.
// If the session token is not found or is expired, the returned exists flag will
// be set to false. | [
"Find",
"returns",
"the",
"data",
"for",
"a",
"given",
"session",
"token",
"from",
"the",
"MySQLStore",
"instance",
".",
"If",
"the",
"session",
"token",
"is",
"not",
"found",
"or",
"is",
"expired",
"the",
"returned",
"exists",
"flag",
"will",
"be",
"set",
"to",
"false",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/mysqlstore/mysqlstore.go#L44-L62 |
152,682 | alexedwards/scs | mysqlstore/mysqlstore.go | Commit | func (m *MySQLStore) Commit(token string, b []byte, expiry time.Time) error {
_, err := m.DB.Exec("INSERT INTO sessions (token, data, expiry) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data), expiry = VALUES(expiry)", token, b, expiry.UTC())
if err != nil {
return err
}
return nil
} | go | func (m *MySQLStore) Commit(token string, b []byte, expiry time.Time) error {
_, err := m.DB.Exec("INSERT INTO sessions (token, data, expiry) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE data = VALUES(data), expiry = VALUES(expiry)", token, b, expiry.UTC())
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"m",
"*",
"MySQLStore",
")",
"Commit",
"(",
"token",
"string",
",",
"b",
"[",
"]",
"byte",
",",
"expiry",
"time",
".",
"Time",
")",
"error",
"{",
"_",
",",
"err",
":=",
"m",
".",
"DB",
".",
"Exec",
"(",
"\"",
"\"",
",",
"token",
",",
"b",
",",
"expiry",
".",
"UTC",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Commit adds a session token and data to the MySQLStore instance with the given
// expiry time. If the session token already exists, then the data and expiry
// time are updated. | [
"Commit",
"adds",
"a",
"session",
"token",
"and",
"data",
"to",
"the",
"MySQLStore",
"instance",
"with",
"the",
"given",
"expiry",
"time",
".",
"If",
"the",
"session",
"token",
"already",
"exists",
"then",
"the",
"data",
"and",
"expiry",
"time",
"are",
"updated",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/mysqlstore/mysqlstore.go#L67-L73 |
152,683 | alexedwards/scs | mysqlstore/mysqlstore.go | Delete | func (m *MySQLStore) Delete(token string) error {
_, err := m.DB.Exec("DELETE FROM sessions WHERE token = ?", token)
return err
} | go | func (m *MySQLStore) Delete(token string) error {
_, err := m.DB.Exec("DELETE FROM sessions WHERE token = ?", token)
return err
} | [
"func",
"(",
"m",
"*",
"MySQLStore",
")",
"Delete",
"(",
"token",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"m",
".",
"DB",
".",
"Exec",
"(",
"\"",
"\"",
",",
"token",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Delete removes a session token and corresponding data from the MySQLStore
// instance. | [
"Delete",
"removes",
"a",
"session",
"token",
"and",
"corresponding",
"data",
"from",
"the",
"MySQLStore",
"instance",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/mysqlstore/mysqlstore.go#L77-L80 |
152,684 | alexedwards/scs | data.go | Destroy | func (s *Session) Destroy(ctx context.Context) error {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
err := s.Store.Delete(sd.token)
if err != nil {
return err
}
sd.status = Destroyed
// Reset everything else to defaults.
sd.token = ""
sd.Deadline = time.Now().Add(s.Lifetime).UTC()
for key := range sd.Values {
delete(sd.Values, key)
}
return nil
} | go | func (s *Session) Destroy(ctx context.Context) error {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
err := s.Store.Delete(sd.token)
if err != nil {
return err
}
sd.status = Destroyed
// Reset everything else to defaults.
sd.token = ""
sd.Deadline = time.Now().Add(s.Lifetime).UTC()
for key := range sd.Values {
delete(sd.Values, key)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Destroy",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"sd",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"err",
":=",
"s",
".",
"Store",
".",
"Delete",
"(",
"sd",
".",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"sd",
".",
"status",
"=",
"Destroyed",
"\n\n",
"// Reset everything else to defaults.",
"sd",
".",
"token",
"=",
"\"",
"\"",
"\n",
"sd",
".",
"Deadline",
"=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"s",
".",
"Lifetime",
")",
".",
"UTC",
"(",
")",
"\n",
"for",
"key",
":=",
"range",
"sd",
".",
"Values",
"{",
"delete",
"(",
"sd",
".",
"Values",
",",
"key",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Destroy deletes the session data from the session store and sets the session
// status to Destroyed. Any futher operations in the same request cycle will
// result in a new session being created. | [
"Destroy",
"deletes",
"the",
"session",
"data",
"from",
"the",
"session",
"store",
"and",
"sets",
"the",
"session",
"status",
"to",
"Destroyed",
".",
"Any",
"futher",
"operations",
"in",
"the",
"same",
"request",
"cycle",
"will",
"result",
"in",
"a",
"new",
"session",
"being",
"created",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L131-L152 |
152,685 | alexedwards/scs | data.go | Put | func (s *Session) Put(ctx context.Context, key string, val interface{}) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
sd.Values[key] = val
sd.status = Modified
sd.mu.Unlock()
} | go | func (s *Session) Put(ctx context.Context, key string, val interface{}) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
sd.Values[key] = val
sd.status = Modified
sd.mu.Unlock()
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Put",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
",",
"val",
"interface",
"{",
"}",
")",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"sd",
".",
"Values",
"[",
"key",
"]",
"=",
"val",
"\n",
"sd",
".",
"status",
"=",
"Modified",
"\n",
"sd",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // Put adds a key and corresponding value to the session data. Any existing
// value for the key will be replaced. The session data status will be set to
// Modified. | [
"Put",
"adds",
"a",
"key",
"and",
"corresponding",
"value",
"to",
"the",
"session",
"data",
".",
"Any",
"existing",
"value",
"for",
"the",
"key",
"will",
"be",
"replaced",
".",
"The",
"session",
"data",
"status",
"will",
"be",
"set",
"to",
"Modified",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L157-L164 |
152,686 | alexedwards/scs | data.go | Remove | func (s *Session) Remove(ctx context.Context, key string) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
_, exists := sd.Values[key]
if !exists {
return
}
delete(sd.Values, key)
sd.status = Modified
} | go | func (s *Session) Remove(ctx context.Context, key string) {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
_, exists := sd.Values[key]
if !exists {
return
}
delete(sd.Values, key)
sd.status = Modified
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Remove",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"sd",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"_",
",",
"exists",
":=",
"sd",
".",
"Values",
"[",
"key",
"]",
"\n",
"if",
"!",
"exists",
"{",
"return",
"\n",
"}",
"\n\n",
"delete",
"(",
"sd",
".",
"Values",
",",
"key",
")",
"\n",
"sd",
".",
"status",
"=",
"Modified",
"\n",
"}"
] | // Remove deletes the given key and corresponding value from the session data.
// The session data status will be set to Modified. If the key is not present
// this operation is a no-op. | [
"Remove",
"deletes",
"the",
"given",
"key",
"and",
"corresponding",
"value",
"from",
"the",
"session",
"data",
".",
"The",
"session",
"data",
"status",
"will",
"be",
"set",
"to",
"Modified",
".",
"If",
"the",
"key",
"is",
"not",
"present",
"this",
"operation",
"is",
"a",
"no",
"-",
"op",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L209-L222 |
152,687 | alexedwards/scs | data.go | Exists | func (s *Session) Exists(ctx context.Context, key string) bool {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
_, exists := sd.Values[key]
sd.mu.Unlock()
return exists
} | go | func (s *Session) Exists(ctx context.Context, key string) bool {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
_, exists := sd.Values[key]
sd.mu.Unlock()
return exists
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Exists",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"bool",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"_",
",",
"exists",
":=",
"sd",
".",
"Values",
"[",
"key",
"]",
"\n",
"sd",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"exists",
"\n",
"}"
] | // Exists returns true if the given key is present in the session data. | [
"Exists",
"returns",
"true",
"if",
"the",
"given",
"key",
"is",
"present",
"in",
"the",
"session",
"data",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L225-L233 |
152,688 | alexedwards/scs | data.go | Keys | func (s *Session) Keys(ctx context.Context) []string {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
keys := make([]string, len(sd.Values))
i := 0
for key := range sd.Values {
keys[i] = key
i++
}
sd.mu.Unlock()
sort.Strings(keys)
return keys
} | go | func (s *Session) Keys(ctx context.Context) []string {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
keys := make([]string, len(sd.Values))
i := 0
for key := range sd.Values {
keys[i] = key
i++
}
sd.mu.Unlock()
sort.Strings(keys)
return keys
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Keys",
"(",
"ctx",
"context",
".",
"Context",
")",
"[",
"]",
"string",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"sd",
".",
"Values",
")",
")",
"\n",
"i",
":=",
"0",
"\n",
"for",
"key",
":=",
"range",
"sd",
".",
"Values",
"{",
"keys",
"[",
"i",
"]",
"=",
"key",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"sd",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n",
"return",
"keys",
"\n",
"}"
] | // Keys returns a slice of all key names present in the session data, sorted
// alphabetically. If the data contains no data then an empty slice will be
// returned. | [
"Keys",
"returns",
"a",
"slice",
"of",
"all",
"key",
"names",
"present",
"in",
"the",
"session",
"data",
"sorted",
"alphabetically",
".",
"If",
"the",
"data",
"contains",
"no",
"data",
"then",
"an",
"empty",
"slice",
"will",
"be",
"returned",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L238-L252 |
152,689 | alexedwards/scs | data.go | Status | func (s *Session) Status(ctx context.Context) Status {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
return sd.status
} | go | func (s *Session) Status(ctx context.Context) Status {
sd := s.getSessionDataFromContext(ctx)
sd.mu.Lock()
defer sd.mu.Unlock()
return sd.status
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"Status",
"(",
"ctx",
"context",
".",
"Context",
")",
"Status",
"{",
"sd",
":=",
"s",
".",
"getSessionDataFromContext",
"(",
"ctx",
")",
"\n\n",
"sd",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"sd",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"sd",
".",
"status",
"\n",
"}"
] | // Status returns the current status of the session data. | [
"Status",
"returns",
"the",
"current",
"status",
"of",
"the",
"session",
"data",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L288-L295 |
152,690 | alexedwards/scs | data.go | PopTime | func (s *Session) PopTime(ctx context.Context, key string) time.Time {
val := s.Pop(ctx, key)
t, ok := val.(time.Time)
if !ok {
return time.Time{}
}
return t
} | go | func (s *Session) PopTime(ctx context.Context, key string) time.Time {
val := s.Pop(ctx, key)
t, ok := val.(time.Time)
if !ok {
return time.Time{}
}
return t
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"PopTime",
"(",
"ctx",
"context",
".",
"Context",
",",
"key",
"string",
")",
"time",
".",
"Time",
"{",
"val",
":=",
"s",
".",
"Pop",
"(",
"ctx",
",",
"key",
")",
"\n",
"t",
",",
"ok",
":=",
"val",
".",
"(",
"time",
".",
"Time",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
"\n",
"}",
"\n",
"return",
"t",
"\n",
"}"
] | // PopTime returns the time.Time value for a given key and then deletes it from
// the session data. The session data status will be set to Modified. The zero
// value for a time.Time object is returned if the key does not exist or the
// value could not be type asserted to a time.Time. | [
"PopTime",
"returns",
"the",
"time",
".",
"Time",
"value",
"for",
"a",
"given",
"key",
"and",
"then",
"deletes",
"it",
"from",
"the",
"session",
"data",
".",
"The",
"session",
"data",
"status",
"will",
"be",
"set",
"to",
"Modified",
".",
"The",
"zero",
"value",
"for",
"a",
"time",
".",
"Time",
"object",
"is",
"returned",
"if",
"the",
"key",
"does",
"not",
"exist",
"or",
"the",
"value",
"could",
"not",
"be",
"type",
"asserted",
"to",
"a",
"time",
".",
"Time",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/data.go#L439-L446 |
152,691 | alexedwards/scs | session.go | NewSession | func NewSession() *Session {
s := &Session{
IdleTimeout: 0,
Lifetime: 24 * time.Hour,
Store: memstore.New(),
contextKey: generateContextKey(),
Cookie: SessionCookie{
Name: "session",
Domain: "",
HttpOnly: true,
Path: "/",
Persist: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
},
}
return s
} | go | func NewSession() *Session {
s := &Session{
IdleTimeout: 0,
Lifetime: 24 * time.Hour,
Store: memstore.New(),
contextKey: generateContextKey(),
Cookie: SessionCookie{
Name: "session",
Domain: "",
HttpOnly: true,
Path: "/",
Persist: true,
Secure: false,
SameSite: http.SameSiteLaxMode,
},
}
return s
} | [
"func",
"NewSession",
"(",
")",
"*",
"Session",
"{",
"s",
":=",
"&",
"Session",
"{",
"IdleTimeout",
":",
"0",
",",
"Lifetime",
":",
"24",
"*",
"time",
".",
"Hour",
",",
"Store",
":",
"memstore",
".",
"New",
"(",
")",
",",
"contextKey",
":",
"generateContextKey",
"(",
")",
",",
"Cookie",
":",
"SessionCookie",
"{",
"Name",
":",
"\"",
"\"",
",",
"Domain",
":",
"\"",
"\"",
",",
"HttpOnly",
":",
"true",
",",
"Path",
":",
"\"",
"\"",
",",
"Persist",
":",
"true",
",",
"Secure",
":",
"false",
",",
"SameSite",
":",
"http",
".",
"SameSiteLaxMode",
",",
"}",
",",
"}",
"\n",
"return",
"s",
"\n",
"}"
] | // NewSession returns a new session manager with the default options. It is
// safe for concurrent use. | [
"NewSession",
"returns",
"a",
"new",
"session",
"manager",
"with",
"the",
"default",
"options",
".",
"It",
"is",
"safe",
"for",
"concurrent",
"use",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/session.go#L80-L97 |
152,692 | alexedwards/scs | session.go | LoadAndSave | func (s *Session) LoadAndSave(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var token string
cookie, err := r.Cookie(s.Cookie.Name)
if err == nil {
token = cookie.Value
}
ctx, err := s.Load(r.Context(), token)
if err != nil {
log.Output(2, err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
sr := r.WithContext(ctx)
bw := &bufferedResponseWriter{ResponseWriter: w}
next.ServeHTTP(bw, sr)
switch s.Status(ctx) {
case Modified:
token, expiry, err := s.Commit(ctx)
if err != nil {
log.Output(2, err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
s.writeSessionCookie(w, token, expiry)
case Destroyed:
s.writeSessionCookie(w, "", time.Time{})
}
if bw.code != 0 {
w.WriteHeader(bw.code)
}
w.Write(bw.buf.Bytes())
})
} | go | func (s *Session) LoadAndSave(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var token string
cookie, err := r.Cookie(s.Cookie.Name)
if err == nil {
token = cookie.Value
}
ctx, err := s.Load(r.Context(), token)
if err != nil {
log.Output(2, err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
sr := r.WithContext(ctx)
bw := &bufferedResponseWriter{ResponseWriter: w}
next.ServeHTTP(bw, sr)
switch s.Status(ctx) {
case Modified:
token, expiry, err := s.Commit(ctx)
if err != nil {
log.Output(2, err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
s.writeSessionCookie(w, token, expiry)
case Destroyed:
s.writeSessionCookie(w, "", time.Time{})
}
if bw.code != 0 {
w.WriteHeader(bw.code)
}
w.Write(bw.buf.Bytes())
})
} | [
"func",
"(",
"s",
"*",
"Session",
")",
"LoadAndSave",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"token",
"string",
"\n",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"s",
".",
"Cookie",
".",
"Name",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"token",
"=",
"cookie",
".",
"Value",
"\n",
"}",
"\n\n",
"ctx",
",",
"err",
":=",
"s",
".",
"Load",
"(",
"r",
".",
"Context",
"(",
")",
",",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Output",
"(",
"2",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusInternalServerError",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"sr",
":=",
"r",
".",
"WithContext",
"(",
"ctx",
")",
"\n",
"bw",
":=",
"&",
"bufferedResponseWriter",
"{",
"ResponseWriter",
":",
"w",
"}",
"\n",
"next",
".",
"ServeHTTP",
"(",
"bw",
",",
"sr",
")",
"\n\n",
"switch",
"s",
".",
"Status",
"(",
"ctx",
")",
"{",
"case",
"Modified",
":",
"token",
",",
"expiry",
",",
"err",
":=",
"s",
".",
"Commit",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Output",
"(",
"2",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"http",
".",
"Error",
"(",
"w",
",",
"http",
".",
"StatusText",
"(",
"http",
".",
"StatusInternalServerError",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"s",
".",
"writeSessionCookie",
"(",
"w",
",",
"token",
",",
"expiry",
")",
"\n",
"case",
"Destroyed",
":",
"s",
".",
"writeSessionCookie",
"(",
"w",
",",
"\"",
"\"",
",",
"time",
".",
"Time",
"{",
"}",
")",
"\n",
"}",
"\n\n",
"if",
"bw",
".",
"code",
"!=",
"0",
"{",
"w",
".",
"WriteHeader",
"(",
"bw",
".",
"code",
")",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"bw",
".",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] | // LoadAndSave provides middleware which automatically loads and saves session
// data for the current request, and communicates the session token to and from
// the client in a cookie. | [
"LoadAndSave",
"provides",
"middleware",
"which",
"automatically",
"loads",
"and",
"saves",
"session",
"data",
"for",
"the",
"current",
"request",
"and",
"communicates",
"the",
"session",
"token",
"to",
"and",
"from",
"the",
"client",
"in",
"a",
"cookie",
"."
] | 7591275b1edfd53a361e4bdbe42148cbd1b00ac1 | https://github.com/alexedwards/scs/blob/7591275b1edfd53a361e4bdbe42148cbd1b00ac1/session.go#L102-L139 |
152,693 | rogpeppe/godef | go/ast/resolve.go | NewPackage | func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error) {
var p pkgBuilder
p.fset = fset
// complete package scope
pkgName := ""
pkgScope := NewScope(universe)
for _, file := range files {
// package names must match
switch name := file.Name.Name; {
case pkgName == "":
pkgName = name
case name != pkgName:
p.errorf(file.Package, "package %s; expected %s", name, pkgName)
continue // ignore this file
}
// collect top-level file objects in package scope
for _, obj := range file.Scope.Objects {
p.declare(pkgScope, nil, obj)
}
}
// package global mapping of imported package ids to package objects
imports := make(map[string]*Object)
// complete file scopes with imports and resolve identifiers
for _, file := range files {
// ignore file if it belongs to a different package
// (error has already been reported)
if file.Name.Name != pkgName {
continue
}
// build file scope by processing all imports
importErrors := false
fileScope := NewScope(pkgScope)
for _, spec := range file.Imports {
if importer == nil {
importErrors = true
continue
}
path, _ := strconv.Unquote(string(spec.Path.Value))
pkg, err := importer(imports, path)
if err != nil {
p.errorf(spec.Path.Pos(), "could not import %s (%s)", path, err)
importErrors = true
continue
}
// TODO(gri) If a local package name != "." is provided,
// global identifier resolution could proceed even if the
// import failed. Consider adjusting the logic here a bit.
// local name overrides imported package name
name := pkg.Name
if spec.Name != nil {
name = spec.Name.Name
}
// add import to file scope
if name == "." {
// merge imported scope with file scope
for _, obj := range pkg.Data.(*Scope).Objects {
p.declare(fileScope, pkgScope, obj)
}
} else {
// declare imported package object in file scope
// (do not re-use pkg in the file scope but create
// a new object instead; the Decl field is different
// for different files)
obj := NewObj(Pkg, name)
obj.Decl = spec
obj.Data = pkg.Data
p.declare(fileScope, pkgScope, obj)
}
}
// resolve identifiers
if importErrors {
// don't use the universe scope without correct imports
// (objects in the universe may be shadowed by imports;
// with missing imports, identifiers might get resolved
// incorrectly to universe objects)
pkgScope.Outer = nil
}
i := 0
for _, ident := range file.Unresolved {
if !resolve(fileScope, ident) {
p.errorf(ident.Pos(), "undeclared name: %s", ident.Name)
file.Unresolved[i] = ident
i++
}
}
file.Unresolved = file.Unresolved[0:i]
pkgScope.Outer = universe // reset universe scope
}
return &Package{pkgName, pkgScope, imports, files}, p.GetError(scanner.Sorted)
} | go | func NewPackage(fset *token.FileSet, files map[string]*File, importer Importer, universe *Scope) (*Package, error) {
var p pkgBuilder
p.fset = fset
// complete package scope
pkgName := ""
pkgScope := NewScope(universe)
for _, file := range files {
// package names must match
switch name := file.Name.Name; {
case pkgName == "":
pkgName = name
case name != pkgName:
p.errorf(file.Package, "package %s; expected %s", name, pkgName)
continue // ignore this file
}
// collect top-level file objects in package scope
for _, obj := range file.Scope.Objects {
p.declare(pkgScope, nil, obj)
}
}
// package global mapping of imported package ids to package objects
imports := make(map[string]*Object)
// complete file scopes with imports and resolve identifiers
for _, file := range files {
// ignore file if it belongs to a different package
// (error has already been reported)
if file.Name.Name != pkgName {
continue
}
// build file scope by processing all imports
importErrors := false
fileScope := NewScope(pkgScope)
for _, spec := range file.Imports {
if importer == nil {
importErrors = true
continue
}
path, _ := strconv.Unquote(string(spec.Path.Value))
pkg, err := importer(imports, path)
if err != nil {
p.errorf(spec.Path.Pos(), "could not import %s (%s)", path, err)
importErrors = true
continue
}
// TODO(gri) If a local package name != "." is provided,
// global identifier resolution could proceed even if the
// import failed. Consider adjusting the logic here a bit.
// local name overrides imported package name
name := pkg.Name
if spec.Name != nil {
name = spec.Name.Name
}
// add import to file scope
if name == "." {
// merge imported scope with file scope
for _, obj := range pkg.Data.(*Scope).Objects {
p.declare(fileScope, pkgScope, obj)
}
} else {
// declare imported package object in file scope
// (do not re-use pkg in the file scope but create
// a new object instead; the Decl field is different
// for different files)
obj := NewObj(Pkg, name)
obj.Decl = spec
obj.Data = pkg.Data
p.declare(fileScope, pkgScope, obj)
}
}
// resolve identifiers
if importErrors {
// don't use the universe scope without correct imports
// (objects in the universe may be shadowed by imports;
// with missing imports, identifiers might get resolved
// incorrectly to universe objects)
pkgScope.Outer = nil
}
i := 0
for _, ident := range file.Unresolved {
if !resolve(fileScope, ident) {
p.errorf(ident.Pos(), "undeclared name: %s", ident.Name)
file.Unresolved[i] = ident
i++
}
}
file.Unresolved = file.Unresolved[0:i]
pkgScope.Outer = universe // reset universe scope
}
return &Package{pkgName, pkgScope, imports, files}, p.GetError(scanner.Sorted)
} | [
"func",
"NewPackage",
"(",
"fset",
"*",
"token",
".",
"FileSet",
",",
"files",
"map",
"[",
"string",
"]",
"*",
"File",
",",
"importer",
"Importer",
",",
"universe",
"*",
"Scope",
")",
"(",
"*",
"Package",
",",
"error",
")",
"{",
"var",
"p",
"pkgBuilder",
"\n",
"p",
".",
"fset",
"=",
"fset",
"\n\n",
"// complete package scope",
"pkgName",
":=",
"\"",
"\"",
"\n",
"pkgScope",
":=",
"NewScope",
"(",
"universe",
")",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"files",
"{",
"// package names must match",
"switch",
"name",
":=",
"file",
".",
"Name",
".",
"Name",
";",
"{",
"case",
"pkgName",
"==",
"\"",
"\"",
":",
"pkgName",
"=",
"name",
"\n",
"case",
"name",
"!=",
"pkgName",
":",
"p",
".",
"errorf",
"(",
"file",
".",
"Package",
",",
"\"",
"\"",
",",
"name",
",",
"pkgName",
")",
"\n",
"continue",
"// ignore this file",
"\n",
"}",
"\n\n",
"// collect top-level file objects in package scope",
"for",
"_",
",",
"obj",
":=",
"range",
"file",
".",
"Scope",
".",
"Objects",
"{",
"p",
".",
"declare",
"(",
"pkgScope",
",",
"nil",
",",
"obj",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// package global mapping of imported package ids to package objects",
"imports",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"Object",
")",
"\n\n",
"// complete file scopes with imports and resolve identifiers",
"for",
"_",
",",
"file",
":=",
"range",
"files",
"{",
"// ignore file if it belongs to a different package",
"// (error has already been reported)",
"if",
"file",
".",
"Name",
".",
"Name",
"!=",
"pkgName",
"{",
"continue",
"\n",
"}",
"\n\n",
"// build file scope by processing all imports",
"importErrors",
":=",
"false",
"\n",
"fileScope",
":=",
"NewScope",
"(",
"pkgScope",
")",
"\n",
"for",
"_",
",",
"spec",
":=",
"range",
"file",
".",
"Imports",
"{",
"if",
"importer",
"==",
"nil",
"{",
"importErrors",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"path",
",",
"_",
":=",
"strconv",
".",
"Unquote",
"(",
"string",
"(",
"spec",
".",
"Path",
".",
"Value",
")",
")",
"\n",
"pkg",
",",
"err",
":=",
"importer",
"(",
"imports",
",",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"errorf",
"(",
"spec",
".",
"Path",
".",
"Pos",
"(",
")",
",",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"importErrors",
"=",
"true",
"\n",
"continue",
"\n",
"}",
"\n",
"// TODO(gri) If a local package name != \".\" is provided,",
"// global identifier resolution could proceed even if the",
"// import failed. Consider adjusting the logic here a bit.",
"// local name overrides imported package name",
"name",
":=",
"pkg",
".",
"Name",
"\n",
"if",
"spec",
".",
"Name",
"!=",
"nil",
"{",
"name",
"=",
"spec",
".",
"Name",
".",
"Name",
"\n",
"}",
"\n\n",
"// add import to file scope",
"if",
"name",
"==",
"\"",
"\"",
"{",
"// merge imported scope with file scope",
"for",
"_",
",",
"obj",
":=",
"range",
"pkg",
".",
"Data",
".",
"(",
"*",
"Scope",
")",
".",
"Objects",
"{",
"p",
".",
"declare",
"(",
"fileScope",
",",
"pkgScope",
",",
"obj",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// declare imported package object in file scope",
"// (do not re-use pkg in the file scope but create",
"// a new object instead; the Decl field is different",
"// for different files)",
"obj",
":=",
"NewObj",
"(",
"Pkg",
",",
"name",
")",
"\n",
"obj",
".",
"Decl",
"=",
"spec",
"\n",
"obj",
".",
"Data",
"=",
"pkg",
".",
"Data",
"\n",
"p",
".",
"declare",
"(",
"fileScope",
",",
"pkgScope",
",",
"obj",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// resolve identifiers",
"if",
"importErrors",
"{",
"// don't use the universe scope without correct imports",
"// (objects in the universe may be shadowed by imports;",
"// with missing imports, identifiers might get resolved",
"// incorrectly to universe objects)",
"pkgScope",
".",
"Outer",
"=",
"nil",
"\n",
"}",
"\n",
"i",
":=",
"0",
"\n",
"for",
"_",
",",
"ident",
":=",
"range",
"file",
".",
"Unresolved",
"{",
"if",
"!",
"resolve",
"(",
"fileScope",
",",
"ident",
")",
"{",
"p",
".",
"errorf",
"(",
"ident",
".",
"Pos",
"(",
")",
",",
"\"",
"\"",
",",
"ident",
".",
"Name",
")",
"\n",
"file",
".",
"Unresolved",
"[",
"i",
"]",
"=",
"ident",
"\n",
"i",
"++",
"\n",
"}",
"\n\n",
"}",
"\n",
"file",
".",
"Unresolved",
"=",
"file",
".",
"Unresolved",
"[",
"0",
":",
"i",
"]",
"\n",
"pkgScope",
".",
"Outer",
"=",
"universe",
"// reset universe scope",
"\n",
"}",
"\n\n",
"return",
"&",
"Package",
"{",
"pkgName",
",",
"pkgScope",
",",
"imports",
",",
"files",
"}",
",",
"p",
".",
"GetError",
"(",
"scanner",
".",
"Sorted",
")",
"\n",
"}"
] | // NewPackage creates a new Package node from a set of File nodes. It resolves
// unresolved identifiers across files and updates each file's Unresolved list
// accordingly. If a non-nil importer and universe scope are provided, they are
// used to resolve identifiers not declared in any of the package files. Any
// remaining unresolved identifiers are reported as undeclared. If the files
// belong to different packages, one package name is selected and files with
// different package names are reported and then ignored.
// The result is a package node and a scanner.ErrorList if there were errors.
// | [
"NewPackage",
"creates",
"a",
"new",
"Package",
"node",
"from",
"a",
"set",
"of",
"File",
"nodes",
".",
"It",
"resolves",
"unresolved",
"identifiers",
"across",
"files",
"and",
"updates",
"each",
"file",
"s",
"Unresolved",
"list",
"accordingly",
".",
"If",
"a",
"non",
"-",
"nil",
"importer",
"and",
"universe",
"scope",
"are",
"provided",
"they",
"are",
"used",
"to",
"resolve",
"identifiers",
"not",
"declared",
"in",
"any",
"of",
"the",
"package",
"files",
".",
"Any",
"remaining",
"unresolved",
"identifiers",
"are",
"reported",
"as",
"undeclared",
".",
"If",
"the",
"files",
"belong",
"to",
"different",
"packages",
"one",
"package",
"name",
"is",
"selected",
"and",
"files",
"with",
"different",
"package",
"names",
"are",
"reported",
"and",
"then",
"ignored",
".",
"The",
"result",
"is",
"a",
"package",
"node",
"and",
"a",
"scanner",
".",
"ErrorList",
"if",
"there",
"were",
"errors",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/ast/resolve.go#L75-L174 |
152,694 | rogpeppe/godef | go/printer/printer.go | nlines | func (p *printer) nlines(n, min int) int {
const max = 2 // max. number of newlines
switch {
case n < min:
return min
case n > max:
return max
}
return n
} | go | func (p *printer) nlines(n, min int) int {
const max = 2 // max. number of newlines
switch {
case n < min:
return min
case n > max:
return max
}
return n
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"nlines",
"(",
"n",
",",
"min",
"int",
")",
"int",
"{",
"const",
"max",
"=",
"2",
"// max. number of newlines",
"\n",
"switch",
"{",
"case",
"n",
"<",
"min",
":",
"return",
"min",
"\n",
"case",
"n",
">",
"max",
":",
"return",
"max",
"\n",
"}",
"\n",
"return",
"n",
"\n",
"}"
] | // nlines returns the adjusted number of linebreaks given the desired number
// of breaks n such that min <= result <= max.
// | [
"nlines",
"returns",
"the",
"adjusted",
"number",
"of",
"linebreaks",
"given",
"the",
"desired",
"number",
"of",
"breaks",
"n",
"such",
"that",
"min",
"<",
"=",
"result",
"<",
"=",
"max",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L127-L136 |
152,695 | rogpeppe/godef | go/printer/printer.go | write | func (p *printer) write(data []byte) {
i0 := 0
for i, b := range data {
switch b {
case '\n', '\f':
// write segment ending in b
p.write0(data[i0 : i+1])
// update p.pos
p.pos.Offset += i + 1 - i0
p.pos.Line++
p.pos.Column = 1
if p.mode&inLiteral == 0 {
// write indentation
// use "hard" htabs - indentation columns
// must not be discarded by the tabwriter
j := p.indent
for ; j > len(htabs); j -= len(htabs) {
p.write0(htabs)
}
p.write0(htabs[0:j])
// update p.pos
p.pos.Offset += p.indent
p.pos.Column += p.indent
}
// next segment start
i0 = i + 1
case tabwriter.Escape:
p.mode ^= inLiteral
// ignore escape chars introduced by printer - they are
// invisible and must not affect p.pos (was issue #1089)
p.pos.Offset--
p.pos.Column--
}
}
// write remaining segment
p.write0(data[i0:])
// update p.pos
d := len(data) - i0
p.pos.Offset += d
p.pos.Column += d
} | go | func (p *printer) write(data []byte) {
i0 := 0
for i, b := range data {
switch b {
case '\n', '\f':
// write segment ending in b
p.write0(data[i0 : i+1])
// update p.pos
p.pos.Offset += i + 1 - i0
p.pos.Line++
p.pos.Column = 1
if p.mode&inLiteral == 0 {
// write indentation
// use "hard" htabs - indentation columns
// must not be discarded by the tabwriter
j := p.indent
for ; j > len(htabs); j -= len(htabs) {
p.write0(htabs)
}
p.write0(htabs[0:j])
// update p.pos
p.pos.Offset += p.indent
p.pos.Column += p.indent
}
// next segment start
i0 = i + 1
case tabwriter.Escape:
p.mode ^= inLiteral
// ignore escape chars introduced by printer - they are
// invisible and must not affect p.pos (was issue #1089)
p.pos.Offset--
p.pos.Column--
}
}
// write remaining segment
p.write0(data[i0:])
// update p.pos
d := len(data) - i0
p.pos.Offset += d
p.pos.Column += d
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"write",
"(",
"data",
"[",
"]",
"byte",
")",
"{",
"i0",
":=",
"0",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"data",
"{",
"switch",
"b",
"{",
"case",
"'\\n'",
",",
"'\\f'",
":",
"// write segment ending in b",
"p",
".",
"write0",
"(",
"data",
"[",
"i0",
":",
"i",
"+",
"1",
"]",
")",
"\n\n",
"// update p.pos",
"p",
".",
"pos",
".",
"Offset",
"+=",
"i",
"+",
"1",
"-",
"i0",
"\n",
"p",
".",
"pos",
".",
"Line",
"++",
"\n",
"p",
".",
"pos",
".",
"Column",
"=",
"1",
"\n\n",
"if",
"p",
".",
"mode",
"&",
"inLiteral",
"==",
"0",
"{",
"// write indentation",
"// use \"hard\" htabs - indentation columns",
"// must not be discarded by the tabwriter",
"j",
":=",
"p",
".",
"indent",
"\n",
"for",
";",
"j",
">",
"len",
"(",
"htabs",
")",
";",
"j",
"-=",
"len",
"(",
"htabs",
")",
"{",
"p",
".",
"write0",
"(",
"htabs",
")",
"\n",
"}",
"\n",
"p",
".",
"write0",
"(",
"htabs",
"[",
"0",
":",
"j",
"]",
")",
"\n\n",
"// update p.pos",
"p",
".",
"pos",
".",
"Offset",
"+=",
"p",
".",
"indent",
"\n",
"p",
".",
"pos",
".",
"Column",
"+=",
"p",
".",
"indent",
"\n",
"}",
"\n\n",
"// next segment start",
"i0",
"=",
"i",
"+",
"1",
"\n\n",
"case",
"tabwriter",
".",
"Escape",
":",
"p",
".",
"mode",
"^=",
"inLiteral",
"\n\n",
"// ignore escape chars introduced by printer - they are",
"// invisible and must not affect p.pos (was issue #1089)",
"p",
".",
"pos",
".",
"Offset",
"--",
"\n",
"p",
".",
"pos",
".",
"Column",
"--",
"\n",
"}",
"\n",
"}",
"\n\n",
"// write remaining segment",
"p",
".",
"write0",
"(",
"data",
"[",
"i0",
":",
"]",
")",
"\n\n",
"// update p.pos",
"d",
":=",
"len",
"(",
"data",
")",
"-",
"i0",
"\n",
"p",
".",
"pos",
".",
"Offset",
"+=",
"d",
"\n",
"p",
".",
"pos",
".",
"Column",
"+=",
"d",
"\n",
"}"
] | // write interprets data and writes it to p.output. It inserts indentation
// after a line break unless in a tabwriter escape sequence.
// It updates p.pos as a side-effect.
// | [
"write",
"interprets",
"data",
"and",
"writes",
"it",
"to",
"p",
".",
"output",
".",
"It",
"inserts",
"indentation",
"after",
"a",
"line",
"break",
"unless",
"in",
"a",
"tabwriter",
"escape",
"sequence",
".",
"It",
"updates",
"p",
".",
"pos",
"as",
"a",
"side",
"-",
"effect",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L156-L204 |
152,696 | rogpeppe/godef | go/printer/printer.go | writeWhitespace | func (p *printer) writeWhitespace(n int) {
// write entries
var data [1]byte
for i := 0; i < n; i++ {
switch ch := p.wsbuf[i]; ch {
case ignore:
// ignore!
case indent:
p.indent++
case unindent:
p.indent--
if p.indent < 0 {
p.internalError("negative indentation:", p.indent)
p.indent = 0
}
case newline, formfeed:
// A line break immediately followed by a "correcting"
// unindent is swapped with the unindent - this permits
// proper label positioning. If a comment is between
// the line break and the label, the unindent is not
// part of the comment whitespace prefix and the comment
// will be positioned correctly indented.
if i+1 < n && p.wsbuf[i+1] == unindent {
// Use a formfeed to terminate the current section.
// Otherwise, a long label name on the next line leading
// to a wide column may increase the indentation column
// of lines before the label; effectively leading to wrong
// indentation.
p.wsbuf[i], p.wsbuf[i+1] = unindent, formfeed
i-- // do it again
continue
}
fallthrough
default:
data[0] = byte(ch)
p.write(data[0:])
}
}
// shift remaining entries down
i := 0
for ; n < len(p.wsbuf); n++ {
p.wsbuf[i] = p.wsbuf[n]
i++
}
p.wsbuf = p.wsbuf[0:i]
} | go | func (p *printer) writeWhitespace(n int) {
// write entries
var data [1]byte
for i := 0; i < n; i++ {
switch ch := p.wsbuf[i]; ch {
case ignore:
// ignore!
case indent:
p.indent++
case unindent:
p.indent--
if p.indent < 0 {
p.internalError("negative indentation:", p.indent)
p.indent = 0
}
case newline, formfeed:
// A line break immediately followed by a "correcting"
// unindent is swapped with the unindent - this permits
// proper label positioning. If a comment is between
// the line break and the label, the unindent is not
// part of the comment whitespace prefix and the comment
// will be positioned correctly indented.
if i+1 < n && p.wsbuf[i+1] == unindent {
// Use a formfeed to terminate the current section.
// Otherwise, a long label name on the next line leading
// to a wide column may increase the indentation column
// of lines before the label; effectively leading to wrong
// indentation.
p.wsbuf[i], p.wsbuf[i+1] = unindent, formfeed
i-- // do it again
continue
}
fallthrough
default:
data[0] = byte(ch)
p.write(data[0:])
}
}
// shift remaining entries down
i := 0
for ; n < len(p.wsbuf); n++ {
p.wsbuf[i] = p.wsbuf[n]
i++
}
p.wsbuf = p.wsbuf[0:i]
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"writeWhitespace",
"(",
"n",
"int",
")",
"{",
"// write entries",
"var",
"data",
"[",
"1",
"]",
"byte",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"switch",
"ch",
":=",
"p",
".",
"wsbuf",
"[",
"i",
"]",
";",
"ch",
"{",
"case",
"ignore",
":",
"// ignore!",
"case",
"indent",
":",
"p",
".",
"indent",
"++",
"\n",
"case",
"unindent",
":",
"p",
".",
"indent",
"--",
"\n",
"if",
"p",
".",
"indent",
"<",
"0",
"{",
"p",
".",
"internalError",
"(",
"\"",
"\"",
",",
"p",
".",
"indent",
")",
"\n",
"p",
".",
"indent",
"=",
"0",
"\n",
"}",
"\n",
"case",
"newline",
",",
"formfeed",
":",
"// A line break immediately followed by a \"correcting\"",
"// unindent is swapped with the unindent - this permits",
"// proper label positioning. If a comment is between",
"// the line break and the label, the unindent is not",
"// part of the comment whitespace prefix and the comment",
"// will be positioned correctly indented.",
"if",
"i",
"+",
"1",
"<",
"n",
"&&",
"p",
".",
"wsbuf",
"[",
"i",
"+",
"1",
"]",
"==",
"unindent",
"{",
"// Use a formfeed to terminate the current section.",
"// Otherwise, a long label name on the next line leading",
"// to a wide column may increase the indentation column",
"// of lines before the label; effectively leading to wrong",
"// indentation.",
"p",
".",
"wsbuf",
"[",
"i",
"]",
",",
"p",
".",
"wsbuf",
"[",
"i",
"+",
"1",
"]",
"=",
"unindent",
",",
"formfeed",
"\n",
"i",
"--",
"// do it again",
"\n",
"continue",
"\n",
"}",
"\n",
"fallthrough",
"\n",
"default",
":",
"data",
"[",
"0",
"]",
"=",
"byte",
"(",
"ch",
")",
"\n",
"p",
".",
"write",
"(",
"data",
"[",
"0",
":",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// shift remaining entries down",
"i",
":=",
"0",
"\n",
"for",
";",
"n",
"<",
"len",
"(",
"p",
".",
"wsbuf",
")",
";",
"n",
"++",
"{",
"p",
".",
"wsbuf",
"[",
"i",
"]",
"=",
"p",
".",
"wsbuf",
"[",
"n",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"p",
".",
"wsbuf",
"=",
"p",
".",
"wsbuf",
"[",
"0",
":",
"i",
"]",
"\n",
"}"
] | // whiteWhitespace writes the first n whitespace entries. | [
"whiteWhitespace",
"writes",
"the",
"first",
"n",
"whitespace",
"entries",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L628-L674 |
152,697 | rogpeppe/godef | go/printer/printer.go | commentBefore | func (p *printer) commentBefore(next token.Position) bool {
return p.cindex < len(p.comments) && p.fset.Position(p.comments[p.cindex].List[0].Pos()).Offset < next.Offset
} | go | func (p *printer) commentBefore(next token.Position) bool {
return p.cindex < len(p.comments) && p.fset.Position(p.comments[p.cindex].List[0].Pos()).Offset < next.Offset
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"commentBefore",
"(",
"next",
"token",
".",
"Position",
")",
"bool",
"{",
"return",
"p",
".",
"cindex",
"<",
"len",
"(",
"p",
".",
"comments",
")",
"&&",
"p",
".",
"fset",
".",
"Position",
"(",
"p",
".",
"comments",
"[",
"p",
".",
"cindex",
"]",
".",
"List",
"[",
"0",
"]",
".",
"Pos",
"(",
")",
")",
".",
"Offset",
"<",
"next",
".",
"Offset",
"\n",
"}"
] | // commentBefore returns true iff the current comment occurs
// before the next position in the source code.
// | [
"commentBefore",
"returns",
"true",
"iff",
"the",
"current",
"comment",
"occurs",
"before",
"the",
"next",
"position",
"in",
"the",
"source",
"code",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L789-L791 |
152,698 | rogpeppe/godef | go/printer/printer.go | flush | func (p *printer) flush(next token.Position, tok token.Token) (droppedFF bool) {
if p.commentBefore(next) {
// if there are comments before the next item, intersperse them
droppedFF = p.intersperseComments(next, tok)
} else {
// otherwise, write any leftover whitespace
p.writeWhitespace(len(p.wsbuf))
}
return
} | go | func (p *printer) flush(next token.Position, tok token.Token) (droppedFF bool) {
if p.commentBefore(next) {
// if there are comments before the next item, intersperse them
droppedFF = p.intersperseComments(next, tok)
} else {
// otherwise, write any leftover whitespace
p.writeWhitespace(len(p.wsbuf))
}
return
} | [
"func",
"(",
"p",
"*",
"printer",
")",
"flush",
"(",
"next",
"token",
".",
"Position",
",",
"tok",
"token",
".",
"Token",
")",
"(",
"droppedFF",
"bool",
")",
"{",
"if",
"p",
".",
"commentBefore",
"(",
"next",
")",
"{",
"// if there are comments before the next item, intersperse them",
"droppedFF",
"=",
"p",
".",
"intersperseComments",
"(",
"next",
",",
"tok",
")",
"\n",
"}",
"else",
"{",
"// otherwise, write any leftover whitespace",
"p",
".",
"writeWhitespace",
"(",
"len",
"(",
"p",
".",
"wsbuf",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Flush prints any pending comments and whitespace occurring
// textually before the position of the next token tok. Flush
// returns true if a pending formfeed character was dropped
// from the whitespace buffer as a result of interspersing
// comments.
// | [
"Flush",
"prints",
"any",
"pending",
"comments",
"and",
"whitespace",
"occurring",
"textually",
"before",
"the",
"position",
"of",
"the",
"next",
"token",
"tok",
".",
"Flush",
"returns",
"true",
"if",
"a",
"pending",
"formfeed",
"character",
"was",
"dropped",
"from",
"the",
"whitespace",
"buffer",
"as",
"a",
"result",
"of",
"interspersing",
"comments",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L799-L808 |
152,699 | rogpeppe/godef | go/printer/printer.go | fprint | func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{}, nodeSizes map[ast.Node]int) (int, error) {
// redirect output through a trimmer to eliminate trailing whitespace
// (Input to a tabwriter must be untrimmed since trailing tabs provide
// formatting information. The tabwriter could provide trimming
// functionality but no tabwriter is used when RawFormat is set.)
output = &trimmer{output: output}
// setup tabwriter if needed and redirect output
var tw *tabwriter.Writer
if cfg.Mode&RawFormat == 0 {
minwidth := cfg.Tabwidth
padchar := byte('\t')
if cfg.Mode&UseSpaces != 0 {
padchar = ' '
}
twmode := tabwriter.DiscardEmptyColumns
if cfg.Mode&TabIndent != 0 {
minwidth = 0
twmode |= tabwriter.TabIndent
}
tw = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode)
output = tw
}
// setup printer and print node
var p printer
p.init(output, cfg, fset, nodeSizes)
go func() {
switch n := node.(type) {
case ast.Expr:
p.useNodeComments = true
p.expr(n, ignoreMultiLine)
case ast.Stmt:
p.useNodeComments = true
// A labeled statement will un-indent to position the
// label. Set indent to 1 so we don't get indent "underflow".
if _, labeledStmt := n.(*ast.LabeledStmt); labeledStmt {
p.indent = 1
}
p.stmt(n, false, ignoreMultiLine)
case ast.Decl:
p.useNodeComments = true
p.decl(n, ignoreMultiLine)
case ast.Spec:
p.useNodeComments = true
p.spec(n, 1, false, ignoreMultiLine)
case *ast.File:
p.comments = n.Comments
p.useNodeComments = n.Comments == nil
p.file(n)
default:
p.errors <- fmt.Errorf("printer.Fprint: unsupported node type %T", n)
runtime.Goexit()
}
p.flush(token.Position{Offset: infinity, Line: infinity}, token.EOF)
p.errors <- nil // no errors
}()
err := <-p.errors // wait for completion of goroutine
// flush tabwriter, if any
if tw != nil {
tw.Flush() // ignore errors
}
return p.written, err
} | go | func (cfg *Config) fprint(output io.Writer, fset *token.FileSet, node interface{}, nodeSizes map[ast.Node]int) (int, error) {
// redirect output through a trimmer to eliminate trailing whitespace
// (Input to a tabwriter must be untrimmed since trailing tabs provide
// formatting information. The tabwriter could provide trimming
// functionality but no tabwriter is used when RawFormat is set.)
output = &trimmer{output: output}
// setup tabwriter if needed and redirect output
var tw *tabwriter.Writer
if cfg.Mode&RawFormat == 0 {
minwidth := cfg.Tabwidth
padchar := byte('\t')
if cfg.Mode&UseSpaces != 0 {
padchar = ' '
}
twmode := tabwriter.DiscardEmptyColumns
if cfg.Mode&TabIndent != 0 {
minwidth = 0
twmode |= tabwriter.TabIndent
}
tw = tabwriter.NewWriter(output, minwidth, cfg.Tabwidth, 1, padchar, twmode)
output = tw
}
// setup printer and print node
var p printer
p.init(output, cfg, fset, nodeSizes)
go func() {
switch n := node.(type) {
case ast.Expr:
p.useNodeComments = true
p.expr(n, ignoreMultiLine)
case ast.Stmt:
p.useNodeComments = true
// A labeled statement will un-indent to position the
// label. Set indent to 1 so we don't get indent "underflow".
if _, labeledStmt := n.(*ast.LabeledStmt); labeledStmt {
p.indent = 1
}
p.stmt(n, false, ignoreMultiLine)
case ast.Decl:
p.useNodeComments = true
p.decl(n, ignoreMultiLine)
case ast.Spec:
p.useNodeComments = true
p.spec(n, 1, false, ignoreMultiLine)
case *ast.File:
p.comments = n.Comments
p.useNodeComments = n.Comments == nil
p.file(n)
default:
p.errors <- fmt.Errorf("printer.Fprint: unsupported node type %T", n)
runtime.Goexit()
}
p.flush(token.Position{Offset: infinity, Line: infinity}, token.EOF)
p.errors <- nil // no errors
}()
err := <-p.errors // wait for completion of goroutine
// flush tabwriter, if any
if tw != nil {
tw.Flush() // ignore errors
}
return p.written, err
} | [
"func",
"(",
"cfg",
"*",
"Config",
")",
"fprint",
"(",
"output",
"io",
".",
"Writer",
",",
"fset",
"*",
"token",
".",
"FileSet",
",",
"node",
"interface",
"{",
"}",
",",
"nodeSizes",
"map",
"[",
"ast",
".",
"Node",
"]",
"int",
")",
"(",
"int",
",",
"error",
")",
"{",
"// redirect output through a trimmer to eliminate trailing whitespace",
"// (Input to a tabwriter must be untrimmed since trailing tabs provide",
"// formatting information. The tabwriter could provide trimming",
"// functionality but no tabwriter is used when RawFormat is set.)",
"output",
"=",
"&",
"trimmer",
"{",
"output",
":",
"output",
"}",
"\n\n",
"// setup tabwriter if needed and redirect output",
"var",
"tw",
"*",
"tabwriter",
".",
"Writer",
"\n",
"if",
"cfg",
".",
"Mode",
"&",
"RawFormat",
"==",
"0",
"{",
"minwidth",
":=",
"cfg",
".",
"Tabwidth",
"\n\n",
"padchar",
":=",
"byte",
"(",
"'\\t'",
")",
"\n",
"if",
"cfg",
".",
"Mode",
"&",
"UseSpaces",
"!=",
"0",
"{",
"padchar",
"=",
"' '",
"\n",
"}",
"\n\n",
"twmode",
":=",
"tabwriter",
".",
"DiscardEmptyColumns",
"\n",
"if",
"cfg",
".",
"Mode",
"&",
"TabIndent",
"!=",
"0",
"{",
"minwidth",
"=",
"0",
"\n",
"twmode",
"|=",
"tabwriter",
".",
"TabIndent",
"\n",
"}",
"\n\n",
"tw",
"=",
"tabwriter",
".",
"NewWriter",
"(",
"output",
",",
"minwidth",
",",
"cfg",
".",
"Tabwidth",
",",
"1",
",",
"padchar",
",",
"twmode",
")",
"\n",
"output",
"=",
"tw",
"\n",
"}",
"\n\n",
"// setup printer and print node",
"var",
"p",
"printer",
"\n",
"p",
".",
"init",
"(",
"output",
",",
"cfg",
",",
"fset",
",",
"nodeSizes",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"switch",
"n",
":=",
"node",
".",
"(",
"type",
")",
"{",
"case",
"ast",
".",
"Expr",
":",
"p",
".",
"useNodeComments",
"=",
"true",
"\n",
"p",
".",
"expr",
"(",
"n",
",",
"ignoreMultiLine",
")",
"\n",
"case",
"ast",
".",
"Stmt",
":",
"p",
".",
"useNodeComments",
"=",
"true",
"\n",
"// A labeled statement will un-indent to position the",
"// label. Set indent to 1 so we don't get indent \"underflow\".",
"if",
"_",
",",
"labeledStmt",
":=",
"n",
".",
"(",
"*",
"ast",
".",
"LabeledStmt",
")",
";",
"labeledStmt",
"{",
"p",
".",
"indent",
"=",
"1",
"\n",
"}",
"\n",
"p",
".",
"stmt",
"(",
"n",
",",
"false",
",",
"ignoreMultiLine",
")",
"\n",
"case",
"ast",
".",
"Decl",
":",
"p",
".",
"useNodeComments",
"=",
"true",
"\n",
"p",
".",
"decl",
"(",
"n",
",",
"ignoreMultiLine",
")",
"\n",
"case",
"ast",
".",
"Spec",
":",
"p",
".",
"useNodeComments",
"=",
"true",
"\n",
"p",
".",
"spec",
"(",
"n",
",",
"1",
",",
"false",
",",
"ignoreMultiLine",
")",
"\n",
"case",
"*",
"ast",
".",
"File",
":",
"p",
".",
"comments",
"=",
"n",
".",
"Comments",
"\n",
"p",
".",
"useNodeComments",
"=",
"n",
".",
"Comments",
"==",
"nil",
"\n",
"p",
".",
"file",
"(",
"n",
")",
"\n",
"default",
":",
"p",
".",
"errors",
"<-",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"n",
")",
"\n",
"runtime",
".",
"Goexit",
"(",
")",
"\n",
"}",
"\n",
"p",
".",
"flush",
"(",
"token",
".",
"Position",
"{",
"Offset",
":",
"infinity",
",",
"Line",
":",
"infinity",
"}",
",",
"token",
".",
"EOF",
")",
"\n",
"p",
".",
"errors",
"<-",
"nil",
"// no errors",
"\n",
"}",
"(",
")",
"\n",
"err",
":=",
"<-",
"p",
".",
"errors",
"// wait for completion of goroutine",
"\n\n",
"// flush tabwriter, if any",
"if",
"tw",
"!=",
"nil",
"{",
"tw",
".",
"Flush",
"(",
")",
"// ignore errors",
"\n",
"}",
"\n\n",
"return",
"p",
".",
"written",
",",
"err",
"\n",
"}"
] | // fprint implements Fprint and takes a nodesSizes map for setting up the printer state. | [
"fprint",
"implements",
"Fprint",
"and",
"takes",
"a",
"nodesSizes",
"map",
"for",
"setting",
"up",
"the",
"printer",
"state",
"."
] | 5784335da72394c8f53d9036c26fcc876718879b | https://github.com/rogpeppe/godef/blob/5784335da72394c8f53d9036c26fcc876718879b/go/printer/printer.go#L927-L995 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.