repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
list | docstring
stringlengths 6
2.61k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
remind101/empire
|
pkg/heroku/oauth_authorization.go
|
OAuthAuthorizationCreate
|
func (c *Client) OAuthAuthorizationCreate(scope []string, options *OAuthAuthorizationCreateOpts) (*OAuthAuthorization, error) {
params := struct {
Scope []string `json:"scope"`
Client *string `json:"client,omitempty"`
Description *string `json:"description,omitempty"`
ExpiresIn *int `json:"expires_in,omitempty"`
}{
Scope: scope,
}
if options != nil {
params.Client = options.Client
params.Description = options.Description
params.ExpiresIn = options.ExpiresIn
}
var oauthAuthorizationRes OAuthAuthorization
return &oauthAuthorizationRes, c.Post(&oauthAuthorizationRes, "/oauth/authorizations", params)
}
|
go
|
func (c *Client) OAuthAuthorizationCreate(scope []string, options *OAuthAuthorizationCreateOpts) (*OAuthAuthorization, error) {
params := struct {
Scope []string `json:"scope"`
Client *string `json:"client,omitempty"`
Description *string `json:"description,omitempty"`
ExpiresIn *int `json:"expires_in,omitempty"`
}{
Scope: scope,
}
if options != nil {
params.Client = options.Client
params.Description = options.Description
params.ExpiresIn = options.ExpiresIn
}
var oauthAuthorizationRes OAuthAuthorization
return &oauthAuthorizationRes, c.Post(&oauthAuthorizationRes, "/oauth/authorizations", params)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthAuthorizationCreate",
"(",
"scope",
"[",
"]",
"string",
",",
"options",
"*",
"OAuthAuthorizationCreateOpts",
")",
"(",
"*",
"OAuthAuthorization",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Scope",
"[",
"]",
"string",
"`json:\"scope\"`",
"\n",
"Client",
"*",
"string",
"`json:\"client,omitempty\"`",
"\n",
"Description",
"*",
"string",
"`json:\"description,omitempty\"`",
"\n",
"ExpiresIn",
"*",
"int",
"`json:\"expires_in,omitempty\"`",
"\n",
"}",
"{",
"Scope",
":",
"scope",
",",
"}",
"\n",
"if",
"options",
"!=",
"nil",
"{",
"params",
".",
"Client",
"=",
"options",
".",
"Client",
"\n",
"params",
".",
"Description",
"=",
"options",
".",
"Description",
"\n",
"params",
".",
"ExpiresIn",
"=",
"options",
".",
"ExpiresIn",
"\n",
"}",
"\n",
"var",
"oauthAuthorizationRes",
"OAuthAuthorization",
"\n",
"return",
"&",
"oauthAuthorizationRes",
",",
"c",
".",
"Post",
"(",
"&",
"oauthAuthorizationRes",
",",
"\"",
"\"",
",",
"params",
")",
"\n",
"}"
] |
// Create a new OAuth authorization.
//
// scope is the The scope of access OAuth authorization allows. options is the
// struct of optional parameters for this action.
|
[
"Create",
"a",
"new",
"OAuth",
"authorization",
".",
"scope",
"is",
"the",
"The",
"scope",
"of",
"access",
"OAuth",
"authorization",
"allows",
".",
"options",
"is",
"the",
"struct",
"of",
"optional",
"parameters",
"for",
"this",
"action",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_authorization.go#L60-L76
|
train
|
remind101/empire
|
pkg/heroku/oauth_authorization.go
|
OAuthAuthorizationInfo
|
func (c *Client) OAuthAuthorizationInfo(oauthAuthorizationIdentity string) (*OAuthAuthorization, error) {
var oauthAuthorization OAuthAuthorization
return &oauthAuthorization, c.Get(&oauthAuthorization, "/oauth/authorizations/"+oauthAuthorizationIdentity)
}
|
go
|
func (c *Client) OAuthAuthorizationInfo(oauthAuthorizationIdentity string) (*OAuthAuthorization, error) {
var oauthAuthorization OAuthAuthorization
return &oauthAuthorization, c.Get(&oauthAuthorization, "/oauth/authorizations/"+oauthAuthorizationIdentity)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthAuthorizationInfo",
"(",
"oauthAuthorizationIdentity",
"string",
")",
"(",
"*",
"OAuthAuthorization",
",",
"error",
")",
"{",
"var",
"oauthAuthorization",
"OAuthAuthorization",
"\n",
"return",
"&",
"oauthAuthorization",
",",
"c",
".",
"Get",
"(",
"&",
"oauthAuthorization",
",",
"\"",
"\"",
"+",
"oauthAuthorizationIdentity",
")",
"\n",
"}"
] |
// Info for an OAuth authorization.
//
// oauthAuthorizationIdentity is the unique identifier of the
// OAuthAuthorization.
|
[
"Info",
"for",
"an",
"OAuth",
"authorization",
".",
"oauthAuthorizationIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OAuthAuthorization",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_authorization.go#L100-L103
|
train
|
remind101/empire
|
pkg/heroku/oauth_authorization.go
|
OAuthAuthorizationList
|
func (c *Client) OAuthAuthorizationList(lr *ListRange) ([]OAuthAuthorization, error) {
req, err := c.NewRequest("GET", "/oauth/authorizations", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var oauthAuthorizationsRes []OAuthAuthorization
return oauthAuthorizationsRes, c.DoReq(req, &oauthAuthorizationsRes)
}
|
go
|
func (c *Client) OAuthAuthorizationList(lr *ListRange) ([]OAuthAuthorization, error) {
req, err := c.NewRequest("GET", "/oauth/authorizations", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var oauthAuthorizationsRes []OAuthAuthorization
return oauthAuthorizationsRes, c.DoReq(req, &oauthAuthorizationsRes)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"OAuthAuthorizationList",
"(",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"OAuthAuthorization",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"lr",
"!=",
"nil",
"{",
"lr",
".",
"SetHeader",
"(",
"req",
")",
"\n",
"}",
"\n\n",
"var",
"oauthAuthorizationsRes",
"[",
"]",
"OAuthAuthorization",
"\n",
"return",
"oauthAuthorizationsRes",
",",
"c",
".",
"DoReq",
"(",
"req",
",",
"&",
"oauthAuthorizationsRes",
")",
"\n",
"}"
] |
// List OAuth authorizations.
//
// lr is an optional ListRange that sets the Range options for the paginated
// list of results.
|
[
"List",
"OAuth",
"authorizations",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",
"of",
"results",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/oauth_authorization.go#L109-L121
|
train
|
remind101/empire
|
server/heroku/authentication.go
|
ExpiresIn
|
func (t *AccessToken) ExpiresIn() time.Duration {
if t.ExpiresAt == nil {
return 0
}
return t.ExpiresAt.Sub(time.Now())
}
|
go
|
func (t *AccessToken) ExpiresIn() time.Duration {
if t.ExpiresAt == nil {
return 0
}
return t.ExpiresAt.Sub(time.Now())
}
|
[
"func",
"(",
"t",
"*",
"AccessToken",
")",
"ExpiresIn",
"(",
")",
"time",
".",
"Duration",
"{",
"if",
"t",
".",
"ExpiresAt",
"==",
"nil",
"{",
"return",
"0",
"\n",
"}",
"\n\n",
"return",
"t",
".",
"ExpiresAt",
".",
"Sub",
"(",
"time",
".",
"Now",
"(",
")",
")",
"\n",
"}"
] |
// Returns the amount of time before the token expires.
|
[
"Returns",
"the",
"amount",
"of",
"time",
"before",
"the",
"token",
"expires",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L32-L38
|
train
|
remind101/empire
|
server/heroku/authentication.go
|
IsValid
|
func (t *AccessToken) IsValid() error {
if err := t.User.IsValid(); err != nil {
return err
}
return nil
}
|
go
|
func (t *AccessToken) IsValid() error {
if err := t.User.IsValid(); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"t",
"*",
"AccessToken",
")",
"IsValid",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"t",
".",
"User",
".",
"IsValid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// IsValid returns nil if the AccessToken is valid.
|
[
"IsValid",
"returns",
"nil",
"if",
"the",
"AccessToken",
"is",
"valid",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L41-L47
|
train
|
remind101/empire
|
server/heroku/authentication.go
|
Authenticate
|
func (a *accessTokenAuthenticator) Authenticate(_ string, token string, _ string) (*auth.Session, error) {
at, err := a.findAccessToken(token)
if err != nil {
return nil, err
}
if at == nil {
return nil, auth.ErrForbidden
}
session := &auth.Session{
User: at.User,
ExpiresAt: at.ExpiresAt,
}
return session, nil
}
|
go
|
func (a *accessTokenAuthenticator) Authenticate(_ string, token string, _ string) (*auth.Session, error) {
at, err := a.findAccessToken(token)
if err != nil {
return nil, err
}
if at == nil {
return nil, auth.ErrForbidden
}
session := &auth.Session{
User: at.User,
ExpiresAt: at.ExpiresAt,
}
return session, nil
}
|
[
"func",
"(",
"a",
"*",
"accessTokenAuthenticator",
")",
"Authenticate",
"(",
"_",
"string",
",",
"token",
"string",
",",
"_",
"string",
")",
"(",
"*",
"auth",
".",
"Session",
",",
"error",
")",
"{",
"at",
",",
"err",
":=",
"a",
".",
"findAccessToken",
"(",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"at",
"==",
"nil",
"{",
"return",
"nil",
",",
"auth",
".",
"ErrForbidden",
"\n",
"}",
"\n\n",
"session",
":=",
"&",
"auth",
".",
"Session",
"{",
"User",
":",
"at",
".",
"User",
",",
"ExpiresAt",
":",
"at",
".",
"ExpiresAt",
",",
"}",
"\n\n",
"return",
"session",
",",
"nil",
"\n",
"}"
] |
// Authenticate authenticates the access token, which should be provided as the
// password parameter. Username and otp are ignored.
|
[
"Authenticate",
"authenticates",
"the",
"access",
"token",
"which",
"should",
"be",
"provided",
"as",
"the",
"password",
"parameter",
".",
"Username",
"and",
"otp",
"are",
"ignored",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L143-L159
|
train
|
remind101/empire
|
server/heroku/authentication.go
|
AccessTokensCreate
|
func (s *Server) AccessTokensCreate(token *AccessToken) (*AccessToken, error) {
signed, err := signToken(s.Secret, token)
if err != nil {
return token, err
}
token.Token = signed
return token, token.IsValid()
}
|
go
|
func (s *Server) AccessTokensCreate(token *AccessToken) (*AccessToken, error) {
signed, err := signToken(s.Secret, token)
if err != nil {
return token, err
}
token.Token = signed
return token, token.IsValid()
}
|
[
"func",
"(",
"s",
"*",
"Server",
")",
"AccessTokensCreate",
"(",
"token",
"*",
"AccessToken",
")",
"(",
"*",
"AccessToken",
",",
"error",
")",
"{",
"signed",
",",
"err",
":=",
"signToken",
"(",
"s",
".",
"Secret",
",",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"token",
",",
"err",
"\n",
"}",
"\n\n",
"token",
".",
"Token",
"=",
"signed",
"\n\n",
"return",
"token",
",",
"token",
".",
"IsValid",
"(",
")",
"\n",
"}"
] |
// AccessTokensCreate "creates" the token by jwt signing it and setting the
// Token value.
|
[
"AccessTokensCreate",
"creates",
"the",
"token",
"by",
"jwt",
"signing",
"it",
"and",
"setting",
"the",
"Token",
"value",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L163-L172
|
train
|
remind101/empire
|
server/heroku/authentication.go
|
signToken
|
func signToken(secret []byte, token *AccessToken) (string, error) {
t := accessTokenToJwt(token)
return t.SignedString(secret)
}
|
go
|
func signToken(secret []byte, token *AccessToken) (string, error) {
t := accessTokenToJwt(token)
return t.SignedString(secret)
}
|
[
"func",
"signToken",
"(",
"secret",
"[",
"]",
"byte",
",",
"token",
"*",
"AccessToken",
")",
"(",
"string",
",",
"error",
")",
"{",
"t",
":=",
"accessTokenToJwt",
"(",
"token",
")",
"\n",
"return",
"t",
".",
"SignedString",
"(",
"secret",
")",
"\n",
"}"
] |
// signToken jwt signs the token and adds the signature to the Token field.
|
[
"signToken",
"jwt",
"signs",
"the",
"token",
"and",
"adds",
"the",
"signature",
"to",
"the",
"Token",
"field",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L193-L196
|
train
|
remind101/empire
|
server/heroku/authentication.go
|
parseToken
|
func parseToken(secret []byte, token string) (*AccessToken, error) {
t, err := jwtParse(secret, token)
if err != nil {
return nil, err
}
if !t.Valid {
return nil, nil
}
return jwtToAccessToken(t)
}
|
go
|
func parseToken(secret []byte, token string) (*AccessToken, error) {
t, err := jwtParse(secret, token)
if err != nil {
return nil, err
}
if !t.Valid {
return nil, nil
}
return jwtToAccessToken(t)
}
|
[
"func",
"parseToken",
"(",
"secret",
"[",
"]",
"byte",
",",
"token",
"string",
")",
"(",
"*",
"AccessToken",
",",
"error",
")",
"{",
"t",
",",
"err",
":=",
"jwtParse",
"(",
"secret",
",",
"token",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"!",
"t",
".",
"Valid",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"jwtToAccessToken",
"(",
"t",
")",
"\n",
"}"
] |
// parseToken parses a string token, verifies it, and returns an AccessToken
// instance.
|
[
"parseToken",
"parses",
"a",
"string",
"token",
"verifies",
"it",
"and",
"returns",
"an",
"AccessToken",
"instance",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L200-L212
|
train
|
remind101/empire
|
server/heroku/authentication.go
|
jwtToAccessToken
|
func jwtToAccessToken(t *jwt.Token) (*AccessToken, error) {
var token AccessToken
if t.Claims["exp"] != nil {
exp := time.Unix(int64(t.Claims["exp"].(float64)), 0).UTC()
token.ExpiresAt = &exp
}
if u, ok := t.Claims["User"].(map[string]interface{}); ok {
var user empire.User
if n, ok := u["Name"].(string); ok {
user.Name = n
} else {
return &token, errors.New("missing name")
}
if gt, ok := u["GitHubToken"].(string); ok {
user.GitHubToken = gt
} else {
return &token, errors.New("missing github token")
}
token.User = &user
} else {
return &token, errors.New("missing user")
}
return &token, nil
}
|
go
|
func jwtToAccessToken(t *jwt.Token) (*AccessToken, error) {
var token AccessToken
if t.Claims["exp"] != nil {
exp := time.Unix(int64(t.Claims["exp"].(float64)), 0).UTC()
token.ExpiresAt = &exp
}
if u, ok := t.Claims["User"].(map[string]interface{}); ok {
var user empire.User
if n, ok := u["Name"].(string); ok {
user.Name = n
} else {
return &token, errors.New("missing name")
}
if gt, ok := u["GitHubToken"].(string); ok {
user.GitHubToken = gt
} else {
return &token, errors.New("missing github token")
}
token.User = &user
} else {
return &token, errors.New("missing user")
}
return &token, nil
}
|
[
"func",
"jwtToAccessToken",
"(",
"t",
"*",
"jwt",
".",
"Token",
")",
"(",
"*",
"AccessToken",
",",
"error",
")",
"{",
"var",
"token",
"AccessToken",
"\n\n",
"if",
"t",
".",
"Claims",
"[",
"\"",
"\"",
"]",
"!=",
"nil",
"{",
"exp",
":=",
"time",
".",
"Unix",
"(",
"int64",
"(",
"t",
".",
"Claims",
"[",
"\"",
"\"",
"]",
".",
"(",
"float64",
")",
")",
",",
"0",
")",
".",
"UTC",
"(",
")",
"\n",
"token",
".",
"ExpiresAt",
"=",
"&",
"exp",
"\n",
"}",
"\n\n",
"if",
"u",
",",
"ok",
":=",
"t",
".",
"Claims",
"[",
"\"",
"\"",
"]",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"var",
"user",
"empire",
".",
"User",
"\n\n",
"if",
"n",
",",
"ok",
":=",
"u",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
";",
"ok",
"{",
"user",
".",
"Name",
"=",
"n",
"\n",
"}",
"else",
"{",
"return",
"&",
"token",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"gt",
",",
"ok",
":=",
"u",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
";",
"ok",
"{",
"user",
".",
"GitHubToken",
"=",
"gt",
"\n",
"}",
"else",
"{",
"return",
"&",
"token",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"token",
".",
"User",
"=",
"&",
"user",
"\n",
"}",
"else",
"{",
"return",
"&",
"token",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"token",
",",
"nil",
"\n",
"}"
] |
// jwtToAccessTokens maps a jwt.Token to an AccessToken.
|
[
"jwtToAccessTokens",
"maps",
"a",
"jwt",
".",
"Token",
"to",
"an",
"AccessToken",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/heroku/authentication.go#L231-L260
|
train
|
remind101/empire
|
pkg/heroku/domain.go
|
DomainCreate
|
func (c *Client) DomainCreate(appIdentity string, hostname string) (*Domain, error) {
params := struct {
Hostname string `json:"hostname"`
}{
Hostname: hostname,
}
var domainRes Domain
return &domainRes, c.Post(&domainRes, "/apps/"+appIdentity+"/domains", params)
}
|
go
|
func (c *Client) DomainCreate(appIdentity string, hostname string) (*Domain, error) {
params := struct {
Hostname string `json:"hostname"`
}{
Hostname: hostname,
}
var domainRes Domain
return &domainRes, c.Post(&domainRes, "/apps/"+appIdentity+"/domains", params)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DomainCreate",
"(",
"appIdentity",
"string",
",",
"hostname",
"string",
")",
"(",
"*",
"Domain",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Hostname",
"string",
"`json:\"hostname\"`",
"\n",
"}",
"{",
"Hostname",
":",
"hostname",
",",
"}",
"\n",
"var",
"domainRes",
"Domain",
"\n",
"return",
"&",
"domainRes",
",",
"c",
".",
"Post",
"(",
"&",
"domainRes",
",",
"\"",
"\"",
"+",
"appIdentity",
"+",
"\"",
"\"",
",",
"params",
")",
"\n",
"}"
] |
// Create a new domain.
//
// appIdentity is the unique identifier of the Domain's App. hostname is the
// full hostname.
|
[
"Create",
"a",
"new",
"domain",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"s",
"App",
".",
"hostname",
"is",
"the",
"full",
"hostname",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/domain.go#L30-L38
|
train
|
remind101/empire
|
pkg/heroku/domain.go
|
DomainDelete
|
func (c *Client) DomainDelete(appIdentity string, domainIdentity string) error {
return c.Delete("/apps/" + appIdentity + "/domains/" + domainIdentity)
}
|
go
|
func (c *Client) DomainDelete(appIdentity string, domainIdentity string) error {
return c.Delete("/apps/" + appIdentity + "/domains/" + domainIdentity)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DomainDelete",
"(",
"appIdentity",
"string",
",",
"domainIdentity",
"string",
")",
"error",
"{",
"return",
"c",
".",
"Delete",
"(",
"\"",
"\"",
"+",
"appIdentity",
"+",
"\"",
"\"",
"+",
"domainIdentity",
")",
"\n",
"}"
] |
// Delete an existing domain
//
// appIdentity is the unique identifier of the Domain's App. domainIdentity is
// the unique identifier of the Domain.
|
[
"Delete",
"an",
"existing",
"domain",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"s",
"App",
".",
"domainIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/domain.go#L44-L46
|
train
|
remind101/empire
|
pkg/heroku/domain.go
|
DomainInfo
|
func (c *Client) DomainInfo(appIdentity string, domainIdentity string) (*Domain, error) {
var domain Domain
return &domain, c.Get(&domain, "/apps/"+appIdentity+"/domains/"+domainIdentity)
}
|
go
|
func (c *Client) DomainInfo(appIdentity string, domainIdentity string) (*Domain, error) {
var domain Domain
return &domain, c.Get(&domain, "/apps/"+appIdentity+"/domains/"+domainIdentity)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DomainInfo",
"(",
"appIdentity",
"string",
",",
"domainIdentity",
"string",
")",
"(",
"*",
"Domain",
",",
"error",
")",
"{",
"var",
"domain",
"Domain",
"\n",
"return",
"&",
"domain",
",",
"c",
".",
"Get",
"(",
"&",
"domain",
",",
"\"",
"\"",
"+",
"appIdentity",
"+",
"\"",
"\"",
"+",
"domainIdentity",
")",
"\n",
"}"
] |
// Info for existing domain.
//
// appIdentity is the unique identifier of the Domain's App. domainIdentity is
// the unique identifier of the Domain.
|
[
"Info",
"for",
"existing",
"domain",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"s",
"App",
".",
"domainIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/domain.go#L52-L55
|
train
|
remind101/empire
|
pkg/heroku/domain.go
|
DomainList
|
func (c *Client) DomainList(appIdentity string, lr *ListRange) ([]Domain, error) {
req, err := c.NewRequest("GET", "/apps/"+appIdentity+"/domains", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var domainsRes []Domain
return domainsRes, c.DoReq(req, &domainsRes)
}
|
go
|
func (c *Client) DomainList(appIdentity string, lr *ListRange) ([]Domain, error) {
req, err := c.NewRequest("GET", "/apps/"+appIdentity+"/domains", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var domainsRes []Domain
return domainsRes, c.DoReq(req, &domainsRes)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"DomainList",
"(",
"appIdentity",
"string",
",",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"Domain",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"appIdentity",
"+",
"\"",
"\"",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"lr",
"!=",
"nil",
"{",
"lr",
".",
"SetHeader",
"(",
"req",
")",
"\n",
"}",
"\n\n",
"var",
"domainsRes",
"[",
"]",
"Domain",
"\n",
"return",
"domainsRes",
",",
"c",
".",
"DoReq",
"(",
"req",
",",
"&",
"domainsRes",
")",
"\n",
"}"
] |
// List existing domains.
//
// appIdentity is the unique identifier of the Domain's App. lr is an optional
// ListRange that sets the Range options for the paginated list of results.
|
[
"List",
"existing",
"domains",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"Domain",
"s",
"App",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",
"of",
"results",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/domain.go#L61-L73
|
train
|
remind101/empire
|
pkg/stream/http/http.go
|
StreamingResponseWriter
|
func StreamingResponseWriter(w http.ResponseWriter) *ResponseWriter {
fw, err := newFlushWriter(w)
if err != nil {
panic(err)
}
return &ResponseWriter{
ResponseWriter: w,
w: fw,
}
}
|
go
|
func StreamingResponseWriter(w http.ResponseWriter) *ResponseWriter {
fw, err := newFlushWriter(w)
if err != nil {
panic(err)
}
return &ResponseWriter{
ResponseWriter: w,
w: fw,
}
}
|
[
"func",
"StreamingResponseWriter",
"(",
"w",
"http",
".",
"ResponseWriter",
")",
"*",
"ResponseWriter",
"{",
"fw",
",",
"err",
":=",
"newFlushWriter",
"(",
"w",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"ResponseWriter",
"{",
"ResponseWriter",
":",
"w",
",",
"w",
":",
"fw",
",",
"}",
"\n",
"}"
] |
// StreamingResponseWriter wraps the http.ResponseWriter with unbuffered
// streaming. If the provided ResponseWriter does not implement http.Flusher,
// this function will panic.
|
[
"StreamingResponseWriter",
"wraps",
"the",
"http",
".",
"ResponseWriter",
"with",
"unbuffered",
"streaming",
".",
"If",
"the",
"provided",
"ResponseWriter",
"does",
"not",
"implement",
"http",
".",
"Flusher",
"this",
"function",
"will",
"panic",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/stream/http/http.go#L23-L33
|
train
|
remind101/empire
|
pkg/stream/http/http.go
|
Write
|
func (w *ResponseWriter) Write(p []byte) (int, error) {
return w.w.Write(p)
}
|
go
|
func (w *ResponseWriter) Write(p []byte) (int, error) {
return w.w.Write(p)
}
|
[
"func",
"(",
"w",
"*",
"ResponseWriter",
")",
"Write",
"(",
"p",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"return",
"w",
".",
"w",
".",
"Write",
"(",
"p",
")",
"\n",
"}"
] |
// Write delegates to the underlying flushWriter to perform the write and flush
// it to the connection.
|
[
"Write",
"delegates",
"to",
"the",
"underlying",
"flushWriter",
"to",
"perform",
"the",
"write",
"and",
"flush",
"it",
"to",
"the",
"connection",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/stream/http/http.go#L37-L39
|
train
|
remind101/empire
|
pkg/stream/http/http.go
|
Heartbeat
|
func Heartbeat(outStream io.Writer, interval time.Duration) chan struct{} {
stop := make(chan struct{})
t := time.NewTicker(interval)
go func() {
for {
select {
case <-t.C:
fmt.Fprintf(outStream, "\x00")
continue
case <-stop:
t.Stop()
return
}
}
}()
return stop
}
|
go
|
func Heartbeat(outStream io.Writer, interval time.Duration) chan struct{} {
stop := make(chan struct{})
t := time.NewTicker(interval)
go func() {
for {
select {
case <-t.C:
fmt.Fprintf(outStream, "\x00")
continue
case <-stop:
t.Stop()
return
}
}
}()
return stop
}
|
[
"func",
"Heartbeat",
"(",
"outStream",
"io",
".",
"Writer",
",",
"interval",
"time",
".",
"Duration",
")",
"chan",
"struct",
"{",
"}",
"{",
"stop",
":=",
"make",
"(",
"chan",
"struct",
"{",
"}",
")",
"\n",
"t",
":=",
"time",
".",
"NewTicker",
"(",
"interval",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"t",
".",
"C",
":",
"fmt",
".",
"Fprintf",
"(",
"outStream",
",",
"\"",
"\\x00",
"\"",
")",
"\n",
"continue",
"\n",
"case",
"<-",
"stop",
":",
"t",
".",
"Stop",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"stop",
"\n",
"}"
] |
// Heartbeat sends the null character periodically, to keep the connection alive.
|
[
"Heartbeat",
"sends",
"the",
"null",
"character",
"periodically",
"to",
"keep",
"the",
"connection",
"alive",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/stream/http/http.go#L67-L85
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
taskDefinitionResourceType
|
func taskDefinitionResourceType(app *twelvefactor.Manifest) string {
check := []string{
"EMPIRE_X_TASK_DEFINITION_TYPE",
"ECS_TASK_DEFINITION", // For backwards compatibility.
}
for _, n := range check {
if v, ok := app.Env[n]; ok {
if v == "custom" {
return "Custom::ECSTaskDefinition"
}
}
}
// Default when not set.
return "AWS::ECS::TaskDefinition"
}
|
go
|
func taskDefinitionResourceType(app *twelvefactor.Manifest) string {
check := []string{
"EMPIRE_X_TASK_DEFINITION_TYPE",
"ECS_TASK_DEFINITION", // For backwards compatibility.
}
for _, n := range check {
if v, ok := app.Env[n]; ok {
if v == "custom" {
return "Custom::ECSTaskDefinition"
}
}
}
// Default when not set.
return "AWS::ECS::TaskDefinition"
}
|
[
"func",
"taskDefinitionResourceType",
"(",
"app",
"*",
"twelvefactor",
".",
"Manifest",
")",
"string",
"{",
"check",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"// For backwards compatibility.",
"}",
"\n\n",
"for",
"_",
",",
"n",
":=",
"range",
"check",
"{",
"if",
"v",
",",
"ok",
":=",
"app",
".",
"Env",
"[",
"n",
"]",
";",
"ok",
"{",
"if",
"v",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Default when not set.",
"return",
"\"",
"\"",
"\n",
"}"
] |
// Returns the name of the CloudFormation resource that should be used to create
// custom task definitions.
|
[
"Returns",
"the",
"name",
"of",
"the",
"CloudFormation",
"resource",
"that",
"should",
"be",
"used",
"to",
"create",
"custom",
"task",
"definitions",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L59-L75
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
Validate
|
func (t *EmpireTemplate) Validate() error {
r := func(n string) error {
return errors.New(fmt.Sprintf("%s is required", n))
}
if t.VpcId == "" {
return r("VpcId")
}
if t.Cluster == "" {
return r("Cluster")
}
if t.ServiceRole == "" {
return r("ServiceRole")
}
if t.HostedZone == nil {
return r("HostedZone")
}
if t.InternalSecurityGroupID == "" {
return r("InternalSecurityGroupID")
}
if t.ExternalSecurityGroupID == "" {
return r("ExternalSecurityGroupID")
}
if len(t.InternalSubnetIDs) == 0 {
return r("InternalSubnetIDs")
}
if len(t.ExternalSubnetIDs) == 0 {
return r("ExternalSubnetIDs")
}
if t.CustomResourcesTopic == "" {
return r("CustomResourcesTopic")
}
return nil
}
|
go
|
func (t *EmpireTemplate) Validate() error {
r := func(n string) error {
return errors.New(fmt.Sprintf("%s is required", n))
}
if t.VpcId == "" {
return r("VpcId")
}
if t.Cluster == "" {
return r("Cluster")
}
if t.ServiceRole == "" {
return r("ServiceRole")
}
if t.HostedZone == nil {
return r("HostedZone")
}
if t.InternalSecurityGroupID == "" {
return r("InternalSecurityGroupID")
}
if t.ExternalSecurityGroupID == "" {
return r("ExternalSecurityGroupID")
}
if len(t.InternalSubnetIDs) == 0 {
return r("InternalSubnetIDs")
}
if len(t.ExternalSubnetIDs) == 0 {
return r("ExternalSubnetIDs")
}
if t.CustomResourcesTopic == "" {
return r("CustomResourcesTopic")
}
return nil
}
|
[
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"Validate",
"(",
")",
"error",
"{",
"r",
":=",
"func",
"(",
"n",
"string",
")",
"error",
"{",
"return",
"errors",
".",
"New",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"n",
")",
")",
"\n",
"}",
"\n\n",
"if",
"t",
".",
"VpcId",
"==",
"\"",
"\"",
"{",
"return",
"r",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"Cluster",
"==",
"\"",
"\"",
"{",
"return",
"r",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"ServiceRole",
"==",
"\"",
"\"",
"{",
"return",
"r",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"HostedZone",
"==",
"nil",
"{",
"return",
"r",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"InternalSecurityGroupID",
"==",
"\"",
"\"",
"{",
"return",
"r",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"ExternalSecurityGroupID",
"==",
"\"",
"\"",
"{",
"return",
"r",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"t",
".",
"InternalSubnetIDs",
")",
"==",
"0",
"{",
"return",
"r",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"t",
".",
"ExternalSubnetIDs",
")",
"==",
"0",
"{",
"return",
"r",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"CustomResourcesTopic",
"==",
"\"",
"\"",
"{",
"return",
"r",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Validate checks that all of the expected values are provided.
|
[
"Validate",
"checks",
"that",
"all",
"of",
"the",
"expected",
"values",
"are",
"provided",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L150-L184
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
Execute
|
func (t *EmpireTemplate) Execute(w io.Writer, data interface{}) error {
v, err := t.Build(data.(*TemplateData))
if err != nil {
return err
}
if t.NoCompress {
raw, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
_, err = io.Copy(w, bytes.NewReader(raw))
return err
}
return json.NewEncoder(w).Encode(v)
}
|
go
|
func (t *EmpireTemplate) Execute(w io.Writer, data interface{}) error {
v, err := t.Build(data.(*TemplateData))
if err != nil {
return err
}
if t.NoCompress {
raw, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
_, err = io.Copy(w, bytes.NewReader(raw))
return err
}
return json.NewEncoder(w).Encode(v)
}
|
[
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"Execute",
"(",
"w",
"io",
".",
"Writer",
",",
"data",
"interface",
"{",
"}",
")",
"error",
"{",
"v",
",",
"err",
":=",
"t",
".",
"Build",
"(",
"data",
".",
"(",
"*",
"TemplateData",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"t",
".",
"NoCompress",
"{",
"raw",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"v",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"w",
",",
"bytes",
".",
"NewReader",
"(",
"raw",
")",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"NewEncoder",
"(",
"w",
")",
".",
"Encode",
"(",
"v",
")",
"\n",
"}"
] |
// Execute builds the template, and writes it to w.
|
[
"Execute",
"builds",
"the",
"template",
"and",
"writes",
"it",
"to",
"w",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L187-L204
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
Build
|
func (t *EmpireTemplate) Build(data *TemplateData) (*troposphere.Template, error) {
app := data.Manifest
tmpl := troposphere.NewTemplate()
tmpl.Parameters["DNS"] = troposphere.Parameter{
Type: "String",
Description: "When set to `true`, CNAME's will be altered",
Default: "true",
}
tmpl.Parameters[restartParameter] = troposphere.Parameter{
Type: "String",
Description: "Key used to trigger a restart of an app",
Default: "default",
}
tmpl.Conditions["DNSCondition"] = Equals(Ref("DNS"), "true")
for k, v := range t.ExtraOutputs {
tmpl.Outputs[k] = v
}
tmpl.Outputs["Release"] = troposphere.Output{Value: app.Release}
serviceMappings := []interface{}{}
deploymentMappings := []interface{}{}
scheduledProcesses := map[string]string{}
if taskDefinitionResourceType(app) == "Custom::ECSTaskDefinition" {
tmpl.Resources[appEnvironment] = troposphere.Resource{
Type: "Custom::ECSEnvironment",
Properties: map[string]interface{}{
"ServiceToken": t.CustomResourcesTopic,
"Environment": sortedEnvironment(app.Env),
},
}
}
for _, p := range app.Processes {
if p.Env == nil {
p.Env = make(map[string]string)
}
tmpl.Parameters[scaleParameter(p.Type)] = troposphere.Parameter{
Type: "String",
}
switch {
case p.Schedule != nil:
taskDefinition := t.addScheduledTask(tmpl, app, p)
scheduledProcesses[p.Type] = taskDefinition.Name
default:
service, err := t.addService(tmpl, app, p, data.StackTags)
if err != nil {
return tmpl, err
}
serviceMappings = append(serviceMappings, Join("=", p.Type, Ref(service)))
deploymentMappings = append(deploymentMappings, Join("=", p.Type, GetAtt(service, "DeploymentId")))
}
}
if len(scheduledProcesses) > 0 {
// LambdaFunction that will be used to trigger a RunTask.
tmpl.Resources[runTaskFunction] = runTaskResource(t.serviceRoleArn())
}
tmpl.Outputs[servicesOutput] = troposphere.Output{Value: Join(",", serviceMappings...)}
tmpl.Outputs[deploymentsOutput] = troposphere.Output{Value: Join(",", deploymentMappings...)}
return tmpl, nil
}
|
go
|
func (t *EmpireTemplate) Build(data *TemplateData) (*troposphere.Template, error) {
app := data.Manifest
tmpl := troposphere.NewTemplate()
tmpl.Parameters["DNS"] = troposphere.Parameter{
Type: "String",
Description: "When set to `true`, CNAME's will be altered",
Default: "true",
}
tmpl.Parameters[restartParameter] = troposphere.Parameter{
Type: "String",
Description: "Key used to trigger a restart of an app",
Default: "default",
}
tmpl.Conditions["DNSCondition"] = Equals(Ref("DNS"), "true")
for k, v := range t.ExtraOutputs {
tmpl.Outputs[k] = v
}
tmpl.Outputs["Release"] = troposphere.Output{Value: app.Release}
serviceMappings := []interface{}{}
deploymentMappings := []interface{}{}
scheduledProcesses := map[string]string{}
if taskDefinitionResourceType(app) == "Custom::ECSTaskDefinition" {
tmpl.Resources[appEnvironment] = troposphere.Resource{
Type: "Custom::ECSEnvironment",
Properties: map[string]interface{}{
"ServiceToken": t.CustomResourcesTopic,
"Environment": sortedEnvironment(app.Env),
},
}
}
for _, p := range app.Processes {
if p.Env == nil {
p.Env = make(map[string]string)
}
tmpl.Parameters[scaleParameter(p.Type)] = troposphere.Parameter{
Type: "String",
}
switch {
case p.Schedule != nil:
taskDefinition := t.addScheduledTask(tmpl, app, p)
scheduledProcesses[p.Type] = taskDefinition.Name
default:
service, err := t.addService(tmpl, app, p, data.StackTags)
if err != nil {
return tmpl, err
}
serviceMappings = append(serviceMappings, Join("=", p.Type, Ref(service)))
deploymentMappings = append(deploymentMappings, Join("=", p.Type, GetAtt(service, "DeploymentId")))
}
}
if len(scheduledProcesses) > 0 {
// LambdaFunction that will be used to trigger a RunTask.
tmpl.Resources[runTaskFunction] = runTaskResource(t.serviceRoleArn())
}
tmpl.Outputs[servicesOutput] = troposphere.Output{Value: Join(",", serviceMappings...)}
tmpl.Outputs[deploymentsOutput] = troposphere.Output{Value: Join(",", deploymentMappings...)}
return tmpl, nil
}
|
[
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"Build",
"(",
"data",
"*",
"TemplateData",
")",
"(",
"*",
"troposphere",
".",
"Template",
",",
"error",
")",
"{",
"app",
":=",
"data",
".",
"Manifest",
"\n\n",
"tmpl",
":=",
"troposphere",
".",
"NewTemplate",
"(",
")",
"\n\n",
"tmpl",
".",
"Parameters",
"[",
"\"",
"\"",
"]",
"=",
"troposphere",
".",
"Parameter",
"{",
"Type",
":",
"\"",
"\"",
",",
"Description",
":",
"\"",
"\"",
",",
"Default",
":",
"\"",
"\"",
",",
"}",
"\n",
"tmpl",
".",
"Parameters",
"[",
"restartParameter",
"]",
"=",
"troposphere",
".",
"Parameter",
"{",
"Type",
":",
"\"",
"\"",
",",
"Description",
":",
"\"",
"\"",
",",
"Default",
":",
"\"",
"\"",
",",
"}",
"\n",
"tmpl",
".",
"Conditions",
"[",
"\"",
"\"",
"]",
"=",
"Equals",
"(",
"Ref",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n\n",
"for",
"k",
",",
"v",
":=",
"range",
"t",
".",
"ExtraOutputs",
"{",
"tmpl",
".",
"Outputs",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n\n",
"tmpl",
".",
"Outputs",
"[",
"\"",
"\"",
"]",
"=",
"troposphere",
".",
"Output",
"{",
"Value",
":",
"app",
".",
"Release",
"}",
"\n\n",
"serviceMappings",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"deploymentMappings",
":=",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
"\n",
"scheduledProcesses",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n\n",
"if",
"taskDefinitionResourceType",
"(",
"app",
")",
"==",
"\"",
"\"",
"{",
"tmpl",
".",
"Resources",
"[",
"appEnvironment",
"]",
"=",
"troposphere",
".",
"Resource",
"{",
"Type",
":",
"\"",
"\"",
",",
"Properties",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"t",
".",
"CustomResourcesTopic",
",",
"\"",
"\"",
":",
"sortedEnvironment",
"(",
"app",
".",
"Env",
")",
",",
"}",
",",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"p",
":=",
"range",
"app",
".",
"Processes",
"{",
"if",
"p",
".",
"Env",
"==",
"nil",
"{",
"p",
".",
"Env",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"}",
"\n\n",
"tmpl",
".",
"Parameters",
"[",
"scaleParameter",
"(",
"p",
".",
"Type",
")",
"]",
"=",
"troposphere",
".",
"Parameter",
"{",
"Type",
":",
"\"",
"\"",
",",
"}",
"\n\n",
"switch",
"{",
"case",
"p",
".",
"Schedule",
"!=",
"nil",
":",
"taskDefinition",
":=",
"t",
".",
"addScheduledTask",
"(",
"tmpl",
",",
"app",
",",
"p",
")",
"\n",
"scheduledProcesses",
"[",
"p",
".",
"Type",
"]",
"=",
"taskDefinition",
".",
"Name",
"\n",
"default",
":",
"service",
",",
"err",
":=",
"t",
".",
"addService",
"(",
"tmpl",
",",
"app",
",",
"p",
",",
"data",
".",
"StackTags",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"tmpl",
",",
"err",
"\n",
"}",
"\n",
"serviceMappings",
"=",
"append",
"(",
"serviceMappings",
",",
"Join",
"(",
"\"",
"\"",
",",
"p",
".",
"Type",
",",
"Ref",
"(",
"service",
")",
")",
")",
"\n",
"deploymentMappings",
"=",
"append",
"(",
"deploymentMappings",
",",
"Join",
"(",
"\"",
"\"",
",",
"p",
".",
"Type",
",",
"GetAtt",
"(",
"service",
",",
"\"",
"\"",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"scheduledProcesses",
")",
">",
"0",
"{",
"// LambdaFunction that will be used to trigger a RunTask.",
"tmpl",
".",
"Resources",
"[",
"runTaskFunction",
"]",
"=",
"runTaskResource",
"(",
"t",
".",
"serviceRoleArn",
"(",
")",
")",
"\n",
"}",
"\n\n",
"tmpl",
".",
"Outputs",
"[",
"servicesOutput",
"]",
"=",
"troposphere",
".",
"Output",
"{",
"Value",
":",
"Join",
"(",
"\"",
"\"",
",",
"serviceMappings",
"...",
")",
"}",
"\n",
"tmpl",
".",
"Outputs",
"[",
"deploymentsOutput",
"]",
"=",
"troposphere",
".",
"Output",
"{",
"Value",
":",
"Join",
"(",
"\"",
"\"",
",",
"deploymentMappings",
"...",
")",
"}",
"\n\n",
"return",
"tmpl",
",",
"nil",
"\n",
"}"
] |
// Build builds a Go representation of a CloudFormation template for the app.
|
[
"Build",
"builds",
"a",
"Go",
"representation",
"of",
"a",
"CloudFormation",
"template",
"for",
"the",
"app",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L207-L276
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
serviceRoleArn
|
func (t *EmpireTemplate) serviceRoleArn() interface{} {
if _, err := arn.Parse(t.ServiceRole); err == nil {
return t.ServiceRole
}
return Join("", "arn:aws:iam::", Ref("AWS::AccountId"), ":role/", t.ServiceRole)
}
|
go
|
func (t *EmpireTemplate) serviceRoleArn() interface{} {
if _, err := arn.Parse(t.ServiceRole); err == nil {
return t.ServiceRole
}
return Join("", "arn:aws:iam::", Ref("AWS::AccountId"), ":role/", t.ServiceRole)
}
|
[
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"serviceRoleArn",
"(",
")",
"interface",
"{",
"}",
"{",
"if",
"_",
",",
"err",
":=",
"arn",
".",
"Parse",
"(",
"t",
".",
"ServiceRole",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"t",
".",
"ServiceRole",
"\n",
"}",
"\n",
"return",
"Join",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"Ref",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
",",
"t",
".",
"ServiceRole",
")",
"\n",
"}"
] |
// If the ServiceRole option is not an ARN, it will return a CloudFormation
// expression that expands the ServiceRole to an ARN.
|
[
"If",
"the",
"ServiceRole",
"option",
"is",
"not",
"an",
"ARN",
"it",
"will",
"return",
"a",
"CloudFormation",
"expression",
"that",
"expands",
"the",
"ServiceRole",
"to",
"an",
"ARN",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L738-L743
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
ContainerDefinition
|
func (t *EmpireTemplate) ContainerDefinition(app *twelvefactor.Manifest, p *twelvefactor.Process) *ecs.ContainerDefinition {
command := []*string{}
for _, s := range p.Command {
ss := s
command = append(command, &ss)
}
labels := make(map[string]*string)
for k, v := range twelvefactor.Labels(app, p) {
labels[k] = aws.String(v)
}
ulimits := []*ecs.Ulimit{}
if p.Nproc != 0 {
ulimits = []*ecs.Ulimit{
&ecs.Ulimit{
Name: aws.String("nproc"),
SoftLimit: aws.Int64(int64(p.Nproc)),
HardLimit: aws.Int64(int64(p.Nproc)),
},
}
}
return &ecs.ContainerDefinition{
Name: aws.String(p.Type),
Cpu: aws.Int64(int64(p.CPUShares)),
Command: command,
Image: aws.String(p.Image.String()),
Essential: aws.Bool(true),
Memory: aws.Int64(int64(p.Memory / bytesize.MB)),
Environment: sortedEnvironment(twelvefactor.Env(app, p)),
LogConfiguration: t.LogConfiguration,
DockerLabels: labels,
Ulimits: ulimits,
}
}
|
go
|
func (t *EmpireTemplate) ContainerDefinition(app *twelvefactor.Manifest, p *twelvefactor.Process) *ecs.ContainerDefinition {
command := []*string{}
for _, s := range p.Command {
ss := s
command = append(command, &ss)
}
labels := make(map[string]*string)
for k, v := range twelvefactor.Labels(app, p) {
labels[k] = aws.String(v)
}
ulimits := []*ecs.Ulimit{}
if p.Nproc != 0 {
ulimits = []*ecs.Ulimit{
&ecs.Ulimit{
Name: aws.String("nproc"),
SoftLimit: aws.Int64(int64(p.Nproc)),
HardLimit: aws.Int64(int64(p.Nproc)),
},
}
}
return &ecs.ContainerDefinition{
Name: aws.String(p.Type),
Cpu: aws.Int64(int64(p.CPUShares)),
Command: command,
Image: aws.String(p.Image.String()),
Essential: aws.Bool(true),
Memory: aws.Int64(int64(p.Memory / bytesize.MB)),
Environment: sortedEnvironment(twelvefactor.Env(app, p)),
LogConfiguration: t.LogConfiguration,
DockerLabels: labels,
Ulimits: ulimits,
}
}
|
[
"func",
"(",
"t",
"*",
"EmpireTemplate",
")",
"ContainerDefinition",
"(",
"app",
"*",
"twelvefactor",
".",
"Manifest",
",",
"p",
"*",
"twelvefactor",
".",
"Process",
")",
"*",
"ecs",
".",
"ContainerDefinition",
"{",
"command",
":=",
"[",
"]",
"*",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"p",
".",
"Command",
"{",
"ss",
":=",
"s",
"\n",
"command",
"=",
"append",
"(",
"command",
",",
"&",
"ss",
")",
"\n",
"}",
"\n\n",
"labels",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"string",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"twelvefactor",
".",
"Labels",
"(",
"app",
",",
"p",
")",
"{",
"labels",
"[",
"k",
"]",
"=",
"aws",
".",
"String",
"(",
"v",
")",
"\n",
"}",
"\n\n",
"ulimits",
":=",
"[",
"]",
"*",
"ecs",
".",
"Ulimit",
"{",
"}",
"\n",
"if",
"p",
".",
"Nproc",
"!=",
"0",
"{",
"ulimits",
"=",
"[",
"]",
"*",
"ecs",
".",
"Ulimit",
"{",
"&",
"ecs",
".",
"Ulimit",
"{",
"Name",
":",
"aws",
".",
"String",
"(",
"\"",
"\"",
")",
",",
"SoftLimit",
":",
"aws",
".",
"Int64",
"(",
"int64",
"(",
"p",
".",
"Nproc",
")",
")",
",",
"HardLimit",
":",
"aws",
".",
"Int64",
"(",
"int64",
"(",
"p",
".",
"Nproc",
")",
")",
",",
"}",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"ecs",
".",
"ContainerDefinition",
"{",
"Name",
":",
"aws",
".",
"String",
"(",
"p",
".",
"Type",
")",
",",
"Cpu",
":",
"aws",
".",
"Int64",
"(",
"int64",
"(",
"p",
".",
"CPUShares",
")",
")",
",",
"Command",
":",
"command",
",",
"Image",
":",
"aws",
".",
"String",
"(",
"p",
".",
"Image",
".",
"String",
"(",
")",
")",
",",
"Essential",
":",
"aws",
".",
"Bool",
"(",
"true",
")",
",",
"Memory",
":",
"aws",
".",
"Int64",
"(",
"int64",
"(",
"p",
".",
"Memory",
"/",
"bytesize",
".",
"MB",
")",
")",
",",
"Environment",
":",
"sortedEnvironment",
"(",
"twelvefactor",
".",
"Env",
"(",
"app",
",",
"p",
")",
")",
",",
"LogConfiguration",
":",
"t",
".",
"LogConfiguration",
",",
"DockerLabels",
":",
"labels",
",",
"Ulimits",
":",
"ulimits",
",",
"}",
"\n",
"}"
] |
// ContainerDefinition generates an ECS ContainerDefinition for a process.
|
[
"ContainerDefinition",
"generates",
"an",
"ECS",
"ContainerDefinition",
"for",
"a",
"process",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L754-L789
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
HostedZone
|
func HostedZone(config client.ConfigProvider, hostedZoneID string) (*route53.HostedZone, error) {
r := route53.New(config)
zid := fixHostedZoneIDPrefix(hostedZoneID)
out, err := r.GetHostedZone(&route53.GetHostedZoneInput{Id: zid})
if err != nil {
return nil, err
}
return out.HostedZone, nil
}
|
go
|
func HostedZone(config client.ConfigProvider, hostedZoneID string) (*route53.HostedZone, error) {
r := route53.New(config)
zid := fixHostedZoneIDPrefix(hostedZoneID)
out, err := r.GetHostedZone(&route53.GetHostedZoneInput{Id: zid})
if err != nil {
return nil, err
}
return out.HostedZone, nil
}
|
[
"func",
"HostedZone",
"(",
"config",
"client",
".",
"ConfigProvider",
",",
"hostedZoneID",
"string",
")",
"(",
"*",
"route53",
".",
"HostedZone",
",",
"error",
")",
"{",
"r",
":=",
"route53",
".",
"New",
"(",
"config",
")",
"\n",
"zid",
":=",
"fixHostedZoneIDPrefix",
"(",
"hostedZoneID",
")",
"\n",
"out",
",",
"err",
":=",
"r",
".",
"GetHostedZone",
"(",
"&",
"route53",
".",
"GetHostedZoneInput",
"{",
"Id",
":",
"zid",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"out",
".",
"HostedZone",
",",
"nil",
"\n",
"}"
] |
// HostedZone returns the HostedZone for the ZoneID.
|
[
"HostedZone",
"returns",
"the",
"HostedZone",
"for",
"the",
"ZoneID",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L792-L801
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
cloudformationContainerDefinition
|
func cloudformationContainerDefinition(cd *ecs.ContainerDefinition) *ContainerDefinitionProperties {
labels := make(map[string]interface{})
for k, v := range cd.DockerLabels {
labels[k] = *v
}
c := &ContainerDefinitionProperties{
Name: *cd.Name,
Command: cd.Command,
Cpu: *cd.Cpu,
Image: *cd.Image,
Essential: *cd.Essential,
Memory: *cd.Memory,
Environment: cd.Environment,
DockerLabels: labels,
Ulimits: cd.Ulimits,
}
if cd.LogConfiguration != nil {
c.LogConfiguration = cd.LogConfiguration
}
return c
}
|
go
|
func cloudformationContainerDefinition(cd *ecs.ContainerDefinition) *ContainerDefinitionProperties {
labels := make(map[string]interface{})
for k, v := range cd.DockerLabels {
labels[k] = *v
}
c := &ContainerDefinitionProperties{
Name: *cd.Name,
Command: cd.Command,
Cpu: *cd.Cpu,
Image: *cd.Image,
Essential: *cd.Essential,
Memory: *cd.Memory,
Environment: cd.Environment,
DockerLabels: labels,
Ulimits: cd.Ulimits,
}
if cd.LogConfiguration != nil {
c.LogConfiguration = cd.LogConfiguration
}
return c
}
|
[
"func",
"cloudformationContainerDefinition",
"(",
"cd",
"*",
"ecs",
".",
"ContainerDefinition",
")",
"*",
"ContainerDefinitionProperties",
"{",
"labels",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"cd",
".",
"DockerLabels",
"{",
"labels",
"[",
"k",
"]",
"=",
"*",
"v",
"\n",
"}",
"\n\n",
"c",
":=",
"&",
"ContainerDefinitionProperties",
"{",
"Name",
":",
"*",
"cd",
".",
"Name",
",",
"Command",
":",
"cd",
".",
"Command",
",",
"Cpu",
":",
"*",
"cd",
".",
"Cpu",
",",
"Image",
":",
"*",
"cd",
".",
"Image",
",",
"Essential",
":",
"*",
"cd",
".",
"Essential",
",",
"Memory",
":",
"*",
"cd",
".",
"Memory",
",",
"Environment",
":",
"cd",
".",
"Environment",
",",
"DockerLabels",
":",
"labels",
",",
"Ulimits",
":",
"cd",
".",
"Ulimits",
",",
"}",
"\n",
"if",
"cd",
".",
"LogConfiguration",
"!=",
"nil",
"{",
"c",
".",
"LogConfiguration",
"=",
"cd",
".",
"LogConfiguration",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] |
// cloudformationContainerDefinition returns the CloudFormation representation
// of a ecs.ContainerDefinition.
|
[
"cloudformationContainerDefinition",
"returns",
"the",
"CloudFormation",
"representation",
"of",
"a",
"ecs",
".",
"ContainerDefinition",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L830-L851
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
runTaskResource
|
func runTaskResource(role interface{}) troposphere.Resource {
return troposphere.Resource{
Type: "AWS::Lambda::Function",
Properties: map[string]interface{}{
"Description": fmt.Sprintf("Lambda function to run an ECS task"),
"Handler": "index.handler",
"Role": role,
"Runtime": "python2.7",
"Code": map[string]interface{}{
"ZipFile": runTaskCode,
},
},
}
}
|
go
|
func runTaskResource(role interface{}) troposphere.Resource {
return troposphere.Resource{
Type: "AWS::Lambda::Function",
Properties: map[string]interface{}{
"Description": fmt.Sprintf("Lambda function to run an ECS task"),
"Handler": "index.handler",
"Role": role,
"Runtime": "python2.7",
"Code": map[string]interface{}{
"ZipFile": runTaskCode,
},
},
}
}
|
[
"func",
"runTaskResource",
"(",
"role",
"interface",
"{",
"}",
")",
"troposphere",
".",
"Resource",
"{",
"return",
"troposphere",
".",
"Resource",
"{",
"Type",
":",
"\"",
"\"",
",",
"Properties",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"role",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"runTaskCode",
",",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] |
// runTaskResource returns a troposphere resource that will create a lambda
// function that can be used to run an ECS task.
|
[
"runTaskResource",
"returns",
"a",
"troposphere",
"resource",
"that",
"will",
"create",
"a",
"lambda",
"function",
"that",
"can",
"be",
"used",
"to",
"run",
"an",
"ECS",
"task",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L885-L898
|
train
|
remind101/empire
|
scheduler/cloudformation/template.go
|
tagsFromLabels
|
func tagsFromLabels(labels map[string]string) []*cloudformation.Tag {
tags := cloudformationTags{}
for k, v := range labels {
tags = append(tags, &cloudformation.Tag{Key: aws.String(k), Value: aws.String(v)})
}
sort.Sort(tags)
return tags
}
|
go
|
func tagsFromLabels(labels map[string]string) []*cloudformation.Tag {
tags := cloudformationTags{}
for k, v := range labels {
tags = append(tags, &cloudformation.Tag{Key: aws.String(k), Value: aws.String(v)})
}
sort.Sort(tags)
return tags
}
|
[
"func",
"tagsFromLabels",
"(",
"labels",
"map",
"[",
"string",
"]",
"string",
")",
"[",
"]",
"*",
"cloudformation",
".",
"Tag",
"{",
"tags",
":=",
"cloudformationTags",
"{",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"labels",
"{",
"tags",
"=",
"append",
"(",
"tags",
",",
"&",
"cloudformation",
".",
"Tag",
"{",
"Key",
":",
"aws",
".",
"String",
"(",
"k",
")",
",",
"Value",
":",
"aws",
".",
"String",
"(",
"v",
")",
"}",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"tags",
")",
"\n",
"return",
"tags",
"\n",
"}"
] |
// tagsFromLabels generates a list of CloudFormation tags from the labels, it
// also sorts the tags by key.
|
[
"tagsFromLabels",
"generates",
"a",
"list",
"of",
"CloudFormation",
"tags",
"from",
"the",
"labels",
"it",
"also",
"sorts",
"the",
"tags",
"by",
"key",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/cloudformation/template.go#L922-L929
|
train
|
remind101/empire
|
events.go
|
AsyncEvents
|
func AsyncEvents(e EventStream) EventStream {
s := &asyncEventStream{
e: e,
events: make(chan Event, 100),
}
go s.start()
return s
}
|
go
|
func AsyncEvents(e EventStream) EventStream {
s := &asyncEventStream{
e: e,
events: make(chan Event, 100),
}
go s.start()
return s
}
|
[
"func",
"AsyncEvents",
"(",
"e",
"EventStream",
")",
"EventStream",
"{",
"s",
":=",
"&",
"asyncEventStream",
"{",
"e",
":",
"e",
",",
"events",
":",
"make",
"(",
"chan",
"Event",
",",
"100",
")",
",",
"}",
"\n",
"go",
"s",
".",
"start",
"(",
")",
"\n",
"return",
"s",
"\n",
"}"
] |
// AsyncEvents returns a new AsyncEventStream that will buffer upto 100 events
// before applying backpressure.
|
[
"AsyncEvents",
"returns",
"a",
"new",
"AsyncEventStream",
"that",
"will",
"buffer",
"upto",
"100",
"events",
"before",
"applying",
"backpressure",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/events.go#L355-L362
|
train
|
remind101/empire
|
server/auth/github/client.go
|
NewClient
|
func NewClient(config *oauth2.Config) *Client {
return &Client{
Config: config,
backoff: backoff,
}
}
|
go
|
func NewClient(config *oauth2.Config) *Client {
return &Client{
Config: config,
backoff: backoff,
}
}
|
[
"func",
"NewClient",
"(",
"config",
"*",
"oauth2",
".",
"Config",
")",
"*",
"Client",
"{",
"return",
"&",
"Client",
"{",
"Config",
":",
"config",
",",
"backoff",
":",
"backoff",
",",
"}",
"\n",
"}"
] |
// NewClient returns a new Client instance that uses the given oauth2 config.
|
[
"NewClient",
"returns",
"a",
"new",
"Client",
"instance",
"that",
"uses",
"the",
"given",
"oauth2",
"config",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/auth/github/client.go#L80-L85
|
train
|
remind101/empire
|
server/auth/github/client.go
|
IsOrganizationMember
|
func (c *Client) IsOrganizationMember(organization, token string) (bool, error) {
req, err := c.NewRequest("HEAD", fmt.Sprintf("/user/memberships/orgs/%s", organization), nil)
if err != nil {
return false, err
}
tokenAuth(req, token)
resp, err := c.Do(req, nil)
if err != nil {
if resp != nil && resp.StatusCode == 404 {
return false, nil
}
return false, err
}
return true, nil
}
|
go
|
func (c *Client) IsOrganizationMember(organization, token string) (bool, error) {
req, err := c.NewRequest("HEAD", fmt.Sprintf("/user/memberships/orgs/%s", organization), nil)
if err != nil {
return false, err
}
tokenAuth(req, token)
resp, err := c.Do(req, nil)
if err != nil {
if resp != nil && resp.StatusCode == 404 {
return false, nil
}
return false, err
}
return true, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"IsOrganizationMember",
"(",
"organization",
",",
"token",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"organization",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"tokenAuth",
"(",
"req",
",",
"token",
")",
"\n\n",
"resp",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"req",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"resp",
"!=",
"nil",
"&&",
"resp",
".",
"StatusCode",
"==",
"404",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] |
// IsOrganizationMember returns true of the authenticated user is a member of the
// organization.
|
[
"IsOrganizationMember",
"returns",
"true",
"of",
"the",
"authenticated",
"user",
"is",
"a",
"member",
"of",
"the",
"organization",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/auth/github/client.go#L172-L189
|
train
|
remind101/empire
|
server/auth/github/client.go
|
IsTeamMember
|
func (c *Client) IsTeamMember(teamID, token string) (bool, error) {
u, err := c.GetUser(token)
if err != nil {
return false, err
}
req, err := c.NewRequest("GET", fmt.Sprintf("/teams/%s/memberships/%s", teamID, u.Login), nil)
if err != nil {
return false, err
}
tokenAuth(req, token)
var t TeamMembership
resp, err := c.Do(req, &t)
if err != nil {
if resp != nil && resp.StatusCode == 404 {
return false, nil
}
return false, err
}
return t.State == "active", nil
}
|
go
|
func (c *Client) IsTeamMember(teamID, token string) (bool, error) {
u, err := c.GetUser(token)
if err != nil {
return false, err
}
req, err := c.NewRequest("GET", fmt.Sprintf("/teams/%s/memberships/%s", teamID, u.Login), nil)
if err != nil {
return false, err
}
tokenAuth(req, token)
var t TeamMembership
resp, err := c.Do(req, &t)
if err != nil {
if resp != nil && resp.StatusCode == 404 {
return false, nil
}
return false, err
}
return t.State == "active", nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"IsTeamMember",
"(",
"teamID",
",",
"token",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"u",
",",
"err",
":=",
"c",
".",
"GetUser",
"(",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"teamID",
",",
"u",
".",
"Login",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"tokenAuth",
"(",
"req",
",",
"token",
")",
"\n\n",
"var",
"t",
"TeamMembership",
"\n\n",
"resp",
",",
"err",
":=",
"c",
".",
"Do",
"(",
"req",
",",
"&",
"t",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"resp",
"!=",
"nil",
"&&",
"resp",
".",
"StatusCode",
"==",
"404",
"{",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"t",
".",
"State",
"==",
"\"",
"\"",
",",
"nil",
"\n",
"}"
] |
// IsTeamMember returns true if the given user is a member of the team.
|
[
"IsTeamMember",
"returns",
"true",
"if",
"the",
"given",
"user",
"is",
"a",
"member",
"of",
"the",
"team",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/server/auth/github/client.go#L192-L216
|
train
|
remind101/empire
|
pkg/heroku/organization_app.go
|
OrganizationAppCreate
|
func (c *Client) OrganizationAppCreate(options *OrganizationAppCreateOpts, message string) (*OrganizationApp, error) {
rh := RequestHeaders{CommitMessage: message}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.PostWithHeaders(&organizationAppRes, "/organizations/apps", options, rh.Headers())
}
|
go
|
func (c *Client) OrganizationAppCreate(options *OrganizationAppCreateOpts, message string) (*OrganizationApp, error) {
rh := RequestHeaders{CommitMessage: message}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.PostWithHeaders(&organizationAppRes, "/organizations/apps", options, rh.Headers())
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppCreate",
"(",
"options",
"*",
"OrganizationAppCreateOpts",
",",
"message",
"string",
")",
"(",
"*",
"OrganizationApp",
",",
"error",
")",
"{",
"rh",
":=",
"RequestHeaders",
"{",
"CommitMessage",
":",
"message",
"}",
"\n",
"var",
"organizationAppRes",
"OrganizationApp",
"\n",
"return",
"&",
"organizationAppRes",
",",
"c",
".",
"PostWithHeaders",
"(",
"&",
"organizationAppRes",
",",
"\"",
"\"",
",",
"options",
",",
"rh",
".",
"Headers",
"(",
")",
")",
"\n",
"}"
] |
// Create a new app in the specified organization, in the default organization
// if unspecified, or in personal account, if default organization is not set.
//
// options is the struct of optional parameters for this action.
|
[
"Create",
"a",
"new",
"app",
"in",
"the",
"specified",
"organization",
"in",
"the",
"default",
"organization",
"if",
"unspecified",
"or",
"in",
"personal",
"account",
"if",
"default",
"organization",
"is",
"not",
"set",
".",
"options",
"is",
"the",
"struct",
"of",
"optional",
"parameters",
"for",
"this",
"action",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L84-L88
|
train
|
remind101/empire
|
pkg/heroku/organization_app.go
|
OrganizationAppList
|
func (c *Client) OrganizationAppList(lr *ListRange) ([]OrganizationApp, error) {
req, err := c.NewRequest("GET", "/organizations/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationAppsRes []OrganizationApp
return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
}
|
go
|
func (c *Client) OrganizationAppList(lr *ListRange) ([]OrganizationApp, error) {
req, err := c.NewRequest("GET", "/organizations/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationAppsRes []OrganizationApp
return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppList",
"(",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"OrganizationApp",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"lr",
"!=",
"nil",
"{",
"lr",
".",
"SetHeader",
"(",
"req",
")",
"\n",
"}",
"\n\n",
"var",
"organizationAppsRes",
"[",
"]",
"OrganizationApp",
"\n",
"return",
"organizationAppsRes",
",",
"c",
".",
"DoReq",
"(",
"req",
",",
"&",
"organizationAppsRes",
")",
"\n",
"}"
] |
// List apps in the default organization, or in personal account, if default
// organization is not set.
//
// lr is an optional ListRange that sets the Range options for the paginated
// list of results.
|
[
"List",
"apps",
"in",
"the",
"default",
"organization",
"or",
"in",
"personal",
"account",
"if",
"default",
"organization",
"is",
"not",
"set",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",
"of",
"results",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L111-L123
|
train
|
remind101/empire
|
pkg/heroku/organization_app.go
|
OrganizationAppListForOrganization
|
func (c *Client) OrganizationAppListForOrganization(organizationIdentity string, lr *ListRange) ([]OrganizationApp, error) {
req, err := c.NewRequest("GET", "/organizations/"+organizationIdentity+"/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationAppsRes []OrganizationApp
return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
}
|
go
|
func (c *Client) OrganizationAppListForOrganization(organizationIdentity string, lr *ListRange) ([]OrganizationApp, error) {
req, err := c.NewRequest("GET", "/organizations/"+organizationIdentity+"/apps", nil, nil)
if err != nil {
return nil, err
}
if lr != nil {
lr.SetHeader(req)
}
var organizationAppsRes []OrganizationApp
return organizationAppsRes, c.DoReq(req, &organizationAppsRes)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppListForOrganization",
"(",
"organizationIdentity",
"string",
",",
"lr",
"*",
"ListRange",
")",
"(",
"[",
"]",
"OrganizationApp",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"c",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"organizationIdentity",
"+",
"\"",
"\"",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"lr",
"!=",
"nil",
"{",
"lr",
".",
"SetHeader",
"(",
"req",
")",
"\n",
"}",
"\n\n",
"var",
"organizationAppsRes",
"[",
"]",
"OrganizationApp",
"\n",
"return",
"organizationAppsRes",
",",
"c",
".",
"DoReq",
"(",
"req",
",",
"&",
"organizationAppsRes",
")",
"\n",
"}"
] |
// List organization apps.
//
// organizationIdentity is the unique identifier of the OrganizationApp's
// Organization. lr is an optional ListRange that sets the Range options for the
// paginated list of results.
|
[
"List",
"organization",
"apps",
".",
"organizationIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationApp",
"s",
"Organization",
".",
"lr",
"is",
"an",
"optional",
"ListRange",
"that",
"sets",
"the",
"Range",
"options",
"for",
"the",
"paginated",
"list",
"of",
"results",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L130-L142
|
train
|
remind101/empire
|
pkg/heroku/organization_app.go
|
OrganizationAppInfo
|
func (c *Client) OrganizationAppInfo(appIdentity string) (*OrganizationApp, error) {
var organizationApp OrganizationApp
return &organizationApp, c.Get(&organizationApp, "/organizations/apps/"+appIdentity)
}
|
go
|
func (c *Client) OrganizationAppInfo(appIdentity string) (*OrganizationApp, error) {
var organizationApp OrganizationApp
return &organizationApp, c.Get(&organizationApp, "/organizations/apps/"+appIdentity)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppInfo",
"(",
"appIdentity",
"string",
")",
"(",
"*",
"OrganizationApp",
",",
"error",
")",
"{",
"var",
"organizationApp",
"OrganizationApp",
"\n",
"return",
"&",
"organizationApp",
",",
"c",
".",
"Get",
"(",
"&",
"organizationApp",
",",
"\"",
"\"",
"+",
"appIdentity",
")",
"\n",
"}"
] |
// Info for an organization app.
//
// appIdentity is the unique identifier of the OrganizationApp's App.
|
[
"Info",
"for",
"an",
"organization",
"app",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationApp",
"s",
"App",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L147-L150
|
train
|
remind101/empire
|
pkg/heroku/organization_app.go
|
OrganizationAppUpdateLocked
|
func (c *Client) OrganizationAppUpdateLocked(appIdentity string, locked bool) (*OrganizationApp, error) {
params := struct {
Locked bool `json:"locked"`
}{
Locked: locked,
}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.Patch(&organizationAppRes, "/organizations/apps/"+appIdentity, params)
}
|
go
|
func (c *Client) OrganizationAppUpdateLocked(appIdentity string, locked bool) (*OrganizationApp, error) {
params := struct {
Locked bool `json:"locked"`
}{
Locked: locked,
}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.Patch(&organizationAppRes, "/organizations/apps/"+appIdentity, params)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppUpdateLocked",
"(",
"appIdentity",
"string",
",",
"locked",
"bool",
")",
"(",
"*",
"OrganizationApp",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Locked",
"bool",
"`json:\"locked\"`",
"\n",
"}",
"{",
"Locked",
":",
"locked",
",",
"}",
"\n",
"var",
"organizationAppRes",
"OrganizationApp",
"\n",
"return",
"&",
"organizationAppRes",
",",
"c",
".",
"Patch",
"(",
"&",
"organizationAppRes",
",",
"\"",
"\"",
"+",
"appIdentity",
",",
"params",
")",
"\n",
"}"
] |
// Lock or unlock an organization app.
//
// appIdentity is the unique identifier of the OrganizationApp's App. locked is
// the are other organization members forbidden from joining this app.
|
[
"Lock",
"or",
"unlock",
"an",
"organization",
"app",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationApp",
"s",
"App",
".",
"locked",
"is",
"the",
"are",
"other",
"organization",
"members",
"forbidden",
"from",
"joining",
"this",
"app",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L156-L164
|
train
|
remind101/empire
|
pkg/heroku/organization_app.go
|
OrganizationAppTransferToOrganization
|
func (c *Client) OrganizationAppTransferToOrganization(appIdentity string, owner string) (*OrganizationApp, error) {
params := struct {
Owner string `json:"owner"`
}{
Owner: owner,
}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.Patch(&organizationAppRes, "/organizations/apps/"+appIdentity, params)
}
|
go
|
func (c *Client) OrganizationAppTransferToOrganization(appIdentity string, owner string) (*OrganizationApp, error) {
params := struct {
Owner string `json:"owner"`
}{
Owner: owner,
}
var organizationAppRes OrganizationApp
return &organizationAppRes, c.Patch(&organizationAppRes, "/organizations/apps/"+appIdentity, params)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"OrganizationAppTransferToOrganization",
"(",
"appIdentity",
"string",
",",
"owner",
"string",
")",
"(",
"*",
"OrganizationApp",
",",
"error",
")",
"{",
"params",
":=",
"struct",
"{",
"Owner",
"string",
"`json:\"owner\"`",
"\n",
"}",
"{",
"Owner",
":",
"owner",
",",
"}",
"\n",
"var",
"organizationAppRes",
"OrganizationApp",
"\n",
"return",
"&",
"organizationAppRes",
",",
"c",
".",
"Patch",
"(",
"&",
"organizationAppRes",
",",
"\"",
"\"",
"+",
"appIdentity",
",",
"params",
")",
"\n",
"}"
] |
// Transfer an existing organization app to another organization.
//
// appIdentity is the unique identifier of the OrganizationApp's App. owner is
// the unique name of organization.
|
[
"Transfer",
"an",
"existing",
"organization",
"app",
"to",
"another",
"organization",
".",
"appIdentity",
"is",
"the",
"unique",
"identifier",
"of",
"the",
"OrganizationApp",
"s",
"App",
".",
"owner",
"is",
"the",
"unique",
"name",
"of",
"organization",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/pkg/heroku/organization_app.go#L184-L192
|
train
|
remind101/empire
|
internal/saml/service_provider.go
|
MakeRedirectAuthenticationRequest
|
func (sp *ServiceProvider) MakeRedirectAuthenticationRequest(relayState string) (*url.URL, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPRedirectBinding))
if err != nil {
return nil, err
}
return req.Redirect(relayState), nil
}
|
go
|
func (sp *ServiceProvider) MakeRedirectAuthenticationRequest(relayState string) (*url.URL, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPRedirectBinding))
if err != nil {
return nil, err
}
return req.Redirect(relayState), nil
}
|
[
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"MakeRedirectAuthenticationRequest",
"(",
"relayState",
"string",
")",
"(",
"*",
"url",
".",
"URL",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"sp",
".",
"MakeAuthenticationRequest",
"(",
"sp",
".",
"GetSSOBindingLocation",
"(",
"HTTPRedirectBinding",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"req",
".",
"Redirect",
"(",
"relayState",
")",
",",
"nil",
"\n",
"}"
] |
// MakeRedirectAuthenticationRequest creates a SAML authentication request using
// the HTTP-Redirect binding. It returns a URL that we will redirect the user to
// in order to start the auth process.
|
[
"MakeRedirectAuthenticationRequest",
"creates",
"a",
"SAML",
"authentication",
"request",
"using",
"the",
"HTTP",
"-",
"Redirect",
"binding",
".",
"It",
"returns",
"a",
"URL",
"that",
"we",
"will",
"redirect",
"the",
"user",
"to",
"in",
"order",
"to",
"start",
"the",
"auth",
"process",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L104-L110
|
train
|
remind101/empire
|
internal/saml/service_provider.go
|
getIDPSigningCert
|
func (sp *ServiceProvider) getIDPSigningCert() []byte {
cert := ""
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "signing" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
// If there are no explicitly signing certs, just return the first
// non-empty cert we find.
if cert == "" {
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "" && keyDescriptor.KeyInfo.Certificate != "" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
}
if cert == "" {
return nil
}
// cleanup whitespace and re-encode a PEM
cert = regexp.MustCompile("\\s+").ReplaceAllString(cert, "")
certBytes, _ := base64.StdEncoding.DecodeString(cert)
certBytes = pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes})
return certBytes
}
|
go
|
func (sp *ServiceProvider) getIDPSigningCert() []byte {
cert := ""
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "signing" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
// If there are no explicitly signing certs, just return the first
// non-empty cert we find.
if cert == "" {
for _, keyDescriptor := range sp.IDPMetadata.IDPSSODescriptor.KeyDescriptor {
if keyDescriptor.Use == "" && keyDescriptor.KeyInfo.Certificate != "" {
cert = keyDescriptor.KeyInfo.Certificate
break
}
}
}
if cert == "" {
return nil
}
// cleanup whitespace and re-encode a PEM
cert = regexp.MustCompile("\\s+").ReplaceAllString(cert, "")
certBytes, _ := base64.StdEncoding.DecodeString(cert)
certBytes = pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes})
return certBytes
}
|
[
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"getIDPSigningCert",
"(",
")",
"[",
"]",
"byte",
"{",
"cert",
":=",
"\"",
"\"",
"\n\n",
"for",
"_",
",",
"keyDescriptor",
":=",
"range",
"sp",
".",
"IDPMetadata",
".",
"IDPSSODescriptor",
".",
"KeyDescriptor",
"{",
"if",
"keyDescriptor",
".",
"Use",
"==",
"\"",
"\"",
"{",
"cert",
"=",
"keyDescriptor",
".",
"KeyInfo",
".",
"Certificate",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"// If there are no explicitly signing certs, just return the first",
"// non-empty cert we find.",
"if",
"cert",
"==",
"\"",
"\"",
"{",
"for",
"_",
",",
"keyDescriptor",
":=",
"range",
"sp",
".",
"IDPMetadata",
".",
"IDPSSODescriptor",
".",
"KeyDescriptor",
"{",
"if",
"keyDescriptor",
".",
"Use",
"==",
"\"",
"\"",
"&&",
"keyDescriptor",
".",
"KeyInfo",
".",
"Certificate",
"!=",
"\"",
"\"",
"{",
"cert",
"=",
"keyDescriptor",
".",
"KeyInfo",
".",
"Certificate",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"cert",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// cleanup whitespace and re-encode a PEM",
"cert",
"=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\\\\",
"\"",
")",
".",
"ReplaceAllString",
"(",
"cert",
",",
"\"",
"\"",
")",
"\n",
"certBytes",
",",
"_",
":=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"cert",
")",
"\n",
"certBytes",
"=",
"pem",
".",
"EncodeToMemory",
"(",
"&",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"",
"\"",
",",
"Bytes",
":",
"certBytes",
"}",
")",
"\n",
"return",
"certBytes",
"\n",
"}"
] |
// getIDPSigningCert returns the certificate which we can use to verify things
// signed by the IDP in PEM format, or nil if no such certificate is found.
|
[
"getIDPSigningCert",
"returns",
"the",
"certificate",
"which",
"we",
"can",
"use",
"to",
"verify",
"things",
"signed",
"by",
"the",
"IDP",
"in",
"PEM",
"format",
"or",
"nil",
"if",
"no",
"such",
"certificate",
"is",
"found",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L148-L180
|
train
|
remind101/empire
|
internal/saml/service_provider.go
|
MakePostAuthenticationRequest
|
func (sp *ServiceProvider) MakePostAuthenticationRequest(relayState string) ([]byte, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPPostBinding))
if err != nil {
return nil, err
}
return req.Post(relayState), nil
}
|
go
|
func (sp *ServiceProvider) MakePostAuthenticationRequest(relayState string) ([]byte, error) {
req, err := sp.MakeAuthenticationRequest(sp.GetSSOBindingLocation(HTTPPostBinding))
if err != nil {
return nil, err
}
return req.Post(relayState), nil
}
|
[
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"MakePostAuthenticationRequest",
"(",
"relayState",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"sp",
".",
"MakeAuthenticationRequest",
"(",
"sp",
".",
"GetSSOBindingLocation",
"(",
"HTTPPostBinding",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"req",
".",
"Post",
"(",
"relayState",
")",
",",
"nil",
"\n",
"}"
] |
// MakePostAuthenticationRequest creates a SAML authentication request using
// the HTTP-POST binding. It returns HTML text representing an HTML form that
// can be sent presented to a browser to initiate the login process.
|
[
"MakePostAuthenticationRequest",
"creates",
"a",
"SAML",
"authentication",
"request",
"using",
"the",
"HTTP",
"-",
"POST",
"binding",
".",
"It",
"returns",
"HTML",
"text",
"representing",
"an",
"HTML",
"form",
"that",
"can",
"be",
"sent",
"presented",
"to",
"a",
"browser",
"to",
"initiate",
"the",
"login",
"process",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L209-L215
|
train
|
remind101/empire
|
internal/saml/service_provider.go
|
Get
|
func (aa AssertionAttributes) Get(name string) *AssertionAttribute {
for _, attr := range aa {
if attr.Name == name {
return &attr
}
if attr.FriendlyName == name {
return &attr
}
}
return nil
}
|
go
|
func (aa AssertionAttributes) Get(name string) *AssertionAttribute {
for _, attr := range aa {
if attr.Name == name {
return &attr
}
if attr.FriendlyName == name {
return &attr
}
}
return nil
}
|
[
"func",
"(",
"aa",
"AssertionAttributes",
")",
"Get",
"(",
"name",
"string",
")",
"*",
"AssertionAttribute",
"{",
"for",
"_",
",",
"attr",
":=",
"range",
"aa",
"{",
"if",
"attr",
".",
"Name",
"==",
"name",
"{",
"return",
"&",
"attr",
"\n",
"}",
"\n",
"if",
"attr",
".",
"FriendlyName",
"==",
"name",
"{",
"return",
"&",
"attr",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Get returns the assertion attribute whose Name or FriendlyName
// matches name, or nil if no matching attribute is found.
|
[
"Get",
"returns",
"the",
"assertion",
"attribute",
"whose",
"Name",
"or",
"FriendlyName",
"matches",
"name",
"or",
"nil",
"if",
"no",
"matching",
"attribute",
"is",
"found",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L255-L265
|
train
|
remind101/empire
|
internal/saml/service_provider.go
|
InitiateLogin
|
func (sp *ServiceProvider) InitiateLogin(w http.ResponseWriter) error {
acsURL, _ := url.Parse(sp.AcsURL)
binding := HTTPRedirectBinding
bindingLocation := sp.GetSSOBindingLocation(binding)
if bindingLocation == "" {
binding = HTTPPostBinding
bindingLocation = sp.GetSSOBindingLocation(binding)
}
req, err := sp.MakeAuthenticationRequest(bindingLocation)
if err != nil {
return err
}
relayState := base64.URLEncoding.EncodeToString(randomBytes(42))
state := jwt.New(jwt.GetSigningMethod("HS256"))
claims := state.Claims.(jwt.MapClaims)
claims["id"] = req.ID
signedState, err := state.SignedString(sp.cookieSecret())
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: fmt.Sprintf("saml_%s", relayState),
Value: signedState,
MaxAge: int(MaxIssueDelay.Seconds()),
HttpOnly: false,
Path: acsURL.Path,
})
if binding == HTTPRedirectBinding {
redirectURL := req.Redirect(relayState)
w.Header().Add("Location", redirectURL.String())
w.WriteHeader(http.StatusFound)
return nil
}
if binding == HTTPPostBinding {
w.Header().Set("Content-Security-Policy", ""+
"default-src; "+
"script-src 'sha256-D8xB+y+rJ90RmLdP72xBqEEc0NUatn7yuCND0orkrgk='; "+
"reflected-xss block; "+
"referrer no-referrer;")
w.Header().Add("Content-type", "text/html")
w.Write([]byte(`<!DOCTYPE html><html><body>`))
w.Write(req.Post(relayState))
w.Write([]byte(`</body></html>`))
return nil
}
panic("not reached")
}
|
go
|
func (sp *ServiceProvider) InitiateLogin(w http.ResponseWriter) error {
acsURL, _ := url.Parse(sp.AcsURL)
binding := HTTPRedirectBinding
bindingLocation := sp.GetSSOBindingLocation(binding)
if bindingLocation == "" {
binding = HTTPPostBinding
bindingLocation = sp.GetSSOBindingLocation(binding)
}
req, err := sp.MakeAuthenticationRequest(bindingLocation)
if err != nil {
return err
}
relayState := base64.URLEncoding.EncodeToString(randomBytes(42))
state := jwt.New(jwt.GetSigningMethod("HS256"))
claims := state.Claims.(jwt.MapClaims)
claims["id"] = req.ID
signedState, err := state.SignedString(sp.cookieSecret())
if err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
Name: fmt.Sprintf("saml_%s", relayState),
Value: signedState,
MaxAge: int(MaxIssueDelay.Seconds()),
HttpOnly: false,
Path: acsURL.Path,
})
if binding == HTTPRedirectBinding {
redirectURL := req.Redirect(relayState)
w.Header().Add("Location", redirectURL.String())
w.WriteHeader(http.StatusFound)
return nil
}
if binding == HTTPPostBinding {
w.Header().Set("Content-Security-Policy", ""+
"default-src; "+
"script-src 'sha256-D8xB+y+rJ90RmLdP72xBqEEc0NUatn7yuCND0orkrgk='; "+
"reflected-xss block; "+
"referrer no-referrer;")
w.Header().Add("Content-type", "text/html")
w.Write([]byte(`<!DOCTYPE html><html><body>`))
w.Write(req.Post(relayState))
w.Write([]byte(`</body></html>`))
return nil
}
panic("not reached")
}
|
[
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"InitiateLogin",
"(",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"acsURL",
",",
"_",
":=",
"url",
".",
"Parse",
"(",
"sp",
".",
"AcsURL",
")",
"\n\n",
"binding",
":=",
"HTTPRedirectBinding",
"\n",
"bindingLocation",
":=",
"sp",
".",
"GetSSOBindingLocation",
"(",
"binding",
")",
"\n",
"if",
"bindingLocation",
"==",
"\"",
"\"",
"{",
"binding",
"=",
"HTTPPostBinding",
"\n",
"bindingLocation",
"=",
"sp",
".",
"GetSSOBindingLocation",
"(",
"binding",
")",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"sp",
".",
"MakeAuthenticationRequest",
"(",
"bindingLocation",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"relayState",
":=",
"base64",
".",
"URLEncoding",
".",
"EncodeToString",
"(",
"randomBytes",
"(",
"42",
")",
")",
"\n",
"state",
":=",
"jwt",
".",
"New",
"(",
"jwt",
".",
"GetSigningMethod",
"(",
"\"",
"\"",
")",
")",
"\n",
"claims",
":=",
"state",
".",
"Claims",
".",
"(",
"jwt",
".",
"MapClaims",
")",
"\n",
"claims",
"[",
"\"",
"\"",
"]",
"=",
"req",
".",
"ID",
"\n",
"signedState",
",",
"err",
":=",
"state",
".",
"SignedString",
"(",
"sp",
".",
"cookieSecret",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"http",
".",
"SetCookie",
"(",
"w",
",",
"&",
"http",
".",
"Cookie",
"{",
"Name",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"relayState",
")",
",",
"Value",
":",
"signedState",
",",
"MaxAge",
":",
"int",
"(",
"MaxIssueDelay",
".",
"Seconds",
"(",
")",
")",
",",
"HttpOnly",
":",
"false",
",",
"Path",
":",
"acsURL",
".",
"Path",
",",
"}",
")",
"\n\n",
"if",
"binding",
"==",
"HTTPRedirectBinding",
"{",
"redirectURL",
":=",
"req",
".",
"Redirect",
"(",
"relayState",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"redirectURL",
".",
"String",
"(",
")",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusFound",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"binding",
"==",
"HTTPPostBinding",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"`<!DOCTYPE html><html><body>`",
")",
")",
"\n",
"w",
".",
"Write",
"(",
"req",
".",
"Post",
"(",
"relayState",
")",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"`</body></html>`",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// Login performs the necessary actions to start an SP initiated login.
|
[
"Login",
"performs",
"the",
"necessary",
"actions",
"to",
"start",
"an",
"SP",
"initiated",
"login",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L443-L494
|
train
|
remind101/empire
|
internal/saml/service_provider.go
|
Parse
|
func (sp *ServiceProvider) Parse(w http.ResponseWriter, r *http.Request) (*Assertion, error) {
allowIdPInitiated := ""
possibleRequestIDs := []string{allowIdPInitiated}
// Find the request id that relates to this RelayState.
relayState := r.PostFormValue("RelayState")
if sp.cookieSecret() != nil && relayState != "" {
cookieName := fmt.Sprintf("saml_%s", relayState)
cookie, err := r.Cookie(cookieName)
if err != nil {
return nil, fmt.Errorf("cannot find %s cookie", cookieName)
}
// Verify the integrity of the cookie.
state, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) {
return sp.cookieSecret(), nil
})
if err != nil || !state.Valid {
return nil, fmt.Errorf("could not decode state JWT: %v", err)
}
claims := state.Claims.(jwt.MapClaims)
id := claims["id"].(string)
possibleRequestIDs = append(possibleRequestIDs, id)
// delete the cookie
cookie.Value = ""
cookie.Expires = time.Time{}
http.SetCookie(w, cookie)
}
samlResponse := r.PostFormValue("SAMLResponse")
return sp.ParseSAMLResponse(samlResponse, possibleRequestIDs)
}
|
go
|
func (sp *ServiceProvider) Parse(w http.ResponseWriter, r *http.Request) (*Assertion, error) {
allowIdPInitiated := ""
possibleRequestIDs := []string{allowIdPInitiated}
// Find the request id that relates to this RelayState.
relayState := r.PostFormValue("RelayState")
if sp.cookieSecret() != nil && relayState != "" {
cookieName := fmt.Sprintf("saml_%s", relayState)
cookie, err := r.Cookie(cookieName)
if err != nil {
return nil, fmt.Errorf("cannot find %s cookie", cookieName)
}
// Verify the integrity of the cookie.
state, err := jwt.Parse(cookie.Value, func(t *jwt.Token) (interface{}, error) {
return sp.cookieSecret(), nil
})
if err != nil || !state.Valid {
return nil, fmt.Errorf("could not decode state JWT: %v", err)
}
claims := state.Claims.(jwt.MapClaims)
id := claims["id"].(string)
possibleRequestIDs = append(possibleRequestIDs, id)
// delete the cookie
cookie.Value = ""
cookie.Expires = time.Time{}
http.SetCookie(w, cookie)
}
samlResponse := r.PostFormValue("SAMLResponse")
return sp.ParseSAMLResponse(samlResponse, possibleRequestIDs)
}
|
[
"func",
"(",
"sp",
"*",
"ServiceProvider",
")",
"Parse",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"Assertion",
",",
"error",
")",
"{",
"allowIdPInitiated",
":=",
"\"",
"\"",
"\n",
"possibleRequestIDs",
":=",
"[",
"]",
"string",
"{",
"allowIdPInitiated",
"}",
"\n\n",
"// Find the request id that relates to this RelayState.",
"relayState",
":=",
"r",
".",
"PostFormValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"sp",
".",
"cookieSecret",
"(",
")",
"!=",
"nil",
"&&",
"relayState",
"!=",
"\"",
"\"",
"{",
"cookieName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"relayState",
")",
"\n",
"cookie",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"cookieName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cookieName",
")",
"\n",
"}",
"\n\n",
"// Verify the integrity of the cookie.",
"state",
",",
"err",
":=",
"jwt",
".",
"Parse",
"(",
"cookie",
".",
"Value",
",",
"func",
"(",
"t",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"return",
"sp",
".",
"cookieSecret",
"(",
")",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"!",
"state",
".",
"Valid",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"claims",
":=",
"state",
".",
"Claims",
".",
"(",
"jwt",
".",
"MapClaims",
")",
"\n",
"id",
":=",
"claims",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n\n",
"possibleRequestIDs",
"=",
"append",
"(",
"possibleRequestIDs",
",",
"id",
")",
"\n\n",
"// delete the cookie",
"cookie",
".",
"Value",
"=",
"\"",
"\"",
"\n",
"cookie",
".",
"Expires",
"=",
"time",
".",
"Time",
"{",
"}",
"\n",
"http",
".",
"SetCookie",
"(",
"w",
",",
"cookie",
")",
"\n",
"}",
"\n\n",
"samlResponse",
":=",
"r",
".",
"PostFormValue",
"(",
"\"",
"\"",
")",
"\n",
"return",
"sp",
".",
"ParseSAMLResponse",
"(",
"samlResponse",
",",
"possibleRequestIDs",
")",
"\n",
"}"
] |
// Parse parses the SAMLResponse
|
[
"Parse",
"parses",
"the",
"SAMLResponse"
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/saml/service_provider.go#L497-L531
|
train
|
remind101/empire
|
internal/realip/realip.go
|
RealIP
|
func (r *Resolver) RealIP(req *http.Request) string {
var hdrRealIP string
if r.XRealIp {
hdrRealIP = req.Header.Get("X-Real-Ip")
}
var hdrForwardedFor string
if r.XForwardedFor {
hdrForwardedFor = req.Header.Get("X-Forwarded-For")
}
if len(hdrForwardedFor) == 0 && len(hdrRealIP) == 0 {
return ipAddrFromRemoteAddr(req.RemoteAddr)
}
// X-Forwarded-For is potentially a list of addresses separated with ","
forwarded := sort.StringSlice(strings.Split(hdrForwardedFor, ","))
// This will ignore the X-Forwarded-For entries matching a load balancer
// and use the first (from right to left) untrused address as the real
// ip. This is done to prevent spoofing X-Forwarded-For.
//
// For example, let's say you wanted try to spoof your ip to make it
// look like a request came from an office ip (204.28.121.211). You
// would make a request like this:
//
// curl https://www.example.com/debug -H "X-Forwarded-For: 204.28.121.211"
//
// The load balancer would then tag on the connecting ip, as well as the
// ip address of the load balancer itself. The application would receive
// an X-Forwarded-For header like the following:
//
// "X-Forwarded-For": [
// "204.28.121.211, 49.228.250.246, 10.128.21.180"
// ]
//
// This will look at each ip from right to left, and use the first
// "untrusted" address as the real ip.
//
// 1. The first ip, 10.128.21.180, is the loadbalancer ip address and is
// considered trusted because it's a LAN cidr.
// 2. The second ip, 49.228.250.246, is untrusted, so this is determined to
// be the real ip address.
//
// By doing this, the spoofed ip (204.28.121.211) is ignored.
reverse(forwarded)
for _, addr := range forwarded {
// return first non-local address
addr = strings.TrimSpace(addr)
if len(addr) > 0 && !isLocalAddress(addr) {
return addr
}
}
return hdrRealIP
}
|
go
|
func (r *Resolver) RealIP(req *http.Request) string {
var hdrRealIP string
if r.XRealIp {
hdrRealIP = req.Header.Get("X-Real-Ip")
}
var hdrForwardedFor string
if r.XForwardedFor {
hdrForwardedFor = req.Header.Get("X-Forwarded-For")
}
if len(hdrForwardedFor) == 0 && len(hdrRealIP) == 0 {
return ipAddrFromRemoteAddr(req.RemoteAddr)
}
// X-Forwarded-For is potentially a list of addresses separated with ","
forwarded := sort.StringSlice(strings.Split(hdrForwardedFor, ","))
// This will ignore the X-Forwarded-For entries matching a load balancer
// and use the first (from right to left) untrused address as the real
// ip. This is done to prevent spoofing X-Forwarded-For.
//
// For example, let's say you wanted try to spoof your ip to make it
// look like a request came from an office ip (204.28.121.211). You
// would make a request like this:
//
// curl https://www.example.com/debug -H "X-Forwarded-For: 204.28.121.211"
//
// The load balancer would then tag on the connecting ip, as well as the
// ip address of the load balancer itself. The application would receive
// an X-Forwarded-For header like the following:
//
// "X-Forwarded-For": [
// "204.28.121.211, 49.228.250.246, 10.128.21.180"
// ]
//
// This will look at each ip from right to left, and use the first
// "untrusted" address as the real ip.
//
// 1. The first ip, 10.128.21.180, is the loadbalancer ip address and is
// considered trusted because it's a LAN cidr.
// 2. The second ip, 49.228.250.246, is untrusted, so this is determined to
// be the real ip address.
//
// By doing this, the spoofed ip (204.28.121.211) is ignored.
reverse(forwarded)
for _, addr := range forwarded {
// return first non-local address
addr = strings.TrimSpace(addr)
if len(addr) > 0 && !isLocalAddress(addr) {
return addr
}
}
return hdrRealIP
}
|
[
"func",
"(",
"r",
"*",
"Resolver",
")",
"RealIP",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"var",
"hdrRealIP",
"string",
"\n",
"if",
"r",
".",
"XRealIp",
"{",
"hdrRealIP",
"=",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"hdrForwardedFor",
"string",
"\n",
"if",
"r",
".",
"XForwardedFor",
"{",
"hdrForwardedFor",
"=",
"req",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"hdrForwardedFor",
")",
"==",
"0",
"&&",
"len",
"(",
"hdrRealIP",
")",
"==",
"0",
"{",
"return",
"ipAddrFromRemoteAddr",
"(",
"req",
".",
"RemoteAddr",
")",
"\n",
"}",
"\n\n",
"// X-Forwarded-For is potentially a list of addresses separated with \",\"",
"forwarded",
":=",
"sort",
".",
"StringSlice",
"(",
"strings",
".",
"Split",
"(",
"hdrForwardedFor",
",",
"\"",
"\"",
")",
")",
"\n\n",
"// This will ignore the X-Forwarded-For entries matching a load balancer",
"// and use the first (from right to left) untrused address as the real",
"// ip. This is done to prevent spoofing X-Forwarded-For.",
"//",
"// For example, let's say you wanted try to spoof your ip to make it",
"// look like a request came from an office ip (204.28.121.211). You",
"// would make a request like this:",
"//",
"// curl https://www.example.com/debug -H \"X-Forwarded-For: 204.28.121.211\"",
"//",
"// The load balancer would then tag on the connecting ip, as well as the",
"// ip address of the load balancer itself. The application would receive",
"// an X-Forwarded-For header like the following:",
"//",
"// \"X-Forwarded-For\": [",
"// \"204.28.121.211, 49.228.250.246, 10.128.21.180\"",
"// ]",
"//",
"// This will look at each ip from right to left, and use the first",
"// \"untrusted\" address as the real ip.",
"//",
"// 1. The first ip, 10.128.21.180, is the loadbalancer ip address and is",
"// considered trusted because it's a LAN cidr.",
"// 2. The second ip, 49.228.250.246, is untrusted, so this is determined to",
"// be the real ip address.",
"//",
"// By doing this, the spoofed ip (204.28.121.211) is ignored.",
"reverse",
"(",
"forwarded",
")",
"\n\n",
"for",
"_",
",",
"addr",
":=",
"range",
"forwarded",
"{",
"// return first non-local address",
"addr",
"=",
"strings",
".",
"TrimSpace",
"(",
"addr",
")",
"\n",
"if",
"len",
"(",
"addr",
")",
">",
"0",
"&&",
"!",
"isLocalAddress",
"(",
"addr",
")",
"{",
"return",
"addr",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"hdrRealIP",
"\n",
"}"
] |
// RealIP return client's real public IP address
// from http request headers.
|
[
"RealIP",
"return",
"client",
"s",
"real",
"public",
"IP",
"address",
"from",
"http",
"request",
"headers",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/realip/realip.go#L67-L123
|
train
|
remind101/empire
|
internal/realip/realip.go
|
Middleware
|
func Middleware(h http.Handler, r *Resolver) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ip := r.RealIP(req)
h.ServeHTTP(w, req.WithContext(context.WithValue(req.Context(), realIPKey, ip)))
})
}
|
go
|
func Middleware(h http.Handler, r *Resolver) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ip := r.RealIP(req)
h.ServeHTTP(w, req.WithContext(context.WithValue(req.Context(), realIPKey, ip)))
})
}
|
[
"func",
"Middleware",
"(",
"h",
"http",
".",
"Handler",
",",
"r",
"*",
"Resolver",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"ip",
":=",
"r",
".",
"RealIP",
"(",
"req",
")",
"\n",
"h",
".",
"ServeHTTP",
"(",
"w",
",",
"req",
".",
"WithContext",
"(",
"context",
".",
"WithValue",
"(",
"req",
".",
"Context",
"(",
")",
",",
"realIPKey",
",",
"ip",
")",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] |
// Middleware is a simple http.Handler middleware that extracts the RealIP from
// the request and set it on the request context. Anything downstream can then
// simply call realip.RealIP to extract the real ip from the request.
|
[
"Middleware",
"is",
"a",
"simple",
"http",
".",
"Handler",
"middleware",
"that",
"extracts",
"the",
"RealIP",
"from",
"the",
"request",
"and",
"set",
"it",
"on",
"the",
"request",
"context",
".",
"Anything",
"downstream",
"can",
"then",
"simply",
"call",
"realip",
".",
"RealIP",
"to",
"extract",
"the",
"real",
"ip",
"from",
"the",
"request",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/realip/realip.go#L128-L133
|
train
|
remind101/empire
|
internal/realip/realip.go
|
RealIP
|
func RealIP(req *http.Request) string {
ip, ok := req.Context().Value(realIPKey).(string)
if !ok {
// Fallback to a secure resolver.
return DefaultResolver.RealIP(req)
}
return ip
}
|
go
|
func RealIP(req *http.Request) string {
ip, ok := req.Context().Value(realIPKey).(string)
if !ok {
// Fallback to a secure resolver.
return DefaultResolver.RealIP(req)
}
return ip
}
|
[
"func",
"RealIP",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"string",
"{",
"ip",
",",
"ok",
":=",
"req",
".",
"Context",
"(",
")",
".",
"Value",
"(",
"realIPKey",
")",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"// Fallback to a secure resolver.",
"return",
"DefaultResolver",
".",
"RealIP",
"(",
"req",
")",
"\n",
"}",
"\n",
"return",
"ip",
"\n",
"}"
] |
// Extracts the real ip from the request context.
|
[
"Extracts",
"the",
"real",
"ip",
"from",
"the",
"request",
"context",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/realip/realip.go#L136-L143
|
train
|
remind101/empire
|
internal/realip/realip.go
|
reverse
|
func reverse(ss []string) {
last := len(ss) - 1
for i := 0; i < len(ss)/2; i++ {
ss[i], ss[last-i] = ss[last-i], ss[i]
}
}
|
go
|
func reverse(ss []string) {
last := len(ss) - 1
for i := 0; i < len(ss)/2; i++ {
ss[i], ss[last-i] = ss[last-i], ss[i]
}
}
|
[
"func",
"reverse",
"(",
"ss",
"[",
"]",
"string",
")",
"{",
"last",
":=",
"len",
"(",
"ss",
")",
"-",
"1",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"ss",
")",
"/",
"2",
";",
"i",
"++",
"{",
"ss",
"[",
"i",
"]",
",",
"ss",
"[",
"last",
"-",
"i",
"]",
"=",
"ss",
"[",
"last",
"-",
"i",
"]",
",",
"ss",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}"
] |
// reverse reverses a slice of strings.
|
[
"reverse",
"reverses",
"a",
"slice",
"of",
"strings",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/internal/realip/realip.go#L146-L151
|
train
|
remind101/empire
|
stats/statsd.go
|
NewStatsd
|
func NewStatsd(addr, prefix string) (*Statsd, error) {
c, err := statsd.NewClient(addr, prefix)
if err != nil {
return nil, err
}
return &Statsd{
client: c,
}, nil
}
|
go
|
func NewStatsd(addr, prefix string) (*Statsd, error) {
c, err := statsd.NewClient(addr, prefix)
if err != nil {
return nil, err
}
return &Statsd{
client: c,
}, nil
}
|
[
"func",
"NewStatsd",
"(",
"addr",
",",
"prefix",
"string",
")",
"(",
"*",
"Statsd",
",",
"error",
")",
"{",
"c",
",",
"err",
":=",
"statsd",
".",
"NewClient",
"(",
"addr",
",",
"prefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"Statsd",
"{",
"client",
":",
"c",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewStatsd returns a new Statsd implementation that sends stats to addr.
|
[
"NewStatsd",
"returns",
"a",
"new",
"Statsd",
"implementation",
"that",
"sends",
"stats",
"to",
"addr",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/stats/statsd.go#L15-L23
|
train
|
remind101/empire
|
scheduler/docker/docker.go
|
RunAttachedWithDocker
|
func RunAttachedWithDocker(s twelvefactor.Scheduler, client *dockerutil.Client) *AttachedScheduler {
return &AttachedScheduler{
Scheduler: s,
dockerScheduler: NewScheduler(client),
}
}
|
go
|
func RunAttachedWithDocker(s twelvefactor.Scheduler, client *dockerutil.Client) *AttachedScheduler {
return &AttachedScheduler{
Scheduler: s,
dockerScheduler: NewScheduler(client),
}
}
|
[
"func",
"RunAttachedWithDocker",
"(",
"s",
"twelvefactor",
".",
"Scheduler",
",",
"client",
"*",
"dockerutil",
".",
"Client",
")",
"*",
"AttachedScheduler",
"{",
"return",
"&",
"AttachedScheduler",
"{",
"Scheduler",
":",
"s",
",",
"dockerScheduler",
":",
"NewScheduler",
"(",
"client",
")",
",",
"}",
"\n",
"}"
] |
// RunAttachedWithDocker wraps a Scheduler to run attached Run's using a Docker
// client.
|
[
"RunAttachedWithDocker",
"wraps",
"a",
"Scheduler",
"to",
"run",
"attached",
"Run",
"s",
"using",
"a",
"Docker",
"client",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L66-L71
|
train
|
remind101/empire
|
scheduler/docker/docker.go
|
Run
|
func (s *AttachedScheduler) Run(ctx context.Context, app *twelvefactor.Manifest) error {
if len(app.Processes) != 1 {
return fmt.Errorf("docker: cannot run mutliple processes with attached scheduler")
}
p := app.Processes[0]
// Attached means stdout, stdin is attached.
attached := p.Stdin != nil || p.Stdout != nil || p.Stderr != nil
if attached {
return s.dockerScheduler.Run(ctx, app)
} else {
return s.Scheduler.Run(ctx, app)
}
}
|
go
|
func (s *AttachedScheduler) Run(ctx context.Context, app *twelvefactor.Manifest) error {
if len(app.Processes) != 1 {
return fmt.Errorf("docker: cannot run mutliple processes with attached scheduler")
}
p := app.Processes[0]
// Attached means stdout, stdin is attached.
attached := p.Stdin != nil || p.Stdout != nil || p.Stderr != nil
if attached {
return s.dockerScheduler.Run(ctx, app)
} else {
return s.Scheduler.Run(ctx, app)
}
}
|
[
"func",
"(",
"s",
"*",
"AttachedScheduler",
")",
"Run",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"*",
"twelvefactor",
".",
"Manifest",
")",
"error",
"{",
"if",
"len",
"(",
"app",
".",
"Processes",
")",
"!=",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"p",
":=",
"app",
".",
"Processes",
"[",
"0",
"]",
"\n",
"// Attached means stdout, stdin is attached.",
"attached",
":=",
"p",
".",
"Stdin",
"!=",
"nil",
"||",
"p",
".",
"Stdout",
"!=",
"nil",
"||",
"p",
".",
"Stderr",
"!=",
"nil",
"\n\n",
"if",
"attached",
"{",
"return",
"s",
".",
"dockerScheduler",
".",
"Run",
"(",
"ctx",
",",
"app",
")",
"\n",
"}",
"else",
"{",
"return",
"s",
".",
"Scheduler",
".",
"Run",
"(",
"ctx",
",",
"app",
")",
"\n",
"}",
"\n",
"}"
] |
// Run runs attached processes using the docker scheduler, and detached
// processes using the wrapped scheduler.
|
[
"Run",
"runs",
"attached",
"processes",
"using",
"the",
"docker",
"scheduler",
"and",
"detached",
"processes",
"using",
"the",
"wrapped",
"scheduler",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L75-L89
|
train
|
remind101/empire
|
scheduler/docker/docker.go
|
Tasks
|
func (s *AttachedScheduler) Tasks(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
if !s.ShowAttached {
return s.Scheduler.Tasks(ctx, app)
}
type instancesResult struct {
instances []*twelvefactor.Task
err error
}
ch := make(chan instancesResult, 1)
go func() {
attachedInstances, err := s.dockerScheduler.InstancesFromAttachedRuns(ctx, app)
ch <- instancesResult{attachedInstances, err}
}()
instances, err := s.Scheduler.Tasks(ctx, app)
if err != nil {
return instances, err
}
result := <-ch
if err := result.err; err != nil {
return instances, err
}
return append(instances, result.instances...), nil
}
|
go
|
func (s *AttachedScheduler) Tasks(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
if !s.ShowAttached {
return s.Scheduler.Tasks(ctx, app)
}
type instancesResult struct {
instances []*twelvefactor.Task
err error
}
ch := make(chan instancesResult, 1)
go func() {
attachedInstances, err := s.dockerScheduler.InstancesFromAttachedRuns(ctx, app)
ch <- instancesResult{attachedInstances, err}
}()
instances, err := s.Scheduler.Tasks(ctx, app)
if err != nil {
return instances, err
}
result := <-ch
if err := result.err; err != nil {
return instances, err
}
return append(instances, result.instances...), nil
}
|
[
"func",
"(",
"s",
"*",
"AttachedScheduler",
")",
"Tasks",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"string",
")",
"(",
"[",
"]",
"*",
"twelvefactor",
".",
"Task",
",",
"error",
")",
"{",
"if",
"!",
"s",
".",
"ShowAttached",
"{",
"return",
"s",
".",
"Scheduler",
".",
"Tasks",
"(",
"ctx",
",",
"app",
")",
"\n",
"}",
"\n\n",
"type",
"instancesResult",
"struct",
"{",
"instances",
"[",
"]",
"*",
"twelvefactor",
".",
"Task",
"\n",
"err",
"error",
"\n",
"}",
"\n\n",
"ch",
":=",
"make",
"(",
"chan",
"instancesResult",
",",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"attachedInstances",
",",
"err",
":=",
"s",
".",
"dockerScheduler",
".",
"InstancesFromAttachedRuns",
"(",
"ctx",
",",
"app",
")",
"\n",
"ch",
"<-",
"instancesResult",
"{",
"attachedInstances",
",",
"err",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"instances",
",",
"err",
":=",
"s",
".",
"Scheduler",
".",
"Tasks",
"(",
"ctx",
",",
"app",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"instances",
",",
"err",
"\n",
"}",
"\n\n",
"result",
":=",
"<-",
"ch",
"\n",
"if",
"err",
":=",
"result",
".",
"err",
";",
"err",
"!=",
"nil",
"{",
"return",
"instances",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"append",
"(",
"instances",
",",
"result",
".",
"instances",
"...",
")",
",",
"nil",
"\n",
"}"
] |
// Tasks returns a combination of instances from the wrapped scheduler, as
// well as instances from attached runs.
|
[
"Tasks",
"returns",
"a",
"combination",
"of",
"instances",
"from",
"the",
"wrapped",
"scheduler",
"as",
"well",
"as",
"instances",
"from",
"attached",
"runs",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L93-L120
|
train
|
remind101/empire
|
scheduler/docker/docker.go
|
Stop
|
func (s *AttachedScheduler) Stop(ctx context.Context, maybeContainerID string) error {
if !s.ShowAttached {
return s.Scheduler.Stop(ctx, maybeContainerID)
}
err := s.dockerScheduler.Stop(ctx, maybeContainerID)
// If there's no container with this ID, delegate to the wrapped
// scheduler.
if _, ok := err.(*docker.NoSuchContainer); ok {
return s.Scheduler.Stop(ctx, maybeContainerID)
}
return err
}
|
go
|
func (s *AttachedScheduler) Stop(ctx context.Context, maybeContainerID string) error {
if !s.ShowAttached {
return s.Scheduler.Stop(ctx, maybeContainerID)
}
err := s.dockerScheduler.Stop(ctx, maybeContainerID)
// If there's no container with this ID, delegate to the wrapped
// scheduler.
if _, ok := err.(*docker.NoSuchContainer); ok {
return s.Scheduler.Stop(ctx, maybeContainerID)
}
return err
}
|
[
"func",
"(",
"s",
"*",
"AttachedScheduler",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
",",
"maybeContainerID",
"string",
")",
"error",
"{",
"if",
"!",
"s",
".",
"ShowAttached",
"{",
"return",
"s",
".",
"Scheduler",
".",
"Stop",
"(",
"ctx",
",",
"maybeContainerID",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"s",
".",
"dockerScheduler",
".",
"Stop",
"(",
"ctx",
",",
"maybeContainerID",
")",
"\n\n",
"// If there's no container with this ID, delegate to the wrapped",
"// scheduler.",
"if",
"_",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"docker",
".",
"NoSuchContainer",
")",
";",
"ok",
"{",
"return",
"s",
".",
"Scheduler",
".",
"Stop",
"(",
"ctx",
",",
"maybeContainerID",
")",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}"
] |
// Stop checks if there's an attached run matching the given id, and stops that
// container if there is. Otherwise, it delegates to the wrapped Scheduler.
|
[
"Stop",
"checks",
"if",
"there",
"s",
"an",
"attached",
"run",
"matching",
"the",
"given",
"id",
"and",
"stops",
"that",
"container",
"if",
"there",
"is",
".",
"Otherwise",
"it",
"delegates",
"to",
"the",
"wrapped",
"Scheduler",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L124-L138
|
train
|
remind101/empire
|
scheduler/docker/docker.go
|
InstancesFromAttachedRuns
|
func (s *Scheduler) InstancesFromAttachedRuns(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
// Filter only docker containers that were started as an attached run.
attached := fmt.Sprintf("%s=%s", runLabel, Attached)
return s.instances(ctx, app, attached)
}
|
go
|
func (s *Scheduler) InstancesFromAttachedRuns(ctx context.Context, app string) ([]*twelvefactor.Task, error) {
// Filter only docker containers that were started as an attached run.
attached := fmt.Sprintf("%s=%s", runLabel, Attached)
return s.instances(ctx, app, attached)
}
|
[
"func",
"(",
"s",
"*",
"Scheduler",
")",
"InstancesFromAttachedRuns",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"string",
")",
"(",
"[",
"]",
"*",
"twelvefactor",
".",
"Task",
",",
"error",
")",
"{",
"// Filter only docker containers that were started as an attached run.",
"attached",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"runLabel",
",",
"Attached",
")",
"\n",
"return",
"s",
".",
"instances",
"(",
"ctx",
",",
"app",
",",
"attached",
")",
"\n",
"}"
] |
// InstancesFromAttachedRuns returns Instances that were started from attached
// runs.
|
[
"InstancesFromAttachedRuns",
"returns",
"Instances",
"that",
"were",
"started",
"from",
"attached",
"runs",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L234-L238
|
train
|
remind101/empire
|
scheduler/docker/docker.go
|
instances
|
func (s *Scheduler) instances(ctx context.Context, app string, labels ...string) ([]*twelvefactor.Task, error) {
var instances []*twelvefactor.Task
containers, err := s.docker.ListContainers(docker.ListContainersOptions{
Filters: map[string][]string{
"label": append([]string{
fmt.Sprintf("%s=%s", appLabel, app),
}, labels...),
},
})
if err != nil {
return nil, fmt.Errorf("error listing containers from attached runs: %v", err)
}
for _, apiContainer := range containers {
container, err := s.docker.InspectContainer(apiContainer.ID)
if err != nil {
return instances, fmt.Errorf("error inspecting container %s: %v", apiContainer.ID, err)
}
state := strings.ToUpper(container.State.StateString())
instances = append(instances, &twelvefactor.Task{
ID: container.ID[0:12],
State: state,
UpdatedAt: container.State.StartedAt,
Process: &twelvefactor.Process{
Type: container.Config.Labels[processLabel],
Command: container.Config.Cmd,
Env: parseEnv(container.Config.Env),
Memory: uint(container.HostConfig.Memory),
CPUShares: uint(container.HostConfig.CPUShares),
},
})
}
return instances, nil
}
|
go
|
func (s *Scheduler) instances(ctx context.Context, app string, labels ...string) ([]*twelvefactor.Task, error) {
var instances []*twelvefactor.Task
containers, err := s.docker.ListContainers(docker.ListContainersOptions{
Filters: map[string][]string{
"label": append([]string{
fmt.Sprintf("%s=%s", appLabel, app),
}, labels...),
},
})
if err != nil {
return nil, fmt.Errorf("error listing containers from attached runs: %v", err)
}
for _, apiContainer := range containers {
container, err := s.docker.InspectContainer(apiContainer.ID)
if err != nil {
return instances, fmt.Errorf("error inspecting container %s: %v", apiContainer.ID, err)
}
state := strings.ToUpper(container.State.StateString())
instances = append(instances, &twelvefactor.Task{
ID: container.ID[0:12],
State: state,
UpdatedAt: container.State.StartedAt,
Process: &twelvefactor.Process{
Type: container.Config.Labels[processLabel],
Command: container.Config.Cmd,
Env: parseEnv(container.Config.Env),
Memory: uint(container.HostConfig.Memory),
CPUShares: uint(container.HostConfig.CPUShares),
},
})
}
return instances, nil
}
|
[
"func",
"(",
"s",
"*",
"Scheduler",
")",
"instances",
"(",
"ctx",
"context",
".",
"Context",
",",
"app",
"string",
",",
"labels",
"...",
"string",
")",
"(",
"[",
"]",
"*",
"twelvefactor",
".",
"Task",
",",
"error",
")",
"{",
"var",
"instances",
"[",
"]",
"*",
"twelvefactor",
".",
"Task",
"\n\n",
"containers",
",",
"err",
":=",
"s",
".",
"docker",
".",
"ListContainers",
"(",
"docker",
".",
"ListContainersOptions",
"{",
"Filters",
":",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"\"",
"\"",
":",
"append",
"(",
"[",
"]",
"string",
"{",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"appLabel",
",",
"app",
")",
",",
"}",
",",
"labels",
"...",
")",
",",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"apiContainer",
":=",
"range",
"containers",
"{",
"container",
",",
"err",
":=",
"s",
".",
"docker",
".",
"InspectContainer",
"(",
"apiContainer",
".",
"ID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"instances",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"apiContainer",
".",
"ID",
",",
"err",
")",
"\n",
"}",
"\n\n",
"state",
":=",
"strings",
".",
"ToUpper",
"(",
"container",
".",
"State",
".",
"StateString",
"(",
")",
")",
"\n\n",
"instances",
"=",
"append",
"(",
"instances",
",",
"&",
"twelvefactor",
".",
"Task",
"{",
"ID",
":",
"container",
".",
"ID",
"[",
"0",
":",
"12",
"]",
",",
"State",
":",
"state",
",",
"UpdatedAt",
":",
"container",
".",
"State",
".",
"StartedAt",
",",
"Process",
":",
"&",
"twelvefactor",
".",
"Process",
"{",
"Type",
":",
"container",
".",
"Config",
".",
"Labels",
"[",
"processLabel",
"]",
",",
"Command",
":",
"container",
".",
"Config",
".",
"Cmd",
",",
"Env",
":",
"parseEnv",
"(",
"container",
".",
"Config",
".",
"Env",
")",
",",
"Memory",
":",
"uint",
"(",
"container",
".",
"HostConfig",
".",
"Memory",
")",
",",
"CPUShares",
":",
"uint",
"(",
"container",
".",
"HostConfig",
".",
"CPUShares",
")",
",",
"}",
",",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"instances",
",",
"nil",
"\n",
"}"
] |
// instances returns docker container instances for this app, optionally
// filtered with labels.
|
[
"instances",
"returns",
"docker",
"container",
"instances",
"for",
"this",
"app",
"optionally",
"filtered",
"with",
"labels",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L242-L279
|
train
|
remind101/empire
|
scheduler/docker/docker.go
|
Stop
|
func (s *Scheduler) Stop(ctx context.Context, containerID string) error {
container, err := s.docker.InspectContainer(containerID)
if err != nil {
return err
}
// Some extra protection around stopping containers. We don't want to
// allow users to stop containers that may have been started outside of
// Empire.
if _, ok := container.Config.Labels[runLabel]; !ok {
return &docker.NoSuchContainer{
ID: containerID,
}
}
if err := s.docker.StopContainer(ctx, containerID, stopContainerTimeout); err != nil {
return err
}
return nil
}
|
go
|
func (s *Scheduler) Stop(ctx context.Context, containerID string) error {
container, err := s.docker.InspectContainer(containerID)
if err != nil {
return err
}
// Some extra protection around stopping containers. We don't want to
// allow users to stop containers that may have been started outside of
// Empire.
if _, ok := container.Config.Labels[runLabel]; !ok {
return &docker.NoSuchContainer{
ID: containerID,
}
}
if err := s.docker.StopContainer(ctx, containerID, stopContainerTimeout); err != nil {
return err
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Stop",
"(",
"ctx",
"context",
".",
"Context",
",",
"containerID",
"string",
")",
"error",
"{",
"container",
",",
"err",
":=",
"s",
".",
"docker",
".",
"InspectContainer",
"(",
"containerID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Some extra protection around stopping containers. We don't want to",
"// allow users to stop containers that may have been started outside of",
"// Empire.",
"if",
"_",
",",
"ok",
":=",
"container",
".",
"Config",
".",
"Labels",
"[",
"runLabel",
"]",
";",
"!",
"ok",
"{",
"return",
"&",
"docker",
".",
"NoSuchContainer",
"{",
"ID",
":",
"containerID",
",",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"s",
".",
"docker",
".",
"StopContainer",
"(",
"ctx",
",",
"containerID",
",",
"stopContainerTimeout",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Stop stops the given container.
|
[
"Stop",
"stops",
"the",
"given",
"container",
"."
] |
3daba389f6b07b5d219246bfc7d901fcec664161
|
https://github.com/remind101/empire/blob/3daba389f6b07b5d219246bfc7d901fcec664161/scheduler/docker/docker.go#L282-L302
|
train
|
ory/ladon
|
condition_cidr.go
|
Fulfills
|
func (c *CIDRCondition) Fulfills(value interface{}, _ *Request) bool {
ips, ok := value.(string)
if !ok {
return false
}
_, cidrnet, err := net.ParseCIDR(c.CIDR)
if err != nil {
return false
}
ip := net.ParseIP(ips)
if ip == nil {
return false
}
return cidrnet.Contains(ip)
}
|
go
|
func (c *CIDRCondition) Fulfills(value interface{}, _ *Request) bool {
ips, ok := value.(string)
if !ok {
return false
}
_, cidrnet, err := net.ParseCIDR(c.CIDR)
if err != nil {
return false
}
ip := net.ParseIP(ips)
if ip == nil {
return false
}
return cidrnet.Contains(ip)
}
|
[
"func",
"(",
"c",
"*",
"CIDRCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"ips",
",",
"ok",
":=",
"value",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"_",
",",
"cidrnet",
",",
"err",
":=",
"net",
".",
"ParseCIDR",
"(",
"c",
".",
"CIDR",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"ips",
")",
"\n",
"if",
"ip",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"return",
"cidrnet",
".",
"Contains",
"(",
"ip",
")",
"\n",
"}"
] |
// Fulfills returns true if the the request is fulfilled by the condition.
|
[
"Fulfills",
"returns",
"true",
"if",
"the",
"the",
"request",
"is",
"fulfilled",
"by",
"the",
"condition",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_cidr.go#L33-L50
|
train
|
ory/ladon
|
condition_boolean.go
|
Fulfills
|
func (c *BooleanCondition) Fulfills(value interface{}, _ *Request) bool {
val, ok := value.(bool)
return ok && val == c.BooleanValue
}
|
go
|
func (c *BooleanCondition) Fulfills(value interface{}, _ *Request) bool {
val, ok := value.(bool)
return ok && val == c.BooleanValue
}
|
[
"func",
"(",
"c",
"*",
"BooleanCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"val",
",",
"ok",
":=",
"value",
".",
"(",
"bool",
")",
"\n\n",
"return",
"ok",
"&&",
"val",
"==",
"c",
".",
"BooleanValue",
"\n",
"}"
] |
// Fulfills determines if the BooleanCondition is fulfilled.
// The BooleanCondition is fulfilled if the provided boolean value matches the conditions boolean value.
|
[
"Fulfills",
"determines",
"if",
"the",
"BooleanCondition",
"is",
"fulfilled",
".",
"The",
"BooleanCondition",
"is",
"fulfilled",
"if",
"the",
"provided",
"boolean",
"value",
"matches",
"the",
"conditions",
"boolean",
"value",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_boolean.go#L21-L25
|
train
|
ory/ladon
|
condition_subject_equal.go
|
Fulfills
|
func (c *EqualsSubjectCondition) Fulfills(value interface{}, r *Request) bool {
s, ok := value.(string)
return ok && s == r.Subject
}
|
go
|
func (c *EqualsSubjectCondition) Fulfills(value interface{}, r *Request) bool {
s, ok := value.(string)
return ok && s == r.Subject
}
|
[
"func",
"(",
"c",
"*",
"EqualsSubjectCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"r",
"*",
"Request",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"value",
".",
"(",
"string",
")",
"\n\n",
"return",
"ok",
"&&",
"s",
"==",
"r",
".",
"Subject",
"\n",
"}"
] |
// Fulfills returns true if the request's subject is equal to the given value string
|
[
"Fulfills",
"returns",
"true",
"if",
"the",
"request",
"s",
"subject",
"is",
"equal",
"to",
"the",
"given",
"value",
"string"
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_subject_equal.go#L27-L31
|
train
|
ory/ladon
|
manager/memory/manager_memory.go
|
Update
|
func (m *MemoryManager) Update(policy Policy) error {
m.Lock()
defer m.Unlock()
m.Policies[policy.GetID()] = policy
return nil
}
|
go
|
func (m *MemoryManager) Update(policy Policy) error {
m.Lock()
defer m.Unlock()
m.Policies[policy.GetID()] = policy
return nil
}
|
[
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"Update",
"(",
"policy",
"Policy",
")",
"error",
"{",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"Unlock",
"(",
")",
"\n",
"m",
".",
"Policies",
"[",
"policy",
".",
"GetID",
"(",
")",
"]",
"=",
"policy",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Update updates an existing policy.
|
[
"Update",
"updates",
"an",
"existing",
"policy",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L47-L52
|
train
|
ory/ladon
|
manager/memory/manager_memory.go
|
GetAll
|
func (m *MemoryManager) GetAll(limit, offset int64) (Policies, error) {
keys := make([]string, len(m.Policies))
i := 0
m.RLock()
for key := range m.Policies {
keys[i] = key
i++
}
start, end := pagination.Index(int(limit), int(offset), len(m.Policies))
sort.Strings(keys)
ps := make(Policies, len(keys[start:end]))
i = 0
for _, key := range keys[start:end] {
ps[i] = m.Policies[key]
i++
}
m.RUnlock()
return ps, nil
}
|
go
|
func (m *MemoryManager) GetAll(limit, offset int64) (Policies, error) {
keys := make([]string, len(m.Policies))
i := 0
m.RLock()
for key := range m.Policies {
keys[i] = key
i++
}
start, end := pagination.Index(int(limit), int(offset), len(m.Policies))
sort.Strings(keys)
ps := make(Policies, len(keys[start:end]))
i = 0
for _, key := range keys[start:end] {
ps[i] = m.Policies[key]
i++
}
m.RUnlock()
return ps, nil
}
|
[
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"GetAll",
"(",
"limit",
",",
"offset",
"int64",
")",
"(",
"Policies",
",",
"error",
")",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"m",
".",
"Policies",
")",
")",
"\n",
"i",
":=",
"0",
"\n",
"m",
".",
"RLock",
"(",
")",
"\n",
"for",
"key",
":=",
"range",
"m",
".",
"Policies",
"{",
"keys",
"[",
"i",
"]",
"=",
"key",
"\n",
"i",
"++",
"\n",
"}",
"\n\n",
"start",
",",
"end",
":=",
"pagination",
".",
"Index",
"(",
"int",
"(",
"limit",
")",
",",
"int",
"(",
"offset",
")",
",",
"len",
"(",
"m",
".",
"Policies",
")",
")",
"\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n",
"ps",
":=",
"make",
"(",
"Policies",
",",
"len",
"(",
"keys",
"[",
"start",
":",
"end",
"]",
")",
")",
"\n",
"i",
"=",
"0",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"[",
"start",
":",
"end",
"]",
"{",
"ps",
"[",
"i",
"]",
"=",
"m",
".",
"Policies",
"[",
"key",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"m",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"ps",
",",
"nil",
"\n",
"}"
] |
// GetAll returns all policies.
|
[
"GetAll",
"returns",
"all",
"policies",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L55-L74
|
train
|
ory/ladon
|
manager/memory/manager_memory.go
|
Create
|
func (m *MemoryManager) Create(policy Policy) error {
m.Lock()
defer m.Unlock()
if _, found := m.Policies[policy.GetID()]; found {
return errors.New("Policy exists")
}
m.Policies[policy.GetID()] = policy
return nil
}
|
go
|
func (m *MemoryManager) Create(policy Policy) error {
m.Lock()
defer m.Unlock()
if _, found := m.Policies[policy.GetID()]; found {
return errors.New("Policy exists")
}
m.Policies[policy.GetID()] = policy
return nil
}
|
[
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"Create",
"(",
"policy",
"Policy",
")",
"error",
"{",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"_",
",",
"found",
":=",
"m",
".",
"Policies",
"[",
"policy",
".",
"GetID",
"(",
")",
"]",
";",
"found",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"m",
".",
"Policies",
"[",
"policy",
".",
"GetID",
"(",
")",
"]",
"=",
"policy",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Create a new pollicy to MemoryManager.
|
[
"Create",
"a",
"new",
"pollicy",
"to",
"MemoryManager",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L77-L87
|
train
|
ory/ladon
|
manager/memory/manager_memory.go
|
Get
|
func (m *MemoryManager) Get(id string) (Policy, error) {
m.RLock()
defer m.RUnlock()
p, ok := m.Policies[id]
if !ok {
return nil, errors.New("Not found")
}
return p, nil
}
|
go
|
func (m *MemoryManager) Get(id string) (Policy, error) {
m.RLock()
defer m.RUnlock()
p, ok := m.Policies[id]
if !ok {
return nil, errors.New("Not found")
}
return p, nil
}
|
[
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"Get",
"(",
"id",
"string",
")",
"(",
"Policy",
",",
"error",
")",
"{",
"m",
".",
"RLock",
"(",
")",
"\n",
"defer",
"m",
".",
"RUnlock",
"(",
")",
"\n",
"p",
",",
"ok",
":=",
"m",
".",
"Policies",
"[",
"id",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"p",
",",
"nil",
"\n",
"}"
] |
// Get retrieves a policy.
|
[
"Get",
"retrieves",
"a",
"policy",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L90-L99
|
train
|
ory/ladon
|
manager/memory/manager_memory.go
|
Delete
|
func (m *MemoryManager) Delete(id string) error {
m.Lock()
defer m.Unlock()
delete(m.Policies, id)
return nil
}
|
go
|
func (m *MemoryManager) Delete(id string) error {
m.Lock()
defer m.Unlock()
delete(m.Policies, id)
return nil
}
|
[
"func",
"(",
"m",
"*",
"MemoryManager",
")",
"Delete",
"(",
"id",
"string",
")",
"error",
"{",
"m",
".",
"Lock",
"(",
")",
"\n",
"defer",
"m",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"m",
".",
"Policies",
",",
"id",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Delete removes a policy.
|
[
"Delete",
"removes",
"a",
"policy",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/manager/memory/manager_memory.go#L102-L107
|
train
|
ory/ladon
|
condition_string_pairs_equal.go
|
Fulfills
|
func (c *StringPairsEqualCondition) Fulfills(value interface{}, _ *Request) bool {
pairs, PairsOk := value.([]interface{})
if !PairsOk {
return false
}
for _, v := range pairs {
pair, PairOk := v.([]interface{})
if !PairOk || (len(pair) != 2) {
return false
}
a, AOk := pair[0].(string)
b, BOk := pair[1].(string)
if !AOk || !BOk || (a != b) {
return false
}
}
return true
}
|
go
|
func (c *StringPairsEqualCondition) Fulfills(value interface{}, _ *Request) bool {
pairs, PairsOk := value.([]interface{})
if !PairsOk {
return false
}
for _, v := range pairs {
pair, PairOk := v.([]interface{})
if !PairOk || (len(pair) != 2) {
return false
}
a, AOk := pair[0].(string)
b, BOk := pair[1].(string)
if !AOk || !BOk || (a != b) {
return false
}
}
return true
}
|
[
"func",
"(",
"c",
"*",
"StringPairsEqualCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"pairs",
",",
"PairsOk",
":=",
"value",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"PairsOk",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"v",
":=",
"range",
"pairs",
"{",
"pair",
",",
"PairOk",
":=",
"v",
".",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"PairOk",
"||",
"(",
"len",
"(",
"pair",
")",
"!=",
"2",
")",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"a",
",",
"AOk",
":=",
"pair",
"[",
"0",
"]",
".",
"(",
"string",
")",
"\n",
"b",
",",
"BOk",
":=",
"pair",
"[",
"1",
"]",
".",
"(",
"string",
")",
"\n\n",
"if",
"!",
"AOk",
"||",
"!",
"BOk",
"||",
"(",
"a",
"!=",
"b",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"true",
"\n",
"}"
] |
// Fulfills returns true if the given value is an array of string arrays and
// each string array has exactly two values which are equal
|
[
"Fulfills",
"returns",
"true",
"if",
"the",
"given",
"value",
"is",
"an",
"array",
"of",
"string",
"arrays",
"and",
"each",
"string",
"array",
"has",
"exactly",
"two",
"values",
"which",
"are",
"equal"
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_string_pairs_equal.go#L30-L51
|
train
|
ory/ladon
|
condition_string_match.go
|
Fulfills
|
func (c *StringMatchCondition) Fulfills(value interface{}, _ *Request) bool {
s, ok := value.(string)
matches, _ := regexp.MatchString(c.Matches, s)
return ok && matches
}
|
go
|
func (c *StringMatchCondition) Fulfills(value interface{}, _ *Request) bool {
s, ok := value.(string)
matches, _ := regexp.MatchString(c.Matches, s)
return ok && matches
}
|
[
"func",
"(",
"c",
"*",
"StringMatchCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"value",
".",
"(",
"string",
")",
"\n\n",
"matches",
",",
"_",
":=",
"regexp",
".",
"MatchString",
"(",
"c",
".",
"Matches",
",",
"s",
")",
"\n\n",
"return",
"ok",
"&&",
"matches",
"\n",
"}"
] |
// Fulfills returns true if the given value is a string and matches the regex
// pattern in StringMatchCondition.Matches
|
[
"Fulfills",
"returns",
"true",
"if",
"the",
"given",
"value",
"is",
"a",
"string",
"and",
"matches",
"the",
"regex",
"pattern",
"in",
"StringMatchCondition",
".",
"Matches"
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_string_match.go#L35-L41
|
train
|
ory/ladon
|
ladon.go
|
IsAllowed
|
func (l *Ladon) IsAllowed(r *Request) (err error) {
policies, err := l.Manager.FindRequestCandidates(r)
if err != nil {
return err
}
// Although the manager is responsible of matching the policies, it might decide to just scan for
// subjects, it might return all policies, or it might have a different pattern matching than Golang.
// Thus, we need to make sure that we actually matched the right policies.
return l.DoPoliciesAllow(r, policies)
}
|
go
|
func (l *Ladon) IsAllowed(r *Request) (err error) {
policies, err := l.Manager.FindRequestCandidates(r)
if err != nil {
return err
}
// Although the manager is responsible of matching the policies, it might decide to just scan for
// subjects, it might return all policies, or it might have a different pattern matching than Golang.
// Thus, we need to make sure that we actually matched the right policies.
return l.DoPoliciesAllow(r, policies)
}
|
[
"func",
"(",
"l",
"*",
"Ladon",
")",
"IsAllowed",
"(",
"r",
"*",
"Request",
")",
"(",
"err",
"error",
")",
"{",
"policies",
",",
"err",
":=",
"l",
".",
"Manager",
".",
"FindRequestCandidates",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Although the manager is responsible of matching the policies, it might decide to just scan for",
"// subjects, it might return all policies, or it might have a different pattern matching than Golang.",
"// Thus, we need to make sure that we actually matched the right policies.",
"return",
"l",
".",
"DoPoliciesAllow",
"(",
"r",
",",
"policies",
")",
"\n",
"}"
] |
// IsAllowed returns nil if subject s has permission p on resource r with context c or an error otherwise.
|
[
"IsAllowed",
"returns",
"nil",
"if",
"subject",
"s",
"has",
"permission",
"p",
"on",
"resource",
"r",
"with",
"context",
"c",
"or",
"an",
"error",
"otherwise",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/ladon.go#L49-L59
|
train
|
ory/ladon
|
ladon.go
|
DoPoliciesAllow
|
func (l *Ladon) DoPoliciesAllow(r *Request, policies []Policy) (err error) {
var allowed = false
var deciders = Policies{}
// Iterate through all policies
for _, p := range policies {
// Does the action match with one of the policies?
// This is the first check because usually actions are a superset of get|update|delete|set
// and thus match faster.
if pm, err := l.matcher().Matches(p, p.GetActions(), r.Action); err != nil {
return errors.WithStack(err)
} else if !pm {
// no, continue to next policy
continue
}
// Does the subject match with one of the policies?
// There are usually less subjects than resources which is why this is checked
// before checking for resources.
if sm, err := l.matcher().Matches(p, p.GetSubjects(), r.Subject); err != nil {
return err
} else if !sm {
// no, continue to next policy
continue
}
// Does the resource match with one of the policies?
if rm, err := l.matcher().Matches(p, p.GetResources(), r.Resource); err != nil {
return errors.WithStack(err)
} else if !rm {
// no, continue to next policy
continue
}
// Are the policies conditions met?
// This is checked first because it usually has a small complexity.
if !l.passesConditions(p, r) {
// no, continue to next policy
continue
}
// Is the policies effect deny? If yes, this overrides all allow policies -> access denied.
if !p.AllowAccess() {
deciders = append(deciders, p)
l.auditLogger().LogRejectedAccessRequest(r, policies, deciders)
return errors.WithStack(ErrRequestForcefullyDenied)
}
allowed = true
deciders = append(deciders, p)
}
if !allowed {
l.auditLogger().LogRejectedAccessRequest(r, policies, deciders)
return errors.WithStack(ErrRequestDenied)
}
l.auditLogger().LogGrantedAccessRequest(r, policies, deciders)
return nil
}
|
go
|
func (l *Ladon) DoPoliciesAllow(r *Request, policies []Policy) (err error) {
var allowed = false
var deciders = Policies{}
// Iterate through all policies
for _, p := range policies {
// Does the action match with one of the policies?
// This is the first check because usually actions are a superset of get|update|delete|set
// and thus match faster.
if pm, err := l.matcher().Matches(p, p.GetActions(), r.Action); err != nil {
return errors.WithStack(err)
} else if !pm {
// no, continue to next policy
continue
}
// Does the subject match with one of the policies?
// There are usually less subjects than resources which is why this is checked
// before checking for resources.
if sm, err := l.matcher().Matches(p, p.GetSubjects(), r.Subject); err != nil {
return err
} else if !sm {
// no, continue to next policy
continue
}
// Does the resource match with one of the policies?
if rm, err := l.matcher().Matches(p, p.GetResources(), r.Resource); err != nil {
return errors.WithStack(err)
} else if !rm {
// no, continue to next policy
continue
}
// Are the policies conditions met?
// This is checked first because it usually has a small complexity.
if !l.passesConditions(p, r) {
// no, continue to next policy
continue
}
// Is the policies effect deny? If yes, this overrides all allow policies -> access denied.
if !p.AllowAccess() {
deciders = append(deciders, p)
l.auditLogger().LogRejectedAccessRequest(r, policies, deciders)
return errors.WithStack(ErrRequestForcefullyDenied)
}
allowed = true
deciders = append(deciders, p)
}
if !allowed {
l.auditLogger().LogRejectedAccessRequest(r, policies, deciders)
return errors.WithStack(ErrRequestDenied)
}
l.auditLogger().LogGrantedAccessRequest(r, policies, deciders)
return nil
}
|
[
"func",
"(",
"l",
"*",
"Ladon",
")",
"DoPoliciesAllow",
"(",
"r",
"*",
"Request",
",",
"policies",
"[",
"]",
"Policy",
")",
"(",
"err",
"error",
")",
"{",
"var",
"allowed",
"=",
"false",
"\n",
"var",
"deciders",
"=",
"Policies",
"{",
"}",
"\n\n",
"// Iterate through all policies",
"for",
"_",
",",
"p",
":=",
"range",
"policies",
"{",
"// Does the action match with one of the policies?",
"// This is the first check because usually actions are a superset of get|update|delete|set",
"// and thus match faster.",
"if",
"pm",
",",
"err",
":=",
"l",
".",
"matcher",
"(",
")",
".",
"Matches",
"(",
"p",
",",
"p",
".",
"GetActions",
"(",
")",
",",
"r",
".",
"Action",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"WithStack",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"!",
"pm",
"{",
"// no, continue to next policy",
"continue",
"\n",
"}",
"\n\n",
"// Does the subject match with one of the policies?",
"// There are usually less subjects than resources which is why this is checked",
"// before checking for resources.",
"if",
"sm",
",",
"err",
":=",
"l",
".",
"matcher",
"(",
")",
".",
"Matches",
"(",
"p",
",",
"p",
".",
"GetSubjects",
"(",
")",
",",
"r",
".",
"Subject",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"else",
"if",
"!",
"sm",
"{",
"// no, continue to next policy",
"continue",
"\n",
"}",
"\n\n",
"// Does the resource match with one of the policies?",
"if",
"rm",
",",
"err",
":=",
"l",
".",
"matcher",
"(",
")",
".",
"Matches",
"(",
"p",
",",
"p",
".",
"GetResources",
"(",
")",
",",
"r",
".",
"Resource",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"WithStack",
"(",
"err",
")",
"\n",
"}",
"else",
"if",
"!",
"rm",
"{",
"// no, continue to next policy",
"continue",
"\n",
"}",
"\n\n",
"// Are the policies conditions met?",
"// This is checked first because it usually has a small complexity.",
"if",
"!",
"l",
".",
"passesConditions",
"(",
"p",
",",
"r",
")",
"{",
"// no, continue to next policy",
"continue",
"\n",
"}",
"\n\n",
"// Is the policies effect deny? If yes, this overrides all allow policies -> access denied.",
"if",
"!",
"p",
".",
"AllowAccess",
"(",
")",
"{",
"deciders",
"=",
"append",
"(",
"deciders",
",",
"p",
")",
"\n",
"l",
".",
"auditLogger",
"(",
")",
".",
"LogRejectedAccessRequest",
"(",
"r",
",",
"policies",
",",
"deciders",
")",
"\n",
"return",
"errors",
".",
"WithStack",
"(",
"ErrRequestForcefullyDenied",
")",
"\n",
"}",
"\n\n",
"allowed",
"=",
"true",
"\n",
"deciders",
"=",
"append",
"(",
"deciders",
",",
"p",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"allowed",
"{",
"l",
".",
"auditLogger",
"(",
")",
".",
"LogRejectedAccessRequest",
"(",
"r",
",",
"policies",
",",
"deciders",
")",
"\n",
"return",
"errors",
".",
"WithStack",
"(",
"ErrRequestDenied",
")",
"\n",
"}",
"\n\n",
"l",
".",
"auditLogger",
"(",
")",
".",
"LogGrantedAccessRequest",
"(",
"r",
",",
"policies",
",",
"deciders",
")",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DoPoliciesAllow returns nil if subject s has permission p on resource r with context c for a given policy list or an error otherwise.
// The IsAllowed interface should be preferred since it uses the manager directly. This is a lower level interface for when you don't want to use the ladon manager.
|
[
"DoPoliciesAllow",
"returns",
"nil",
"if",
"subject",
"s",
"has",
"permission",
"p",
"on",
"resource",
"r",
"with",
"context",
"c",
"for",
"a",
"given",
"policy",
"list",
"or",
"an",
"error",
"otherwise",
".",
"The",
"IsAllowed",
"interface",
"should",
"be",
"preferred",
"since",
"it",
"uses",
"the",
"manager",
"directly",
".",
"This",
"is",
"a",
"lower",
"level",
"interface",
"for",
"when",
"you",
"don",
"t",
"want",
"to",
"use",
"the",
"ladon",
"manager",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/ladon.go#L63-L122
|
train
|
ory/ladon
|
condition_resource_contains.go
|
Fulfills
|
func (c *ResourceContainsCondition) Fulfills(value interface{}, r *Request) bool {
filter, ok := value.(map[string]interface{})
if !ok {
return false
}
valueString, ok := filter["value"].(string)
if !ok || len(valueString) < 1 {
return false
}
//If no delimiter provided default to "equals" check
delimiterString, ok := filter["delimiter"].(string)
if !ok || len(delimiterString) < 1 {
delimiterString = ""
}
// Append delimiter to strings to prevent delim+1 being interpreted as delim+10 being present
filterValue := delimiterString + valueString + delimiterString
resourceString := delimiterString + r.Resource + delimiterString
matches := strings.Contains(resourceString, filterValue)
return matches
}
|
go
|
func (c *ResourceContainsCondition) Fulfills(value interface{}, r *Request) bool {
filter, ok := value.(map[string]interface{})
if !ok {
return false
}
valueString, ok := filter["value"].(string)
if !ok || len(valueString) < 1 {
return false
}
//If no delimiter provided default to "equals" check
delimiterString, ok := filter["delimiter"].(string)
if !ok || len(delimiterString) < 1 {
delimiterString = ""
}
// Append delimiter to strings to prevent delim+1 being interpreted as delim+10 being present
filterValue := delimiterString + valueString + delimiterString
resourceString := delimiterString + r.Resource + delimiterString
matches := strings.Contains(resourceString, filterValue)
return matches
}
|
[
"func",
"(",
"c",
"*",
"ResourceContainsCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"r",
"*",
"Request",
")",
"bool",
"{",
"filter",
",",
"ok",
":=",
"value",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"valueString",
",",
"ok",
":=",
"filter",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"valueString",
")",
"<",
"1",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"//If no delimiter provided default to \"equals\" check",
"delimiterString",
",",
"ok",
":=",
"filter",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
"\n",
"if",
"!",
"ok",
"||",
"len",
"(",
"delimiterString",
")",
"<",
"1",
"{",
"delimiterString",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// Append delimiter to strings to prevent delim+1 being interpreted as delim+10 being present",
"filterValue",
":=",
"delimiterString",
"+",
"valueString",
"+",
"delimiterString",
"\n",
"resourceString",
":=",
"delimiterString",
"+",
"r",
".",
"Resource",
"+",
"delimiterString",
"\n\n",
"matches",
":=",
"strings",
".",
"Contains",
"(",
"resourceString",
",",
"filterValue",
")",
"\n",
"return",
"matches",
"\n\n",
"}"
] |
// Fulfills returns true if the request's resouce contains the given value string
|
[
"Fulfills",
"returns",
"true",
"if",
"the",
"request",
"s",
"resouce",
"contains",
"the",
"given",
"value",
"string"
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_resource_contains.go#L29-L54
|
train
|
ory/ladon
|
matcher_regexp.go
|
Matches
|
func (m *RegexpMatcher) Matches(p Policy, haystack []string, needle string) (bool, error) {
var reg *regexp.Regexp
var err error
for _, h := range haystack {
// This means that the current haystack item does not contain a regular expression
if strings.Count(h, string(p.GetStartDelimiter())) == 0 {
// If we have a simple string match, we've got a match!
if h == needle {
return true, nil
}
// Not string match, but also no regexp, continue with next haystack item
continue
}
if reg = m.get(h); reg != nil {
if reg.MatchString(needle) {
return true, nil
}
continue
}
reg, err = compiler.CompileRegex(h, p.GetStartDelimiter(), p.GetEndDelimiter())
if err != nil {
return false, errors.WithStack(err)
}
m.set(h, reg)
if reg.MatchString(needle) {
return true, nil
}
}
return false, nil
}
|
go
|
func (m *RegexpMatcher) Matches(p Policy, haystack []string, needle string) (bool, error) {
var reg *regexp.Regexp
var err error
for _, h := range haystack {
// This means that the current haystack item does not contain a regular expression
if strings.Count(h, string(p.GetStartDelimiter())) == 0 {
// If we have a simple string match, we've got a match!
if h == needle {
return true, nil
}
// Not string match, but also no regexp, continue with next haystack item
continue
}
if reg = m.get(h); reg != nil {
if reg.MatchString(needle) {
return true, nil
}
continue
}
reg, err = compiler.CompileRegex(h, p.GetStartDelimiter(), p.GetEndDelimiter())
if err != nil {
return false, errors.WithStack(err)
}
m.set(h, reg)
if reg.MatchString(needle) {
return true, nil
}
}
return false, nil
}
|
[
"func",
"(",
"m",
"*",
"RegexpMatcher",
")",
"Matches",
"(",
"p",
"Policy",
",",
"haystack",
"[",
"]",
"string",
",",
"needle",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"var",
"reg",
"*",
"regexp",
".",
"Regexp",
"\n",
"var",
"err",
"error",
"\n",
"for",
"_",
",",
"h",
":=",
"range",
"haystack",
"{",
"// This means that the current haystack item does not contain a regular expression",
"if",
"strings",
".",
"Count",
"(",
"h",
",",
"string",
"(",
"p",
".",
"GetStartDelimiter",
"(",
")",
")",
")",
"==",
"0",
"{",
"// If we have a simple string match, we've got a match!",
"if",
"h",
"==",
"needle",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n\n",
"// Not string match, but also no regexp, continue with next haystack item",
"continue",
"\n",
"}",
"\n\n",
"if",
"reg",
"=",
"m",
".",
"get",
"(",
"h",
")",
";",
"reg",
"!=",
"nil",
"{",
"if",
"reg",
".",
"MatchString",
"(",
"needle",
")",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n\n",
"reg",
",",
"err",
"=",
"compiler",
".",
"CompileRegex",
"(",
"h",
",",
"p",
".",
"GetStartDelimiter",
"(",
")",
",",
"p",
".",
"GetEndDelimiter",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"errors",
".",
"WithStack",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"m",
".",
"set",
"(",
"h",
",",
"reg",
")",
"\n",
"if",
"reg",
".",
"MatchString",
"(",
"needle",
")",
"{",
"return",
"true",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] |
// Matches a needle with an array of regular expressions and returns true if a match was found.
|
[
"Matches",
"a",
"needle",
"with",
"an",
"array",
"of",
"regular",
"expressions",
"and",
"returns",
"true",
"if",
"a",
"match",
"was",
"found",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/matcher_regexp.go#L66-L100
|
train
|
ory/ladon
|
condition.go
|
AddCondition
|
func (cs Conditions) AddCondition(key string, c Condition) {
cs[key] = c
}
|
go
|
func (cs Conditions) AddCondition(key string, c Condition) {
cs[key] = c
}
|
[
"func",
"(",
"cs",
"Conditions",
")",
"AddCondition",
"(",
"key",
"string",
",",
"c",
"Condition",
")",
"{",
"cs",
"[",
"key",
"]",
"=",
"c",
"\n",
"}"
] |
// AddCondition adds a condition to the collection.
|
[
"AddCondition",
"adds",
"a",
"condition",
"to",
"the",
"collection",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition.go#L42-L44
|
train
|
ory/ladon
|
condition.go
|
MarshalJSON
|
func (cs Conditions) MarshalJSON() ([]byte, error) {
out := make(map[string]*jsonCondition, len(cs))
for k, c := range cs {
raw, err := json.Marshal(c)
if err != nil {
return []byte{}, errors.WithStack(err)
}
out[k] = &jsonCondition{
Type: c.GetName(),
Options: json.RawMessage(raw),
}
}
return json.Marshal(out)
}
|
go
|
func (cs Conditions) MarshalJSON() ([]byte, error) {
out := make(map[string]*jsonCondition, len(cs))
for k, c := range cs {
raw, err := json.Marshal(c)
if err != nil {
return []byte{}, errors.WithStack(err)
}
out[k] = &jsonCondition{
Type: c.GetName(),
Options: json.RawMessage(raw),
}
}
return json.Marshal(out)
}
|
[
"func",
"(",
"cs",
"Conditions",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"out",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"jsonCondition",
",",
"len",
"(",
"cs",
")",
")",
"\n",
"for",
"k",
",",
"c",
":=",
"range",
"cs",
"{",
"raw",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"[",
"]",
"byte",
"{",
"}",
",",
"errors",
".",
"WithStack",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"out",
"[",
"k",
"]",
"=",
"&",
"jsonCondition",
"{",
"Type",
":",
"c",
".",
"GetName",
"(",
")",
",",
"Options",
":",
"json",
".",
"RawMessage",
"(",
"raw",
")",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"json",
".",
"Marshal",
"(",
"out",
")",
"\n",
"}"
] |
// MarshalJSON marshals a list of conditions to json.
|
[
"MarshalJSON",
"marshals",
"a",
"list",
"of",
"conditions",
"to",
"json",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition.go#L47-L62
|
train
|
ory/ladon
|
condition.go
|
UnmarshalJSON
|
func (cs Conditions) UnmarshalJSON(data []byte) error {
if cs == nil {
return errors.New("Can not be nil")
}
var jcs map[string]jsonCondition
var dc Condition
if err := json.Unmarshal(data, &jcs); err != nil {
return errors.WithStack(err)
}
for k, jc := range jcs {
var found bool
for name, c := range ConditionFactories {
if name == jc.Type {
found = true
dc = c()
if len(jc.Options) == 0 {
cs[k] = dc
break
}
if err := json.Unmarshal(jc.Options, dc); err != nil {
return errors.WithStack(err)
}
cs[k] = dc
break
}
}
if !found {
return errors.Errorf("Could not find condition type %s", jc.Type)
}
}
return nil
}
|
go
|
func (cs Conditions) UnmarshalJSON(data []byte) error {
if cs == nil {
return errors.New("Can not be nil")
}
var jcs map[string]jsonCondition
var dc Condition
if err := json.Unmarshal(data, &jcs); err != nil {
return errors.WithStack(err)
}
for k, jc := range jcs {
var found bool
for name, c := range ConditionFactories {
if name == jc.Type {
found = true
dc = c()
if len(jc.Options) == 0 {
cs[k] = dc
break
}
if err := json.Unmarshal(jc.Options, dc); err != nil {
return errors.WithStack(err)
}
cs[k] = dc
break
}
}
if !found {
return errors.Errorf("Could not find condition type %s", jc.Type)
}
}
return nil
}
|
[
"func",
"(",
"cs",
"Conditions",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"if",
"cs",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"jcs",
"map",
"[",
"string",
"]",
"jsonCondition",
"\n",
"var",
"dc",
"Condition",
"\n\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"jcs",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"WithStack",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"k",
",",
"jc",
":=",
"range",
"jcs",
"{",
"var",
"found",
"bool",
"\n",
"for",
"name",
",",
"c",
":=",
"range",
"ConditionFactories",
"{",
"if",
"name",
"==",
"jc",
".",
"Type",
"{",
"found",
"=",
"true",
"\n",
"dc",
"=",
"c",
"(",
")",
"\n\n",
"if",
"len",
"(",
"jc",
".",
"Options",
")",
"==",
"0",
"{",
"cs",
"[",
"k",
"]",
"=",
"dc",
"\n",
"break",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"jc",
".",
"Options",
",",
"dc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"WithStack",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"cs",
"[",
"k",
"]",
"=",
"dc",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"!",
"found",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"jc",
".",
"Type",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalJSON unmarshals a list of conditions from json.
|
[
"UnmarshalJSON",
"unmarshals",
"a",
"list",
"of",
"conditions",
"from",
"json",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition.go#L65-L104
|
train
|
ory/ladon
|
condition_string_equal.go
|
Fulfills
|
func (c *StringEqualCondition) Fulfills(value interface{}, _ *Request) bool {
s, ok := value.(string)
return ok && s == c.Equals
}
|
go
|
func (c *StringEqualCondition) Fulfills(value interface{}, _ *Request) bool {
s, ok := value.(string)
return ok && s == c.Equals
}
|
[
"func",
"(",
"c",
"*",
"StringEqualCondition",
")",
"Fulfills",
"(",
"value",
"interface",
"{",
"}",
",",
"_",
"*",
"Request",
")",
"bool",
"{",
"s",
",",
"ok",
":=",
"value",
".",
"(",
"string",
")",
"\n\n",
"return",
"ok",
"&&",
"s",
"==",
"c",
".",
"Equals",
"\n",
"}"
] |
// Fulfills returns true if the given value is a string and is the
// same as in StringEqualCondition.Equals
|
[
"Fulfills",
"returns",
"true",
"if",
"the",
"given",
"value",
"is",
"a",
"string",
"and",
"is",
"the",
"same",
"as",
"in",
"StringEqualCondition",
".",
"Equals"
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/condition_string_equal.go#L31-L35
|
train
|
ory/ladon
|
compiler/regex.go
|
delimiterIndices
|
func delimiterIndices(s string, delimiterStart, delimiterEnd byte) ([]int, error) {
var level, idx int
idxs := make([]int, 0)
for i := 0; i < len(s); i++ {
switch s[i] {
case delimiterStart:
if level++; level == 1 {
idx = i
}
case delimiterEnd:
if level--; level == 0 {
idxs = append(idxs, idx, i+1)
} else if level < 0 {
return nil, fmt.Errorf(`Unbalanced braces in "%q"`, s)
}
}
}
if level != 0 {
return nil, fmt.Errorf(`Unbalanced braces in "%q"`, s)
}
return idxs, nil
}
|
go
|
func delimiterIndices(s string, delimiterStart, delimiterEnd byte) ([]int, error) {
var level, idx int
idxs := make([]int, 0)
for i := 0; i < len(s); i++ {
switch s[i] {
case delimiterStart:
if level++; level == 1 {
idx = i
}
case delimiterEnd:
if level--; level == 0 {
idxs = append(idxs, idx, i+1)
} else if level < 0 {
return nil, fmt.Errorf(`Unbalanced braces in "%q"`, s)
}
}
}
if level != 0 {
return nil, fmt.Errorf(`Unbalanced braces in "%q"`, s)
}
return idxs, nil
}
|
[
"func",
"delimiterIndices",
"(",
"s",
"string",
",",
"delimiterStart",
",",
"delimiterEnd",
"byte",
")",
"(",
"[",
"]",
"int",
",",
"error",
")",
"{",
"var",
"level",
",",
"idx",
"int",
"\n",
"idxs",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"0",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"s",
")",
";",
"i",
"++",
"{",
"switch",
"s",
"[",
"i",
"]",
"{",
"case",
"delimiterStart",
":",
"if",
"level",
"++",
";",
"level",
"==",
"1",
"{",
"idx",
"=",
"i",
"\n",
"}",
"\n",
"case",
"delimiterEnd",
":",
"if",
"level",
"--",
";",
"level",
"==",
"0",
"{",
"idxs",
"=",
"append",
"(",
"idxs",
",",
"idx",
",",
"i",
"+",
"1",
")",
"\n",
"}",
"else",
"if",
"level",
"<",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"`Unbalanced braces in \"%q\"`",
",",
"s",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"level",
"!=",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"`Unbalanced braces in \"%q\"`",
",",
"s",
")",
"\n",
"}",
"\n\n",
"return",
"idxs",
",",
"nil",
"\n",
"}"
] |
// delimiterIndices returns the first level delimiter indices from a string.
// It returns an error in case of unbalanced delimiters.
|
[
"delimiterIndices",
"returns",
"the",
"first",
"level",
"delimiter",
"indices",
"from",
"a",
"string",
".",
"It",
"returns",
"an",
"error",
"in",
"case",
"of",
"unbalanced",
"delimiters",
"."
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/compiler/regex.go#L75-L98
|
train
|
ory/ladon
|
policy.go
|
UnmarshalJSON
|
func (p *DefaultPolicy) UnmarshalJSON(data []byte) error {
var pol = struct {
ID string `json:"id" gorethink:"id"`
Description string `json:"description" gorethink:"description"`
Subjects []string `json:"subjects" gorethink:"subjects"`
Effect string `json:"effect" gorethink:"effect"`
Resources []string `json:"resources" gorethink:"resources"`
Actions []string `json:"actions" gorethink:"actions"`
Conditions Conditions `json:"conditions" gorethink:"conditions"`
Meta []byte `json:"meta" gorethink:"meta"`
}{
Conditions: Conditions{},
}
if err := json.Unmarshal(data, &pol); err != nil {
return errors.WithStack(err)
}
*p = *&DefaultPolicy{
ID: pol.ID,
Description: pol.Description,
Subjects: pol.Subjects,
Effect: pol.Effect,
Resources: pol.Resources,
Actions: pol.Actions,
Conditions: pol.Conditions,
Meta: pol.Meta,
}
return nil
}
|
go
|
func (p *DefaultPolicy) UnmarshalJSON(data []byte) error {
var pol = struct {
ID string `json:"id" gorethink:"id"`
Description string `json:"description" gorethink:"description"`
Subjects []string `json:"subjects" gorethink:"subjects"`
Effect string `json:"effect" gorethink:"effect"`
Resources []string `json:"resources" gorethink:"resources"`
Actions []string `json:"actions" gorethink:"actions"`
Conditions Conditions `json:"conditions" gorethink:"conditions"`
Meta []byte `json:"meta" gorethink:"meta"`
}{
Conditions: Conditions{},
}
if err := json.Unmarshal(data, &pol); err != nil {
return errors.WithStack(err)
}
*p = *&DefaultPolicy{
ID: pol.ID,
Description: pol.Description,
Subjects: pol.Subjects,
Effect: pol.Effect,
Resources: pol.Resources,
Actions: pol.Actions,
Conditions: pol.Conditions,
Meta: pol.Meta,
}
return nil
}
|
[
"func",
"(",
"p",
"*",
"DefaultPolicy",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"pol",
"=",
"struct",
"{",
"ID",
"string",
"`json:\"id\" gorethink:\"id\"`",
"\n",
"Description",
"string",
"`json:\"description\" gorethink:\"description\"`",
"\n",
"Subjects",
"[",
"]",
"string",
"`json:\"subjects\" gorethink:\"subjects\"`",
"\n",
"Effect",
"string",
"`json:\"effect\" gorethink:\"effect\"`",
"\n",
"Resources",
"[",
"]",
"string",
"`json:\"resources\" gorethink:\"resources\"`",
"\n",
"Actions",
"[",
"]",
"string",
"`json:\"actions\" gorethink:\"actions\"`",
"\n",
"Conditions",
"Conditions",
"`json:\"conditions\" gorethink:\"conditions\"`",
"\n",
"Meta",
"[",
"]",
"byte",
"`json:\"meta\" gorethink:\"meta\"`",
"\n",
"}",
"{",
"Conditions",
":",
"Conditions",
"{",
"}",
",",
"}",
"\n\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"pol",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"WithStack",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"*",
"p",
"=",
"*",
"&",
"DefaultPolicy",
"{",
"ID",
":",
"pol",
".",
"ID",
",",
"Description",
":",
"pol",
".",
"Description",
",",
"Subjects",
":",
"pol",
".",
"Subjects",
",",
"Effect",
":",
"pol",
".",
"Effect",
",",
"Resources",
":",
"pol",
".",
"Resources",
",",
"Actions",
":",
"pol",
".",
"Actions",
",",
"Conditions",
":",
"pol",
".",
"Conditions",
",",
"Meta",
":",
"pol",
".",
"Meta",
",",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// UnmarshalJSON overwrite own policy with values of the given in policy in JSON format
|
[
"UnmarshalJSON",
"overwrite",
"own",
"policy",
"with",
"values",
"of",
"the",
"given",
"in",
"policy",
"in",
"JSON",
"format"
] |
7f1c376a9a46cd4e09f90d3940e81cd963b0d87d
|
https://github.com/ory/ladon/blob/7f1c376a9a46cd4e09f90d3940e81cd963b0d87d/policy.go#L81-L110
|
train
|
sajari/docconv
|
tidy.go
|
Tidy
|
func Tidy(r io.Reader, xmlIn bool) ([]byte, error) {
f, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
return nil, err
}
defer os.Remove(f.Name())
io.Copy(f, r)
var output []byte
if xmlIn {
output, err = exec.Command("tidy", "-xml", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
} else {
output, err = exec.Command("tidy", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
}
if err != nil && err.Error() != "exit status 1" {
return nil, err
}
return output, nil
}
|
go
|
func Tidy(r io.Reader, xmlIn bool) ([]byte, error) {
f, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
return nil, err
}
defer os.Remove(f.Name())
io.Copy(f, r)
var output []byte
if xmlIn {
output, err = exec.Command("tidy", "-xml", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
} else {
output, err = exec.Command("tidy", "-numeric", "-asxml", "-quiet", "-utf8", f.Name()).Output()
}
if err != nil && err.Error() != "exit status 1" {
return nil, err
}
return output, nil
}
|
[
"func",
"Tidy",
"(",
"r",
"io",
".",
"Reader",
",",
"xmlIn",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"os",
".",
"Remove",
"(",
"f",
".",
"Name",
"(",
")",
")",
"\n",
"io",
".",
"Copy",
"(",
"f",
",",
"r",
")",
"\n\n",
"var",
"output",
"[",
"]",
"byte",
"\n",
"if",
"xmlIn",
"{",
"output",
",",
"err",
"=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"f",
".",
"Name",
"(",
")",
")",
".",
"Output",
"(",
")",
"\n",
"}",
"else",
"{",
"output",
",",
"err",
"=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"f",
".",
"Name",
"(",
")",
")",
".",
"Output",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
".",
"Error",
"(",
")",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"output",
",",
"nil",
"\n",
"}"
] |
// Tidy attempts to tidy up XML.
// Errors & warnings are deliberately suppressed as underlying tools
// throw warnings very easily.
|
[
"Tidy",
"attempts",
"to",
"tidy",
"up",
"XML",
".",
"Errors",
"&",
"warnings",
"are",
"deliberately",
"suppressed",
"as",
"underlying",
"tools",
"throw",
"warnings",
"very",
"easily",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/tidy.go#L13-L32
|
train
|
sajari/docconv
|
local.go
|
Done
|
func (l *LocalFile) Done() {
l.Close()
if l.unlink {
os.Remove(l.Name())
}
}
|
go
|
func (l *LocalFile) Done() {
l.Close()
if l.unlink {
os.Remove(l.Name())
}
}
|
[
"func",
"(",
"l",
"*",
"LocalFile",
")",
"Done",
"(",
")",
"{",
"l",
".",
"Close",
"(",
")",
"\n",
"if",
"l",
".",
"unlink",
"{",
"os",
".",
"Remove",
"(",
"l",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Done cleans up all resources.
|
[
"Done",
"cleans",
"up",
"all",
"resources",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/local.go#L46-L51
|
train
|
sajari/docconv
|
odt.go
|
ConvertODT
|
func ConvertODT(r io.Reader) (string, map[string]string, error) {
meta := make(map[string]string)
var textBody string
b, err := ioutil.ReadAll(r)
if err != nil {
return "", nil, err
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return "", nil, fmt.Errorf("error unzipping data: %v", err)
}
for _, f := range zr.File {
switch f.Name {
case "meta.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error extracting '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
info, err := XMLToMap(rc)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
if tmp, ok := info["creator"]; ok {
meta["Author"] = tmp
}
if tmp, ok := info["date"]; ok {
if t, err := time.Parse("2006-01-02T15:04:05", tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := info["creation-date"]; ok {
if t, err := time.Parse("2006-01-02T15:04:05", tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
case "content.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error extracting '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
textBody, err = XMLToText(rc, []string{"br", "p", "tab"}, []string{}, true)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
}
}
return textBody, meta, nil
}
|
go
|
func ConvertODT(r io.Reader) (string, map[string]string, error) {
meta := make(map[string]string)
var textBody string
b, err := ioutil.ReadAll(r)
if err != nil {
return "", nil, err
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return "", nil, fmt.Errorf("error unzipping data: %v", err)
}
for _, f := range zr.File {
switch f.Name {
case "meta.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error extracting '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
info, err := XMLToMap(rc)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
if tmp, ok := info["creator"]; ok {
meta["Author"] = tmp
}
if tmp, ok := info["date"]; ok {
if t, err := time.Parse("2006-01-02T15:04:05", tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := info["creation-date"]; ok {
if t, err := time.Parse("2006-01-02T15:04:05", tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
case "content.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error extracting '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
textBody, err = XMLToText(rc, []string{"br", "p", "tab"}, []string{}, true)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
}
}
return textBody, meta, nil
}
|
[
"func",
"ConvertODT",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"meta",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"var",
"textBody",
"string",
"\n\n",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"zr",
",",
"err",
":=",
"zip",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"int64",
"(",
"len",
"(",
"b",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"zr",
".",
"File",
"{",
"switch",
"f",
".",
"Name",
"{",
"case",
"\"",
"\"",
":",
"rc",
",",
"err",
":=",
"f",
".",
"Open",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n\n",
"info",
",",
"err",
":=",
"XMLToMap",
"(",
"rc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"tmp",
",",
"ok",
":=",
"info",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"tmp",
"\n",
"}",
"\n",
"if",
"tmp",
",",
"ok",
":=",
"info",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"tmp",
")",
";",
"err",
"==",
"nil",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Unix",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"tmp",
",",
"ok",
":=",
"info",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"tmp",
")",
";",
"err",
"==",
"nil",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Unix",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"case",
"\"",
"\"",
":",
"rc",
",",
"err",
":=",
"f",
".",
"Open",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n\n",
"textBody",
",",
"err",
"=",
"XMLToText",
"(",
"rc",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"[",
"]",
"string",
"{",
"}",
",",
"true",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"textBody",
",",
"meta",
",",
"nil",
"\n",
"}"
] |
// ConvertODT converts a ODT file to text
|
[
"ConvertODT",
"converts",
"a",
"ODT",
"file",
"to",
"text"
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/odt.go#L13-L69
|
train
|
sajari/docconv
|
snappy/decode.go
|
DecodedLen
|
func DecodedLen(src []byte) (int, error) {
v, _, err := decodedLen(src)
return v, err
}
|
go
|
func DecodedLen(src []byte) (int, error) {
v, _, err := decodedLen(src)
return v, err
}
|
[
"func",
"DecodedLen",
"(",
"src",
"[",
"]",
"byte",
")",
"(",
"int",
",",
"error",
")",
"{",
"v",
",",
"_",
",",
"err",
":=",
"decodedLen",
"(",
"src",
")",
"\n",
"return",
"v",
",",
"err",
"\n",
"}"
] |
// DecodedLen returns the length of the decoded block.
|
[
"DecodedLen",
"returns",
"the",
"length",
"of",
"the",
"decoded",
"block",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/snappy/decode.go#L21-L24
|
train
|
sajari/docconv
|
snappy/decode.go
|
Reset
|
func (r *Reader) Reset(reader io.Reader) {
r.r = reader
r.err = nil
r.i = 0
r.j = 0
r.readHeader = false
}
|
go
|
func (r *Reader) Reset(reader io.Reader) {
r.r = reader
r.err = nil
r.i = 0
r.j = 0
r.readHeader = false
}
|
[
"func",
"(",
"r",
"*",
"Reader",
")",
"Reset",
"(",
"reader",
"io",
".",
"Reader",
")",
"{",
"r",
".",
"r",
"=",
"reader",
"\n",
"r",
".",
"err",
"=",
"nil",
"\n",
"r",
".",
"i",
"=",
"0",
"\n",
"r",
".",
"j",
"=",
"0",
"\n",
"r",
".",
"readHeader",
"=",
"false",
"\n",
"}"
] |
// Reset discards any buffered data, resets all state, and switches the Snappy
// reader to read from r. This permits reusing a Reader rather than allocating
// a new one.
|
[
"Reset",
"discards",
"any",
"buffered",
"data",
"resets",
"all",
"state",
"and",
"switches",
"the",
"Snappy",
"reader",
"to",
"read",
"from",
"r",
".",
"This",
"permits",
"reusing",
"a",
"Reader",
"rather",
"than",
"allocating",
"a",
"new",
"one",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/snappy/decode.go#L156-L162
|
train
|
sajari/docconv
|
url.go
|
ConvertURL
|
func ConvertURL(input io.Reader, readability bool) (string, map[string]string, error) {
meta := make(map[string]string)
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(input)
if err != nil {
return "", nil, err
}
g := goose.New()
article, err := g.ExtractFromURL(buf.String())
if err != nil {
return "", nil, err
}
meta["title"] = article.Title
meta["description"] = article.MetaDescription
meta["image"] = article.TopImage
return article.CleanedText, meta, nil
}
|
go
|
func ConvertURL(input io.Reader, readability bool) (string, map[string]string, error) {
meta := make(map[string]string)
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(input)
if err != nil {
return "", nil, err
}
g := goose.New()
article, err := g.ExtractFromURL(buf.String())
if err != nil {
return "", nil, err
}
meta["title"] = article.Title
meta["description"] = article.MetaDescription
meta["image"] = article.TopImage
return article.CleanedText, meta, nil
}
|
[
"func",
"ConvertURL",
"(",
"input",
"io",
".",
"Reader",
",",
"readability",
"bool",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"meta",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"_",
",",
"err",
":=",
"buf",
".",
"ReadFrom",
"(",
"input",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"g",
":=",
"goose",
".",
"New",
"(",
")",
"\n",
"article",
",",
"err",
":=",
"g",
".",
"ExtractFromURL",
"(",
"buf",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"article",
".",
"Title",
"\n",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"article",
".",
"MetaDescription",
"\n",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"article",
".",
"TopImage",
"\n\n",
"return",
"article",
".",
"CleanedText",
",",
"meta",
",",
"nil",
"\n",
"}"
] |
// ConvertURL fetches the HTML page at the URL given in the io.Reader.
|
[
"ConvertURL",
"fetches",
"the",
"HTML",
"page",
"at",
"the",
"URL",
"given",
"in",
"the",
"io",
".",
"Reader",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/url.go#L11-L31
|
train
|
sajari/docconv
|
rtf.go
|
ConvertRTF
|
func ConvertRTF(r io.Reader) (string, map[string]string, error) {
f, err := NewLocalFile(r, "/tmp", "sajari-convert-")
if err != nil {
return "", nil, fmt.Errorf("error creating local file: %v", err)
}
defer f.Done()
var output string
tmpOutput, err := exec.Command("unrtf", "--nopict", "--text", f.Name()).Output()
if err != nil {
return "", nil, fmt.Errorf("unrtf error: %v", err)
}
// Step through content looking for meta data and stripping out comments
meta := make(map[string]string)
for _, line := range strings.Split(string(tmpOutput), "\n") {
if parts := strings.SplitN(line, ":", 2); len(parts) > 1 {
meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
if len(line) > 4 && line[:4] != "### " {
output += line + "\n"
}
}
// Identify meta data
if tmp, ok := meta["AUTHOR"]; ok {
meta["Author"] = tmp
}
if tmp, ok := meta["### creation date"]; ok {
if t, err := time.Parse("02 January 2006 15:04", tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := meta["### revision date"]; ok {
if t, err := time.Parse("02 January 2006 15:04", tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
return output, meta, nil
}
|
go
|
func ConvertRTF(r io.Reader) (string, map[string]string, error) {
f, err := NewLocalFile(r, "/tmp", "sajari-convert-")
if err != nil {
return "", nil, fmt.Errorf("error creating local file: %v", err)
}
defer f.Done()
var output string
tmpOutput, err := exec.Command("unrtf", "--nopict", "--text", f.Name()).Output()
if err != nil {
return "", nil, fmt.Errorf("unrtf error: %v", err)
}
// Step through content looking for meta data and stripping out comments
meta := make(map[string]string)
for _, line := range strings.Split(string(tmpOutput), "\n") {
if parts := strings.SplitN(line, ":", 2); len(parts) > 1 {
meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
if len(line) > 4 && line[:4] != "### " {
output += line + "\n"
}
}
// Identify meta data
if tmp, ok := meta["AUTHOR"]; ok {
meta["Author"] = tmp
}
if tmp, ok := meta["### creation date"]; ok {
if t, err := time.Parse("02 January 2006 15:04", tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := meta["### revision date"]; ok {
if t, err := time.Parse("02 January 2006 15:04", tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
return output, meta, nil
}
|
[
"func",
"ConvertRTF",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"NewLocalFile",
"(",
"r",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Done",
"(",
")",
"\n\n",
"var",
"output",
"string",
"\n",
"tmpOutput",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"f",
".",
"Name",
"(",
")",
")",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Step through content looking for meta data and stripping out comments",
"meta",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"line",
":=",
"range",
"strings",
".",
"Split",
"(",
"string",
"(",
"tmpOutput",
")",
",",
"\"",
"\\n",
"\"",
")",
"{",
"if",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"line",
",",
"\"",
"\"",
",",
"2",
")",
";",
"len",
"(",
"parts",
")",
">",
"1",
"{",
"meta",
"[",
"strings",
".",
"TrimSpace",
"(",
"parts",
"[",
"0",
"]",
")",
"]",
"=",
"strings",
".",
"TrimSpace",
"(",
"parts",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"line",
")",
">",
"4",
"&&",
"line",
"[",
":",
"4",
"]",
"!=",
"\"",
"\"",
"{",
"output",
"+=",
"line",
"+",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Identify meta data",
"if",
"tmp",
",",
"ok",
":=",
"meta",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"tmp",
"\n",
"}",
"\n",
"if",
"tmp",
",",
"ok",
":=",
"meta",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"tmp",
")",
";",
"err",
"==",
"nil",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Unix",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"tmp",
",",
"ok",
":=",
"meta",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"\"",
"\"",
",",
"tmp",
")",
";",
"err",
"==",
"nil",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Unix",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"output",
",",
"meta",
",",
"nil",
"\n",
"}"
] |
// ConvertRTF converts RTF files to text.
|
[
"ConvertRTF",
"converts",
"RTF",
"files",
"to",
"text",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/rtf.go#L12-L52
|
train
|
sajari/docconv
|
docx.go
|
ConvertDocx
|
func ConvertDocx(r io.Reader) (string, map[string]string, error) {
meta := make(map[string]string)
var textHeader, textBody, textFooter string
b, err := ioutil.ReadAll(r)
if err != nil {
return "", nil, err
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return "", nil, fmt.Errorf("error unzipping data: %v", err)
}
// Regular expression for XML files to include in the text parsing
reHeaderFile, _ := regexp.Compile("^word/header[0-9]+.xml$")
reFooterFile, _ := regexp.Compile("^word/footer[0-9]+.xml$")
for _, f := range zr.File {
switch {
case f.Name == "docProps/core.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error opening '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
meta, err = XMLToMap(rc)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
if tmp, ok := meta["modified"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := meta["created"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
case f.Name == "word/document.xml":
textBody, err = parseDocxText(f)
if err != nil {
return "", nil, err
}
case reHeaderFile.MatchString(f.Name):
header, err := parseDocxText(f)
if err != nil {
return "", nil, err
}
textHeader += header + "\n"
case reFooterFile.MatchString(f.Name):
footer, err := parseDocxText(f)
if err != nil {
return "", nil, err
}
textFooter += footer + "\n"
}
}
return textHeader + "\n" + textBody + "\n" + textFooter, meta, nil
}
|
go
|
func ConvertDocx(r io.Reader) (string, map[string]string, error) {
meta := make(map[string]string)
var textHeader, textBody, textFooter string
b, err := ioutil.ReadAll(r)
if err != nil {
return "", nil, err
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return "", nil, fmt.Errorf("error unzipping data: %v", err)
}
// Regular expression for XML files to include in the text parsing
reHeaderFile, _ := regexp.Compile("^word/header[0-9]+.xml$")
reFooterFile, _ := regexp.Compile("^word/footer[0-9]+.xml$")
for _, f := range zr.File {
switch {
case f.Name == "docProps/core.xml":
rc, err := f.Open()
if err != nil {
return "", nil, fmt.Errorf("error opening '%v' from archive: %v", f.Name, err)
}
defer rc.Close()
meta, err = XMLToMap(rc)
if err != nil {
return "", nil, fmt.Errorf("error parsing '%v': %v", f.Name, err)
}
if tmp, ok := meta["modified"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := meta["created"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
case f.Name == "word/document.xml":
textBody, err = parseDocxText(f)
if err != nil {
return "", nil, err
}
case reHeaderFile.MatchString(f.Name):
header, err := parseDocxText(f)
if err != nil {
return "", nil, err
}
textHeader += header + "\n"
case reFooterFile.MatchString(f.Name):
footer, err := parseDocxText(f)
if err != nil {
return "", nil, err
}
textFooter += footer + "\n"
}
}
return textHeader + "\n" + textBody + "\n" + textFooter, meta, nil
}
|
[
"func",
"ConvertDocx",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"meta",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"var",
"textHeader",
",",
"textBody",
",",
"textFooter",
"string",
"\n\n",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"zr",
",",
"err",
":=",
"zip",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"int64",
"(",
"len",
"(",
"b",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Regular expression for XML files to include in the text parsing",
"reHeaderFile",
",",
"_",
":=",
"regexp",
".",
"Compile",
"(",
"\"",
"\"",
")",
"\n",
"reFooterFile",
",",
"_",
":=",
"regexp",
".",
"Compile",
"(",
"\"",
"\"",
")",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"zr",
".",
"File",
"{",
"switch",
"{",
"case",
"f",
".",
"Name",
"==",
"\"",
"\"",
":",
"rc",
",",
"err",
":=",
"f",
".",
"Open",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n\n",
"meta",
",",
"err",
"=",
"XMLToMap",
"(",
"rc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"tmp",
",",
"ok",
":=",
"meta",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"tmp",
")",
";",
"err",
"==",
"nil",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Unix",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"tmp",
",",
"ok",
":=",
"meta",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"tmp",
")",
";",
"err",
"==",
"nil",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Unix",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"case",
"f",
".",
"Name",
"==",
"\"",
"\"",
":",
"textBody",
",",
"err",
"=",
"parseDocxText",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"case",
"reHeaderFile",
".",
"MatchString",
"(",
"f",
".",
"Name",
")",
":",
"header",
",",
"err",
":=",
"parseDocxText",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"textHeader",
"+=",
"header",
"+",
"\"",
"\\n",
"\"",
"\n\n",
"case",
"reFooterFile",
".",
"MatchString",
"(",
"f",
".",
"Name",
")",
":",
"footer",
",",
"err",
":=",
"parseDocxText",
"(",
"f",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"textFooter",
"+=",
"footer",
"+",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"textHeader",
"+",
"\"",
"\\n",
"\"",
"+",
"textBody",
"+",
"\"",
"\\n",
"\"",
"+",
"textFooter",
",",
"meta",
",",
"nil",
"\n",
"}"
] |
// ConvertDocx converts an MS Word docx file to text.
|
[
"ConvertDocx",
"converts",
"an",
"MS",
"Word",
"docx",
"file",
"to",
"text",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docx.go#L14-L79
|
train
|
sajari/docconv
|
docx.go
|
DocxXMLToText
|
func DocxXMLToText(r io.Reader) (string, error) {
return XMLToText(r, []string{"br", "p", "tab"}, []string{"instrText", "script"}, true)
}
|
go
|
func DocxXMLToText(r io.Reader) (string, error) {
return XMLToText(r, []string{"br", "p", "tab"}, []string{"instrText", "script"}, true)
}
|
[
"func",
"DocxXMLToText",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"XMLToText",
"(",
"r",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"true",
")",
"\n",
"}"
] |
// DocxXMLToText converts Docx XML into plain text.
|
[
"DocxXMLToText",
"converts",
"Docx",
"XML",
"into",
"plain",
"text",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docx.go#L96-L98
|
train
|
sajari/docconv
|
html.go
|
ConvertHTML
|
func ConvertHTML(r io.Reader, readability bool) (string, map[string]string, error) {
meta := make(map[string]string)
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(r)
if err != nil {
return "", nil, err
}
cleanXML, err := Tidy(buf, false)
if err != nil {
log.Println("Tidy:", err)
// Tidy failed, so we now manually tokenize instead
clean := cleanHTML(buf, true)
cleanXML = []byte(clean)
// TODO: remove this log
log.Println("Cleaned HTML using Golang tokenizer")
}
if readability {
cleanXML = HTMLReadability(bytes.NewReader(cleanXML))
}
return HTMLToText(bytes.NewReader(cleanXML)), meta, nil
}
|
go
|
func ConvertHTML(r io.Reader, readability bool) (string, map[string]string, error) {
meta := make(map[string]string)
buf := new(bytes.Buffer)
_, err := buf.ReadFrom(r)
if err != nil {
return "", nil, err
}
cleanXML, err := Tidy(buf, false)
if err != nil {
log.Println("Tidy:", err)
// Tidy failed, so we now manually tokenize instead
clean := cleanHTML(buf, true)
cleanXML = []byte(clean)
// TODO: remove this log
log.Println("Cleaned HTML using Golang tokenizer")
}
if readability {
cleanXML = HTMLReadability(bytes.NewReader(cleanXML))
}
return HTMLToText(bytes.NewReader(cleanXML)), meta, nil
}
|
[
"func",
"ConvertHTML",
"(",
"r",
"io",
".",
"Reader",
",",
"readability",
"bool",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"meta",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n\n",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n",
"_",
",",
"err",
":=",
"buf",
".",
"ReadFrom",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"cleanXML",
",",
"err",
":=",
"Tidy",
"(",
"buf",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"// Tidy failed, so we now manually tokenize instead",
"clean",
":=",
"cleanHTML",
"(",
"buf",
",",
"true",
")",
"\n",
"cleanXML",
"=",
"[",
"]",
"byte",
"(",
"clean",
")",
"\n",
"// TODO: remove this log",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"readability",
"{",
"cleanXML",
"=",
"HTMLReadability",
"(",
"bytes",
".",
"NewReader",
"(",
"cleanXML",
")",
")",
"\n",
"}",
"\n",
"return",
"HTMLToText",
"(",
"bytes",
".",
"NewReader",
"(",
"cleanXML",
")",
")",
",",
"meta",
",",
"nil",
"\n",
"}"
] |
// ConvertHTML converts HTML into text.
|
[
"ConvertHTML",
"converts",
"HTML",
"into",
"text",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/html.go#L17-L40
|
train
|
sajari/docconv
|
html.go
|
acceptedHTMLTag
|
func acceptedHTMLTag(tagName string) bool {
for _, tag := range acceptedHTMLTags {
if tag == tagName {
return true
}
}
return false
}
|
go
|
func acceptedHTMLTag(tagName string) bool {
for _, tag := range acceptedHTMLTags {
if tag == tagName {
return true
}
}
return false
}
|
[
"func",
"acceptedHTMLTag",
"(",
"tagName",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"tag",
":=",
"range",
"acceptedHTMLTags",
"{",
"if",
"tag",
"==",
"tagName",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Tests for known friendly HTML parameters that tidy is unlikely to choke on
|
[
"Tests",
"for",
"known",
"friendly",
"HTML",
"parameters",
"that",
"tidy",
"is",
"unlikely",
"to",
"choke",
"on"
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/html.go#L50-L57
|
train
|
sajari/docconv
|
html.go
|
HTMLReadability
|
func HTMLReadability(r io.Reader) []byte {
jr := justext.NewReader(r)
// TODO: Improve this!
jr.Stoplist = readabilityStopList
jr.LengthLow = HTMLReadabilityOptionsValues.LengthLow
jr.LengthHigh = HTMLReadabilityOptionsValues.LengthHigh
jr.StopwordsLow = HTMLReadabilityOptionsValues.StopwordsLow
jr.StopwordsHigh = HTMLReadabilityOptionsValues.StopwordsHigh
jr.MaxLinkDensity = HTMLReadabilityOptionsValues.MaxLinkDensity
jr.MaxHeadingDistance = HTMLReadabilityOptionsValues.MaxHeadingDistance
paragraphSet, err := jr.ReadAll()
if err != nil {
log.Println("Justext:", err)
return nil
}
useClasses := strings.SplitN(HTMLReadabilityOptionsValues.ReadabilityUseClasses, ",", 10)
output := ""
for _, paragraph := range paragraphSet {
for _, class := range useClasses {
if paragraph.CfClass == class {
output += paragraph.Text + "\n"
}
}
}
return []byte(output)
}
|
go
|
func HTMLReadability(r io.Reader) []byte {
jr := justext.NewReader(r)
// TODO: Improve this!
jr.Stoplist = readabilityStopList
jr.LengthLow = HTMLReadabilityOptionsValues.LengthLow
jr.LengthHigh = HTMLReadabilityOptionsValues.LengthHigh
jr.StopwordsLow = HTMLReadabilityOptionsValues.StopwordsLow
jr.StopwordsHigh = HTMLReadabilityOptionsValues.StopwordsHigh
jr.MaxLinkDensity = HTMLReadabilityOptionsValues.MaxLinkDensity
jr.MaxHeadingDistance = HTMLReadabilityOptionsValues.MaxHeadingDistance
paragraphSet, err := jr.ReadAll()
if err != nil {
log.Println("Justext:", err)
return nil
}
useClasses := strings.SplitN(HTMLReadabilityOptionsValues.ReadabilityUseClasses, ",", 10)
output := ""
for _, paragraph := range paragraphSet {
for _, class := range useClasses {
if paragraph.CfClass == class {
output += paragraph.Text + "\n"
}
}
}
return []byte(output)
}
|
[
"func",
"HTMLReadability",
"(",
"r",
"io",
".",
"Reader",
")",
"[",
"]",
"byte",
"{",
"jr",
":=",
"justext",
".",
"NewReader",
"(",
"r",
")",
"\n\n",
"// TODO: Improve this!",
"jr",
".",
"Stoplist",
"=",
"readabilityStopList",
"\n",
"jr",
".",
"LengthLow",
"=",
"HTMLReadabilityOptionsValues",
".",
"LengthLow",
"\n",
"jr",
".",
"LengthHigh",
"=",
"HTMLReadabilityOptionsValues",
".",
"LengthHigh",
"\n",
"jr",
".",
"StopwordsLow",
"=",
"HTMLReadabilityOptionsValues",
".",
"StopwordsLow",
"\n",
"jr",
".",
"StopwordsHigh",
"=",
"HTMLReadabilityOptionsValues",
".",
"StopwordsHigh",
"\n",
"jr",
".",
"MaxLinkDensity",
"=",
"HTMLReadabilityOptionsValues",
".",
"MaxLinkDensity",
"\n",
"jr",
".",
"MaxHeadingDistance",
"=",
"HTMLReadabilityOptionsValues",
".",
"MaxHeadingDistance",
"\n\n",
"paragraphSet",
",",
"err",
":=",
"jr",
".",
"ReadAll",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"useClasses",
":=",
"strings",
".",
"SplitN",
"(",
"HTMLReadabilityOptionsValues",
".",
"ReadabilityUseClasses",
",",
"\"",
"\"",
",",
"10",
")",
"\n\n",
"output",
":=",
"\"",
"\"",
"\n",
"for",
"_",
",",
"paragraph",
":=",
"range",
"paragraphSet",
"{",
"for",
"_",
",",
"class",
":=",
"range",
"useClasses",
"{",
"if",
"paragraph",
".",
"CfClass",
"==",
"class",
"{",
"output",
"+=",
"paragraph",
".",
"Text",
"+",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"[",
"]",
"byte",
"(",
"output",
")",
"\n",
"}"
] |
// HTMLReadability extracts the readable text in an HTML document
|
[
"HTMLReadability",
"extracts",
"the",
"readable",
"text",
"in",
"an",
"HTML",
"document"
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/html.go#L130-L160
|
train
|
sajari/docconv
|
html.go
|
HTMLToText
|
func HTMLToText(input io.Reader) string {
text, _ := XMLToText(input, []string{"br", "p", "h1", "h2", "h3", "h4"}, []string{}, false)
return text
}
|
go
|
func HTMLToText(input io.Reader) string {
text, _ := XMLToText(input, []string{"br", "p", "h1", "h2", "h3", "h4"}, []string{}, false)
return text
}
|
[
"func",
"HTMLToText",
"(",
"input",
"io",
".",
"Reader",
")",
"string",
"{",
"text",
",",
"_",
":=",
"XMLToText",
"(",
"input",
",",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"[",
"]",
"string",
"{",
"}",
",",
"false",
")",
"\n",
"return",
"text",
"\n",
"}"
] |
// HTMLToText converts HTML to plain text.
|
[
"HTMLToText",
"converts",
"HTML",
"to",
"plain",
"text",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/html.go#L163-L166
|
train
|
sajari/docconv
|
docconv.go
|
Convert
|
func Convert(r io.Reader, mimeType string, readability bool) (*Response, error) {
start := time.Now()
var body string
var meta map[string]string
var err error
switch mimeType {
case "application/msword", "application/vnd.ms-word":
body, meta, err = ConvertDoc(r)
case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
body, meta, err = ConvertDocx(r)
case "application/vnd.oasis.opendocument.text":
body, meta, err = ConvertODT(r)
case "application/vnd.apple.pages", "application/x-iwork-pages-sffpages":
body, meta, err = ConvertPages(r)
case "application/pdf":
body, meta, err = ConvertPDF(r)
case "application/rtf", "application/x-rtf", "text/rtf", "text/richtext":
body, meta, err = ConvertRTF(r)
case "text/html":
body, meta, err = ConvertHTML(r, readability)
case "text/url":
body, meta, err = ConvertURL(r, readability)
case "text/xml", "application/xml":
body, meta, err = ConvertXML(r)
case "image/jpeg", "image/png", "image/tif", "image/tiff":
body, meta, err = ConvertImage(r)
case "text/plain":
var b []byte
b, err = ioutil.ReadAll(r)
body = string(b)
}
if err != nil {
return nil, fmt.Errorf("error converting data: %v", err)
}
return &Response{
Body: strings.TrimSpace(body),
Meta: meta,
MSecs: uint32(time.Since(start) / time.Millisecond),
}, nil
}
|
go
|
func Convert(r io.Reader, mimeType string, readability bool) (*Response, error) {
start := time.Now()
var body string
var meta map[string]string
var err error
switch mimeType {
case "application/msword", "application/vnd.ms-word":
body, meta, err = ConvertDoc(r)
case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
body, meta, err = ConvertDocx(r)
case "application/vnd.oasis.opendocument.text":
body, meta, err = ConvertODT(r)
case "application/vnd.apple.pages", "application/x-iwork-pages-sffpages":
body, meta, err = ConvertPages(r)
case "application/pdf":
body, meta, err = ConvertPDF(r)
case "application/rtf", "application/x-rtf", "text/rtf", "text/richtext":
body, meta, err = ConvertRTF(r)
case "text/html":
body, meta, err = ConvertHTML(r, readability)
case "text/url":
body, meta, err = ConvertURL(r, readability)
case "text/xml", "application/xml":
body, meta, err = ConvertXML(r)
case "image/jpeg", "image/png", "image/tif", "image/tiff":
body, meta, err = ConvertImage(r)
case "text/plain":
var b []byte
b, err = ioutil.ReadAll(r)
body = string(b)
}
if err != nil {
return nil, fmt.Errorf("error converting data: %v", err)
}
return &Response{
Body: strings.TrimSpace(body),
Meta: meta,
MSecs: uint32(time.Since(start) / time.Millisecond),
}, nil
}
|
[
"func",
"Convert",
"(",
"r",
"io",
".",
"Reader",
",",
"mimeType",
"string",
",",
"readability",
"bool",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"start",
":=",
"time",
".",
"Now",
"(",
")",
"\n\n",
"var",
"body",
"string",
"\n",
"var",
"meta",
"map",
"[",
"string",
"]",
"string",
"\n",
"var",
"err",
"error",
"\n",
"switch",
"mimeType",
"{",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertDoc",
"(",
"r",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertDocx",
"(",
"r",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertODT",
"(",
"r",
")",
"\n\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertPages",
"(",
"r",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertPDF",
"(",
"r",
")",
"\n\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertRTF",
"(",
"r",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertHTML",
"(",
"r",
",",
"readability",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertURL",
"(",
"r",
",",
"readability",
")",
"\n\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertXML",
"(",
"r",
")",
"\n\n",
"case",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
":",
"body",
",",
"meta",
",",
"err",
"=",
"ConvertImage",
"(",
"r",
")",
"\n\n",
"case",
"\"",
"\"",
":",
"var",
"b",
"[",
"]",
"byte",
"\n",
"b",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"body",
"=",
"string",
"(",
"b",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"return",
"&",
"Response",
"{",
"Body",
":",
"strings",
".",
"TrimSpace",
"(",
"body",
")",
",",
"Meta",
":",
"meta",
",",
"MSecs",
":",
"uint32",
"(",
"time",
".",
"Since",
"(",
"start",
")",
"/",
"time",
".",
"Millisecond",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// Convert a file to plain text.
|
[
"Convert",
"a",
"file",
"to",
"plain",
"text",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docconv.go#L57-L109
|
train
|
sajari/docconv
|
docconv.go
|
ConvertPath
|
func ConvertPath(path string) (*Response, error) {
mimeType := MimeTypeByExtension(path)
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return Convert(f, mimeType, true)
}
|
go
|
func ConvertPath(path string) (*Response, error) {
mimeType := MimeTypeByExtension(path)
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return Convert(f, mimeType, true)
}
|
[
"func",
"ConvertPath",
"(",
"path",
"string",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"mimeType",
":=",
"MimeTypeByExtension",
"(",
"path",
")",
"\n\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"return",
"Convert",
"(",
"f",
",",
"mimeType",
",",
"true",
")",
"\n",
"}"
] |
// ConvertPath converts a local path to text.
|
[
"ConvertPath",
"converts",
"a",
"local",
"path",
"to",
"text",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docconv.go#L112-L122
|
train
|
sajari/docconv
|
docconv.go
|
ConvertPathReadability
|
func ConvertPathReadability(path string, readability bool) ([]byte, error) {
mimeType := MimeTypeByExtension(path)
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
data, err := Convert(f, mimeType, readability)
if err != nil {
return nil, err
}
return json.Marshal(data)
}
|
go
|
func ConvertPathReadability(path string, readability bool) ([]byte, error) {
mimeType := MimeTypeByExtension(path)
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
data, err := Convert(f, mimeType, readability)
if err != nil {
return nil, err
}
return json.Marshal(data)
}
|
[
"func",
"ConvertPathReadability",
"(",
"path",
"string",
",",
"readability",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"mimeType",
":=",
"MimeTypeByExtension",
"(",
"path",
")",
"\n\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"data",
",",
"err",
":=",
"Convert",
"(",
"f",
",",
"mimeType",
",",
"readability",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"data",
")",
"\n",
"}"
] |
// ConvertPathReadability converts a local path to text, with the given readability
// option.
|
[
"ConvertPathReadability",
"converts",
"a",
"local",
"path",
"to",
"text",
"with",
"the",
"given",
"readability",
"option",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docconv.go#L126-L140
|
train
|
sajari/docconv
|
client/client.go
|
New
|
func New(opts ...Opt) *Client {
c := &Client{
endpoint: DefaultEndpoint,
protocol: DefaultProtocol,
httpClient: DefaultHTTPClient,
}
for _, opt := range opts {
opt(c)
}
return c
}
|
go
|
func New(opts ...Opt) *Client {
c := &Client{
endpoint: DefaultEndpoint,
protocol: DefaultProtocol,
httpClient: DefaultHTTPClient,
}
for _, opt := range opts {
opt(c)
}
return c
}
|
[
"func",
"New",
"(",
"opts",
"...",
"Opt",
")",
"*",
"Client",
"{",
"c",
":=",
"&",
"Client",
"{",
"endpoint",
":",
"DefaultEndpoint",
",",
"protocol",
":",
"DefaultProtocol",
",",
"httpClient",
":",
"DefaultHTTPClient",
",",
"}",
"\n\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"c",
")",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] |
// New creates a new docconv client for interacting with a docconv HTTP
// server.
|
[
"New",
"creates",
"a",
"new",
"docconv",
"client",
"for",
"interacting",
"with",
"a",
"docconv",
"HTTP",
"server",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/client/client.go#L55-L66
|
train
|
sajari/docconv
|
client/client.go
|
Convert
|
func (c *Client) Convert(r io.Reader, filename string) (*Response, error) {
buf := &bytes.Buffer{}
w := multipart.NewWriter(buf)
part, err := w.CreateFormFile("input", filename)
if err != nil {
return nil, err
}
if _, err := io.Copy(part, r); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%v%v/convert", c.protocol, c.endpoint), buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", w.FormDataContentType())
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
res := &Response{}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return nil, err
}
return res, nil
}
|
go
|
func (c *Client) Convert(r io.Reader, filename string) (*Response, error) {
buf := &bytes.Buffer{}
w := multipart.NewWriter(buf)
part, err := w.CreateFormFile("input", filename)
if err != nil {
return nil, err
}
if _, err := io.Copy(part, r); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
req, err := http.NewRequest("POST", fmt.Sprintf("%v%v/convert", c.protocol, c.endpoint), buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", w.FormDataContentType())
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
res := &Response{}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return nil, err
}
return res, nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"Convert",
"(",
"r",
"io",
".",
"Reader",
",",
"filename",
"string",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"buf",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"w",
":=",
"multipart",
".",
"NewWriter",
"(",
"buf",
")",
"\n",
"part",
",",
"err",
":=",
"w",
".",
"CreateFormFile",
"(",
"\"",
"\"",
",",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"part",
",",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"w",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"c",
".",
"protocol",
",",
"c",
".",
"endpoint",
")",
",",
"buf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"w",
".",
"FormDataContentType",
"(",
")",
")",
"\n\n",
"resp",
",",
"err",
":=",
"c",
".",
"httpClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"res",
":=",
"&",
"Response",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"resp",
".",
"Body",
")",
".",
"Decode",
"(",
"&",
"res",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"res",
",",
"nil",
"\n",
"}"
] |
// Convert a file from a local path using the http client
|
[
"Convert",
"a",
"file",
"from",
"a",
"local",
"path",
"using",
"the",
"http",
"client"
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/client/client.go#L85-L116
|
train
|
sajari/docconv
|
client/client.go
|
ConvertPath
|
func ConvertPath(c *Client, path string) (*Response, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return c.Convert(f, f.Name())
}
|
go
|
func ConvertPath(c *Client, path string) (*Response, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return c.Convert(f, f.Name())
}
|
[
"func",
"ConvertPath",
"(",
"c",
"*",
"Client",
",",
"path",
"string",
")",
"(",
"*",
"Response",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"return",
"c",
".",
"Convert",
"(",
"f",
",",
"f",
".",
"Name",
"(",
")",
")",
"\n",
"}"
] |
// ConvertPath uses the docconv Client to convert the local file
// found at path.
|
[
"ConvertPath",
"uses",
"the",
"docconv",
"Client",
"to",
"convert",
"the",
"local",
"file",
"found",
"at",
"path",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/client/client.go#L120-L128
|
train
|
sajari/docconv
|
doc.go
|
ConvertDoc
|
func ConvertDoc(r io.Reader) (string, map[string]string, error) {
f, err := NewLocalFile(r, "/tmp", "sajari-convert-")
if err != nil {
return "", nil, fmt.Errorf("error creating local file: %v", err)
}
defer f.Done()
// Meta data
mc := make(chan map[string]string, 1)
go func() {
meta := make(map[string]string)
metaStr, err := exec.Command("wvSummary", f.Name()).Output()
if err != nil {
// TODO: Remove this.
log.Println("wvSummary:", err)
}
// Parse meta output
for _, line := range strings.Split(string(metaStr), "\n") {
if parts := strings.SplitN(line, "=", 2); len(parts) > 1 {
meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
}
// Convert parsed meta
if tmp, ok := meta["Last Modified"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := meta["Created"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
mc <- meta
}()
// Document body
bc := make(chan string, 1)
go func() {
// Save output to a file
outputFile, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
// TODO: Remove this.
log.Println("TempFile Out:", err)
return
}
defer os.Remove(outputFile.Name())
err = exec.Command("wvText", f.Name(), outputFile.Name()).Run()
if err != nil {
// TODO: Remove this.
log.Println("wvText:", err)
}
var buf bytes.Buffer
_, err = buf.ReadFrom(outputFile)
if err != nil {
// TODO: Remove this.
log.Println("wvText:", err)
}
bc <- buf.String()
}()
// TODO: Should errors in either of the above Goroutines stop things from progressing?
body := <-bc
meta := <-mc
// TODO: Check for errors instead of len(body) == 0?
if len(body) == 0 {
f.Seek(0, 0)
return ConvertDocx(f)
}
return body, meta, nil
}
|
go
|
func ConvertDoc(r io.Reader) (string, map[string]string, error) {
f, err := NewLocalFile(r, "/tmp", "sajari-convert-")
if err != nil {
return "", nil, fmt.Errorf("error creating local file: %v", err)
}
defer f.Done()
// Meta data
mc := make(chan map[string]string, 1)
go func() {
meta := make(map[string]string)
metaStr, err := exec.Command("wvSummary", f.Name()).Output()
if err != nil {
// TODO: Remove this.
log.Println("wvSummary:", err)
}
// Parse meta output
for _, line := range strings.Split(string(metaStr), "\n") {
if parts := strings.SplitN(line, "=", 2); len(parts) > 1 {
meta[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
}
}
// Convert parsed meta
if tmp, ok := meta["Last Modified"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["ModifiedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
if tmp, ok := meta["Created"]; ok {
if t, err := time.Parse(time.RFC3339, tmp); err == nil {
meta["CreatedDate"] = fmt.Sprintf("%d", t.Unix())
}
}
mc <- meta
}()
// Document body
bc := make(chan string, 1)
go func() {
// Save output to a file
outputFile, err := ioutil.TempFile("/tmp", "sajari-convert-")
if err != nil {
// TODO: Remove this.
log.Println("TempFile Out:", err)
return
}
defer os.Remove(outputFile.Name())
err = exec.Command("wvText", f.Name(), outputFile.Name()).Run()
if err != nil {
// TODO: Remove this.
log.Println("wvText:", err)
}
var buf bytes.Buffer
_, err = buf.ReadFrom(outputFile)
if err != nil {
// TODO: Remove this.
log.Println("wvText:", err)
}
bc <- buf.String()
}()
// TODO: Should errors in either of the above Goroutines stop things from progressing?
body := <-bc
meta := <-mc
// TODO: Check for errors instead of len(body) == 0?
if len(body) == 0 {
f.Seek(0, 0)
return ConvertDocx(f)
}
return body, meta, nil
}
|
[
"func",
"ConvertDoc",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"NewLocalFile",
"(",
"r",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Done",
"(",
")",
"\n\n",
"// Meta data",
"mc",
":=",
"make",
"(",
"chan",
"map",
"[",
"string",
"]",
"string",
",",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"meta",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"metaStr",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
"(",
")",
")",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// TODO: Remove this.",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"// Parse meta output",
"for",
"_",
",",
"line",
":=",
"range",
"strings",
".",
"Split",
"(",
"string",
"(",
"metaStr",
")",
",",
"\"",
"\\n",
"\"",
")",
"{",
"if",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"line",
",",
"\"",
"\"",
",",
"2",
")",
";",
"len",
"(",
"parts",
")",
">",
"1",
"{",
"meta",
"[",
"strings",
".",
"TrimSpace",
"(",
"parts",
"[",
"0",
"]",
")",
"]",
"=",
"strings",
".",
"TrimSpace",
"(",
"parts",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Convert parsed meta",
"if",
"tmp",
",",
"ok",
":=",
"meta",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"tmp",
")",
";",
"err",
"==",
"nil",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Unix",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"tmp",
",",
"ok",
":=",
"meta",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"tmp",
")",
";",
"err",
"==",
"nil",
"{",
"meta",
"[",
"\"",
"\"",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"t",
".",
"Unix",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"mc",
"<-",
"meta",
"\n",
"}",
"(",
")",
"\n\n",
"// Document body",
"bc",
":=",
"make",
"(",
"chan",
"string",
",",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"// Save output to a file",
"outputFile",
",",
"err",
":=",
"ioutil",
".",
"TempFile",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// TODO: Remove this.",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"os",
".",
"Remove",
"(",
"outputFile",
".",
"Name",
"(",
")",
")",
"\n\n",
"err",
"=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"f",
".",
"Name",
"(",
")",
",",
"outputFile",
".",
"Name",
"(",
")",
")",
".",
"Run",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// TODO: Remove this.",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"_",
",",
"err",
"=",
"buf",
".",
"ReadFrom",
"(",
"outputFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// TODO: Remove this.",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"bc",
"<-",
"buf",
".",
"String",
"(",
")",
"\n",
"}",
"(",
")",
"\n\n",
"// TODO: Should errors in either of the above Goroutines stop things from progressing?",
"body",
":=",
"<-",
"bc",
"\n",
"meta",
":=",
"<-",
"mc",
"\n\n",
"// TODO: Check for errors instead of len(body) == 0?",
"if",
"len",
"(",
"body",
")",
"==",
"0",
"{",
"f",
".",
"Seek",
"(",
"0",
",",
"0",
")",
"\n",
"return",
"ConvertDocx",
"(",
"f",
")",
"\n",
"}",
"\n",
"return",
"body",
",",
"meta",
",",
"nil",
"\n",
"}"
] |
// ConvertDoc converts an MS Word .doc to text.
|
[
"ConvertDoc",
"converts",
"an",
"MS",
"Word",
".",
"doc",
"to",
"text",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/doc.go#L16-L94
|
train
|
sajari/docconv
|
image_ocr.go
|
ConvertImage
|
func ConvertImage(r io.Reader) (string, map[string]string, error) {
f, err := NewLocalFile(r, "/tmp", "sajari-convert-")
if err != nil {
return "", nil, fmt.Errorf("error creating local file: %v", err)
}
defer f.Done()
meta := make(map[string]string)
out := make(chan string, 1)
// TODO: Why is this done in a separate goroutine when ConvertImage blocks until it returns?
go func(file *LocalFile) {
langs.RLock()
body := gosseract.Must(gosseract.Params{Src: file.Name(), Languages: langs.lang})
langs.RUnlock()
out <- string(body)
}(f)
return <-out, meta, nil
}
|
go
|
func ConvertImage(r io.Reader) (string, map[string]string, error) {
f, err := NewLocalFile(r, "/tmp", "sajari-convert-")
if err != nil {
return "", nil, fmt.Errorf("error creating local file: %v", err)
}
defer f.Done()
meta := make(map[string]string)
out := make(chan string, 1)
// TODO: Why is this done in a separate goroutine when ConvertImage blocks until it returns?
go func(file *LocalFile) {
langs.RLock()
body := gosseract.Must(gosseract.Params{Src: file.Name(), Languages: langs.lang})
langs.RUnlock()
out <- string(body)
}(f)
return <-out, meta, nil
}
|
[
"func",
"ConvertImage",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"NewLocalFile",
"(",
"r",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Done",
"(",
")",
"\n\n",
"meta",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"out",
":=",
"make",
"(",
"chan",
"string",
",",
"1",
")",
"\n\n",
"// TODO: Why is this done in a separate goroutine when ConvertImage blocks until it returns?",
"go",
"func",
"(",
"file",
"*",
"LocalFile",
")",
"{",
"langs",
".",
"RLock",
"(",
")",
"\n",
"body",
":=",
"gosseract",
".",
"Must",
"(",
"gosseract",
".",
"Params",
"{",
"Src",
":",
"file",
".",
"Name",
"(",
")",
",",
"Languages",
":",
"langs",
".",
"lang",
"}",
")",
"\n",
"langs",
".",
"RUnlock",
"(",
")",
"\n",
"out",
"<-",
"string",
"(",
"body",
")",
"\n",
"}",
"(",
"f",
")",
"\n\n",
"return",
"<-",
"out",
",",
"meta",
",",
"nil",
"\n",
"}"
] |
// ConvertImage converts images to text.
// Requires gosseract.
|
[
"ConvertImage",
"converts",
"images",
"to",
"text",
".",
"Requires",
"gosseract",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/image_ocr.go#L20-L39
|
train
|
sajari/docconv
|
image_ocr.go
|
SetImageLanguages
|
func SetImageLanguages(l string) {
langs.Lock()
langs.lang = l
langs.Unlock()
}
|
go
|
func SetImageLanguages(l string) {
langs.Lock()
langs.lang = l
langs.Unlock()
}
|
[
"func",
"SetImageLanguages",
"(",
"l",
"string",
")",
"{",
"langs",
".",
"Lock",
"(",
")",
"\n",
"langs",
".",
"lang",
"=",
"l",
"\n",
"langs",
".",
"Unlock",
"(",
")",
"\n",
"}"
] |
// SetImageLanguages sets the languages parameter passed to gosseract.
|
[
"SetImageLanguages",
"sets",
"the",
"languages",
"parameter",
"passed",
"to",
"gosseract",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/image_ocr.go#L42-L46
|
train
|
sajari/docconv
|
pages.go
|
ConvertPages
|
func ConvertPages(r io.Reader) (string, map[string]string, error) {
meta := make(map[string]string)
var textBody string
b, err := ioutil.ReadAll(r)
if err != nil {
return "", nil, fmt.Errorf("error reading data: %v", err)
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return "", nil, fmt.Errorf("error unzipping data: %v", err)
}
for _, f := range zr.File {
if strings.HasSuffix(f.Name, "Preview.pdf") {
// There is a preview PDF version we can use
if rc, err := f.Open(); err == nil {
return ConvertPDF(rc)
}
}
if f.Name == "index.xml" {
// There's an XML version we can use
if rc, err := f.Open(); err == nil {
return ConvertXML(rc)
}
}
if f.Name == "Index/Document.iwa" {
rc, _ := f.Open()
defer rc.Close()
bReader := bufio.NewReader(snappy.NewReader(io.MultiReader(strings.NewReader("\xff\x06\x00\x00sNaPpY"), rc)))
archiveLength, err := binary.ReadVarint(bReader)
archiveInfoData, err := ioutil.ReadAll(io.LimitReader(bReader, archiveLength))
archiveInfo := &TSP.ArchiveInfo{}
err = proto.Unmarshal(archiveInfoData, archiveInfo)
fmt.Println("archiveInfo:", archiveInfo, err)
}
}
return textBody, meta, nil
}
|
go
|
func ConvertPages(r io.Reader) (string, map[string]string, error) {
meta := make(map[string]string)
var textBody string
b, err := ioutil.ReadAll(r)
if err != nil {
return "", nil, fmt.Errorf("error reading data: %v", err)
}
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
return "", nil, fmt.Errorf("error unzipping data: %v", err)
}
for _, f := range zr.File {
if strings.HasSuffix(f.Name, "Preview.pdf") {
// There is a preview PDF version we can use
if rc, err := f.Open(); err == nil {
return ConvertPDF(rc)
}
}
if f.Name == "index.xml" {
// There's an XML version we can use
if rc, err := f.Open(); err == nil {
return ConvertXML(rc)
}
}
if f.Name == "Index/Document.iwa" {
rc, _ := f.Open()
defer rc.Close()
bReader := bufio.NewReader(snappy.NewReader(io.MultiReader(strings.NewReader("\xff\x06\x00\x00sNaPpY"), rc)))
archiveLength, err := binary.ReadVarint(bReader)
archiveInfoData, err := ioutil.ReadAll(io.LimitReader(bReader, archiveLength))
archiveInfo := &TSP.ArchiveInfo{}
err = proto.Unmarshal(archiveInfoData, archiveInfo)
fmt.Println("archiveInfo:", archiveInfo, err)
}
}
return textBody, meta, nil
}
|
[
"func",
"ConvertPages",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"meta",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"var",
"textBody",
"string",
"\n\n",
"b",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"zr",
",",
"err",
":=",
"zip",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"b",
")",
",",
"int64",
"(",
"len",
"(",
"b",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"f",
":=",
"range",
"zr",
".",
"File",
"{",
"if",
"strings",
".",
"HasSuffix",
"(",
"f",
".",
"Name",
",",
"\"",
"\"",
")",
"{",
"// There is a preview PDF version we can use",
"if",
"rc",
",",
"err",
":=",
"f",
".",
"Open",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"ConvertPDF",
"(",
"rc",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"f",
".",
"Name",
"==",
"\"",
"\"",
"{",
"// There's an XML version we can use",
"if",
"rc",
",",
"err",
":=",
"f",
".",
"Open",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"return",
"ConvertXML",
"(",
"rc",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"f",
".",
"Name",
"==",
"\"",
"\"",
"{",
"rc",
",",
"_",
":=",
"f",
".",
"Open",
"(",
")",
"\n",
"defer",
"rc",
".",
"Close",
"(",
")",
"\n",
"bReader",
":=",
"bufio",
".",
"NewReader",
"(",
"snappy",
".",
"NewReader",
"(",
"io",
".",
"MultiReader",
"(",
"strings",
".",
"NewReader",
"(",
"\"",
"\\xff",
"\\x06",
"\\x00",
"\\x00",
"\"",
")",
",",
"rc",
")",
")",
")",
"\n",
"archiveLength",
",",
"err",
":=",
"binary",
".",
"ReadVarint",
"(",
"bReader",
")",
"\n",
"archiveInfoData",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"io",
".",
"LimitReader",
"(",
"bReader",
",",
"archiveLength",
")",
")",
"\n",
"archiveInfo",
":=",
"&",
"TSP",
".",
"ArchiveInfo",
"{",
"}",
"\n",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"archiveInfoData",
",",
"archiveInfo",
")",
"\n",
"fmt",
".",
"Println",
"(",
"\"",
"\"",
",",
"archiveInfo",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"textBody",
",",
"meta",
",",
"nil",
"\n",
"}"
] |
// ConvertPages converts a Pages file to text.
|
[
"ConvertPages",
"converts",
"a",
"Pages",
"file",
"to",
"text",
"."
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/pages.go#L20-L60
|
train
|
sajari/docconv
|
docd/main.go
|
convertPath
|
func convertPath(path string, readability bool) ([]byte, error) {
mimeType := docconv.MimeTypeByExtension(path)
if *logLevel >= 1 {
log.Println("Converting file: " + path + " (" + mimeType + ")")
}
// Open file
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
data, err := docconv.Convert(f, mimeType, readability)
if err != nil {
return nil, err
}
b, err := json.Marshal(data)
if err != nil {
return nil, err
}
if *logLevel >= 2 {
log.Println(string(b))
}
return b, nil
}
|
go
|
func convertPath(path string, readability bool) ([]byte, error) {
mimeType := docconv.MimeTypeByExtension(path)
if *logLevel >= 1 {
log.Println("Converting file: " + path + " (" + mimeType + ")")
}
// Open file
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
data, err := docconv.Convert(f, mimeType, readability)
if err != nil {
return nil, err
}
b, err := json.Marshal(data)
if err != nil {
return nil, err
}
if *logLevel >= 2 {
log.Println(string(b))
}
return b, nil
}
|
[
"func",
"convertPath",
"(",
"path",
"string",
",",
"readability",
"bool",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"mimeType",
":=",
"docconv",
".",
"MimeTypeByExtension",
"(",
"path",
")",
"\n",
"if",
"*",
"logLevel",
">=",
"1",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
"+",
"path",
"+",
"\"",
"\"",
"+",
"mimeType",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Open file",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"data",
",",
"err",
":=",
"docconv",
".",
"Convert",
"(",
"f",
",",
"mimeType",
",",
"readability",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"*",
"logLevel",
">=",
"2",
"{",
"log",
".",
"Println",
"(",
"string",
"(",
"b",
")",
")",
"\n",
"}",
"\n",
"return",
"b",
",",
"nil",
"\n",
"}"
] |
// Convert a file given a path
|
[
"Convert",
"a",
"file",
"given",
"a",
"path"
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docd/main.go#L53-L78
|
train
|
sajari/docconv
|
docd/main.go
|
serve
|
func serve() {
http.HandleFunc("/convert", func(w http.ResponseWriter, r *http.Request) {
// Readability flag. Currently only used for HTML
var readability bool
if r.FormValue("readability") == "1" {
readability = true
if *logLevel >= 2 {
log.Println("Readability is on")
}
}
path := r.FormValue("path")
if path != "" {
b, err := docconv.ConvertPathReadability(path, readability)
if err != nil {
// TODO: return a sensible status code for errors like this.
log.Printf("error converting path '%v': %v", path, err)
return
}
w.Write(b)
return
}
// Get uploaded file
file, info, err := r.FormFile("input")
if err != nil {
log.Println("File upload", err)
return
}
defer file.Close()
// Abort if file doesn't have a mime type
if len(info.Header["Content-Type"]) == 0 {
log.Println("No content type", info.Filename)
return
}
// If a generic mime type was provided then use file extension to determine mimetype
mimeType := info.Header["Content-Type"][0]
if mimeType == "application/octet-stream" {
mimeType = docconv.MimeTypeByExtension(info.Filename)
}
if *logLevel >= 1 {
log.Println("Received file: " + info.Filename + " (" + mimeType + ")")
}
data, err := docconv.Convert(file, mimeType, readability)
if err != nil {
log.Printf("error converting data: %v", err)
data = &docconv.Response{
Error: err.Error(),
}
}
if err := json.NewEncoder(w).Encode(data); err != nil {
log.Printf("error marshaling JSON data: %v", err)
return
}
})
// Start webserver
log.Println("Setting log level to", *logLevel)
log.Println("Starting docconv on", *listenAddr)
log.Fatal(http.ListenAndServe(*listenAddr, nil))
}
|
go
|
func serve() {
http.HandleFunc("/convert", func(w http.ResponseWriter, r *http.Request) {
// Readability flag. Currently only used for HTML
var readability bool
if r.FormValue("readability") == "1" {
readability = true
if *logLevel >= 2 {
log.Println("Readability is on")
}
}
path := r.FormValue("path")
if path != "" {
b, err := docconv.ConvertPathReadability(path, readability)
if err != nil {
// TODO: return a sensible status code for errors like this.
log.Printf("error converting path '%v': %v", path, err)
return
}
w.Write(b)
return
}
// Get uploaded file
file, info, err := r.FormFile("input")
if err != nil {
log.Println("File upload", err)
return
}
defer file.Close()
// Abort if file doesn't have a mime type
if len(info.Header["Content-Type"]) == 0 {
log.Println("No content type", info.Filename)
return
}
// If a generic mime type was provided then use file extension to determine mimetype
mimeType := info.Header["Content-Type"][0]
if mimeType == "application/octet-stream" {
mimeType = docconv.MimeTypeByExtension(info.Filename)
}
if *logLevel >= 1 {
log.Println("Received file: " + info.Filename + " (" + mimeType + ")")
}
data, err := docconv.Convert(file, mimeType, readability)
if err != nil {
log.Printf("error converting data: %v", err)
data = &docconv.Response{
Error: err.Error(),
}
}
if err := json.NewEncoder(w).Encode(data); err != nil {
log.Printf("error marshaling JSON data: %v", err)
return
}
})
// Start webserver
log.Println("Setting log level to", *logLevel)
log.Println("Starting docconv on", *listenAddr)
log.Fatal(http.ListenAndServe(*listenAddr, nil))
}
|
[
"func",
"serve",
"(",
")",
"{",
"http",
".",
"HandleFunc",
"(",
"\"",
"\"",
",",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"// Readability flag. Currently only used for HTML",
"var",
"readability",
"bool",
"\n",
"if",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"readability",
"=",
"true",
"\n",
"if",
"*",
"logLevel",
">=",
"2",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"path",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"path",
"!=",
"\"",
"\"",
"{",
"b",
",",
"err",
":=",
"docconv",
".",
"ConvertPathReadability",
"(",
"path",
",",
"readability",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// TODO: return a sensible status code for errors like this.",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"path",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"b",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Get uploaded file",
"file",
",",
"info",
",",
"err",
":=",
"r",
".",
"FormFile",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"file",
".",
"Close",
"(",
")",
"\n\n",
"// Abort if file doesn't have a mime type",
"if",
"len",
"(",
"info",
".",
"Header",
"[",
"\"",
"\"",
"]",
")",
"==",
"0",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"info",
".",
"Filename",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// If a generic mime type was provided then use file extension to determine mimetype",
"mimeType",
":=",
"info",
".",
"Header",
"[",
"\"",
"\"",
"]",
"[",
"0",
"]",
"\n",
"if",
"mimeType",
"==",
"\"",
"\"",
"{",
"mimeType",
"=",
"docconv",
".",
"MimeTypeByExtension",
"(",
"info",
".",
"Filename",
")",
"\n",
"}",
"\n\n",
"if",
"*",
"logLevel",
">=",
"1",
"{",
"log",
".",
"Println",
"(",
"\"",
"\"",
"+",
"info",
".",
"Filename",
"+",
"\"",
"\"",
"+",
"mimeType",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"data",
",",
"err",
":=",
"docconv",
".",
"Convert",
"(",
"file",
",",
"mimeType",
",",
"readability",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"data",
"=",
"&",
"docconv",
".",
"Response",
"{",
"Error",
":",
"err",
".",
"Error",
"(",
")",
",",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"json",
".",
"NewEncoder",
"(",
"w",
")",
".",
"Encode",
"(",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
")",
"\n\n",
"// Start webserver",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"*",
"logLevel",
")",
"\n",
"log",
".",
"Println",
"(",
"\"",
"\"",
",",
"*",
"listenAddr",
")",
"\n",
"log",
".",
"Fatal",
"(",
"http",
".",
"ListenAndServe",
"(",
"*",
"listenAddr",
",",
"nil",
")",
")",
"\n",
"}"
] |
// Start the conversion web service
|
[
"Start",
"the",
"conversion",
"web",
"service"
] |
eedabc494f8e97c31f94c70453273f16dbecbc6f
|
https://github.com/sajari/docconv/blob/eedabc494f8e97c31f94c70453273f16dbecbc6f/docd/main.go#L81-L146
|
train
|
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.