id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
16,700
|
kontena/kontena
|
cli/lib/kontena/client.rb
|
Kontena.Client.get_stream
|
def get_stream(path, response_block, params = nil, headers = {}, auth = true)
request(path: path, query: params, headers: headers, response_block: response_block, auth: auth, gzip: false)
end
|
ruby
|
def get_stream(path, response_block, params = nil, headers = {}, auth = true)
request(path: path, query: params, headers: headers, response_block: response_block, auth: auth, gzip: false)
end
|
[
"def",
"get_stream",
"(",
"path",
",",
"response_block",
",",
"params",
"=",
"nil",
",",
"headers",
"=",
"{",
"}",
",",
"auth",
"=",
"true",
")",
"request",
"(",
"path",
":",
"path",
",",
"query",
":",
"params",
",",
"headers",
":",
"headers",
",",
"response_block",
":",
"response_block",
",",
"auth",
":",
"auth",
",",
"gzip",
":",
"false",
")",
"end"
] |
Get stream request
@param [String] path
@param [Lambda] response_block
@param [Hash,NilClass] params
@param [Hash] headers
|
[
"Get",
"stream",
"request"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L253-L255
|
16,701
|
kontena/kontena
|
cli/lib/kontena/client.rb
|
Kontena.Client.request
|
def request(http_method: :get, path:'/', body: nil, query: {}, headers: {}, response_block: nil, expects: [200, 201, 204], host: nil, port: nil, auth: true, gzip: true)
retried ||= false
if auth && token_expired?
raise Excon::Error::Unauthorized, "Token expired or not valid, you need to login again, use: kontena #{token_is_for_master? ? "master" : "cloud"} login"
end
request_headers = request_headers(headers, auth: auth, gzip: gzip)
if body.nil?
body_content = ''
request_headers.delete(CONTENT_TYPE)
else
body_content = encode_body(body, request_headers[CONTENT_TYPE])
request_headers.merge!('Content-Length' => body_content.bytesize)
end
uri = URI.parse(path)
host_options = {}
if uri.host
host_options[:host] = uri.host
host_options[:port] = uri.port
host_options[:scheme] = uri.scheme
path = uri.request_uri
else
host_options[:host] = host if host
host_options[:port] = port if port
end
request_options = {
method: http_method,
expects: Array(expects),
path: path_with_prefix(path),
headers: request_headers,
body: body_content,
query: query
}.merge(host_options)
request_options.merge!(response_block: response_block) if response_block
# Store the response into client.last_response
@last_response = http_client.request(request_options)
parse_response(@last_response)
rescue Excon::Error::Unauthorized
if token
debug { 'Server reports access token expired' }
if retried || !token || !token['refresh_token']
raise Kontena::Errors::StandardError.new(401, 'The access token has expired and needs to be refreshed')
end
retried = true
retry if refresh_token
end
raise Kontena::Errors::StandardError.new(401, 'Unauthorized')
rescue Excon::Error::HTTPStatus => error
if error.response.headers['Content-Encoding'] == 'gzip'
error.response.body = Zlib::GzipReader.new(StringIO.new(error.response.body)).read
end
debug { "Request #{error.request[:method].upcase} #{error.request[:path]}: #{error.response.status} #{error.response.reason_phrase}: #{error.response.body}" }
handle_error_response(error.response)
end
|
ruby
|
def request(http_method: :get, path:'/', body: nil, query: {}, headers: {}, response_block: nil, expects: [200, 201, 204], host: nil, port: nil, auth: true, gzip: true)
retried ||= false
if auth && token_expired?
raise Excon::Error::Unauthorized, "Token expired or not valid, you need to login again, use: kontena #{token_is_for_master? ? "master" : "cloud"} login"
end
request_headers = request_headers(headers, auth: auth, gzip: gzip)
if body.nil?
body_content = ''
request_headers.delete(CONTENT_TYPE)
else
body_content = encode_body(body, request_headers[CONTENT_TYPE])
request_headers.merge!('Content-Length' => body_content.bytesize)
end
uri = URI.parse(path)
host_options = {}
if uri.host
host_options[:host] = uri.host
host_options[:port] = uri.port
host_options[:scheme] = uri.scheme
path = uri.request_uri
else
host_options[:host] = host if host
host_options[:port] = port if port
end
request_options = {
method: http_method,
expects: Array(expects),
path: path_with_prefix(path),
headers: request_headers,
body: body_content,
query: query
}.merge(host_options)
request_options.merge!(response_block: response_block) if response_block
# Store the response into client.last_response
@last_response = http_client.request(request_options)
parse_response(@last_response)
rescue Excon::Error::Unauthorized
if token
debug { 'Server reports access token expired' }
if retried || !token || !token['refresh_token']
raise Kontena::Errors::StandardError.new(401, 'The access token has expired and needs to be refreshed')
end
retried = true
retry if refresh_token
end
raise Kontena::Errors::StandardError.new(401, 'Unauthorized')
rescue Excon::Error::HTTPStatus => error
if error.response.headers['Content-Encoding'] == 'gzip'
error.response.body = Zlib::GzipReader.new(StringIO.new(error.response.body)).read
end
debug { "Request #{error.request[:method].upcase} #{error.request[:path]}: #{error.response.status} #{error.response.reason_phrase}: #{error.response.body}" }
handle_error_response(error.response)
end
|
[
"def",
"request",
"(",
"http_method",
":",
":get",
",",
"path",
":",
"'/'",
",",
"body",
":",
"nil",
",",
"query",
":",
"{",
"}",
",",
"headers",
":",
"{",
"}",
",",
"response_block",
":",
"nil",
",",
"expects",
":",
"[",
"200",
",",
"201",
",",
"204",
"]",
",",
"host",
":",
"nil",
",",
"port",
":",
"nil",
",",
"auth",
":",
"true",
",",
"gzip",
":",
"true",
")",
"retried",
"||=",
"false",
"if",
"auth",
"&&",
"token_expired?",
"raise",
"Excon",
"::",
"Error",
"::",
"Unauthorized",
",",
"\"Token expired or not valid, you need to login again, use: kontena #{token_is_for_master? ? \"master\" : \"cloud\"} login\"",
"end",
"request_headers",
"=",
"request_headers",
"(",
"headers",
",",
"auth",
":",
"auth",
",",
"gzip",
":",
"gzip",
")",
"if",
"body",
".",
"nil?",
"body_content",
"=",
"''",
"request_headers",
".",
"delete",
"(",
"CONTENT_TYPE",
")",
"else",
"body_content",
"=",
"encode_body",
"(",
"body",
",",
"request_headers",
"[",
"CONTENT_TYPE",
"]",
")",
"request_headers",
".",
"merge!",
"(",
"'Content-Length'",
"=>",
"body_content",
".",
"bytesize",
")",
"end",
"uri",
"=",
"URI",
".",
"parse",
"(",
"path",
")",
"host_options",
"=",
"{",
"}",
"if",
"uri",
".",
"host",
"host_options",
"[",
":host",
"]",
"=",
"uri",
".",
"host",
"host_options",
"[",
":port",
"]",
"=",
"uri",
".",
"port",
"host_options",
"[",
":scheme",
"]",
"=",
"uri",
".",
"scheme",
"path",
"=",
"uri",
".",
"request_uri",
"else",
"host_options",
"[",
":host",
"]",
"=",
"host",
"if",
"host",
"host_options",
"[",
":port",
"]",
"=",
"port",
"if",
"port",
"end",
"request_options",
"=",
"{",
"method",
":",
"http_method",
",",
"expects",
":",
"Array",
"(",
"expects",
")",
",",
"path",
":",
"path_with_prefix",
"(",
"path",
")",
",",
"headers",
":",
"request_headers",
",",
"body",
":",
"body_content",
",",
"query",
":",
"query",
"}",
".",
"merge",
"(",
"host_options",
")",
"request_options",
".",
"merge!",
"(",
"response_block",
":",
"response_block",
")",
"if",
"response_block",
"# Store the response into client.last_response",
"@last_response",
"=",
"http_client",
".",
"request",
"(",
"request_options",
")",
"parse_response",
"(",
"@last_response",
")",
"rescue",
"Excon",
"::",
"Error",
"::",
"Unauthorized",
"if",
"token",
"debug",
"{",
"'Server reports access token expired'",
"}",
"if",
"retried",
"||",
"!",
"token",
"||",
"!",
"token",
"[",
"'refresh_token'",
"]",
"raise",
"Kontena",
"::",
"Errors",
"::",
"StandardError",
".",
"new",
"(",
"401",
",",
"'The access token has expired and needs to be refreshed'",
")",
"end",
"retried",
"=",
"true",
"retry",
"if",
"refresh_token",
"end",
"raise",
"Kontena",
"::",
"Errors",
"::",
"StandardError",
".",
"new",
"(",
"401",
",",
"'Unauthorized'",
")",
"rescue",
"Excon",
"::",
"Error",
"::",
"HTTPStatus",
"=>",
"error",
"if",
"error",
".",
"response",
".",
"headers",
"[",
"'Content-Encoding'",
"]",
"==",
"'gzip'",
"error",
".",
"response",
".",
"body",
"=",
"Zlib",
"::",
"GzipReader",
".",
"new",
"(",
"StringIO",
".",
"new",
"(",
"error",
".",
"response",
".",
"body",
")",
")",
".",
"read",
"end",
"debug",
"{",
"\"Request #{error.request[:method].upcase} #{error.request[:path]}: #{error.response.status} #{error.response.reason_phrase}: #{error.response.body}\"",
"}",
"handle_error_response",
"(",
"error",
".",
"response",
")",
"end"
] |
Perform a HTTP request. Will try to refresh the access token and retry if it's
expired or if the server responds with HTTP 401.
Automatically parses a JSON response into a hash.
After the request has been performed, the response can be inspected using
client.last_response.
@param http_method [Symbol] :get, :post, etc
@param path [String] if it starts with / then prefix won't be used.
@param body [Hash, String] will be encoded using #encode_body
@param query [Hash] url query parameters
@param headers [Hash] extra headers for request.
@param response_block [Proc] for streaming requests, must respond to #call
@param expects [Array] raises unless response status code matches this list.
@param auth [Boolean] use token authentication default = true
@return [Hash, String] response parsed response object
|
[
"Perform",
"a",
"HTTP",
"request",
".",
"Will",
"try",
"to",
"refresh",
"the",
"access",
"token",
"and",
"retry",
"if",
"it",
"s",
"expired",
"or",
"if",
"the",
"server",
"responds",
"with",
"HTTP",
"401",
"."
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L285-L351
|
16,702
|
kontena/kontena
|
cli/lib/kontena/client.rb
|
Kontena.Client.token_account
|
def token_account
return {} unless token
if token.respond_to?(:account)
token.account
elsif token.kind_of?(Hash) && token['account'].kind_of?(String)
config.find_account(token['account'])
else
{}
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end
|
ruby
|
def token_account
return {} unless token
if token.respond_to?(:account)
token.account
elsif token.kind_of?(Hash) && token['account'].kind_of?(String)
config.find_account(token['account'])
else
{}
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end
|
[
"def",
"token_account",
"return",
"{",
"}",
"unless",
"token",
"if",
"token",
".",
"respond_to?",
"(",
":account",
")",
"token",
".",
"account",
"elsif",
"token",
".",
"kind_of?",
"(",
"Hash",
")",
"&&",
"token",
"[",
"'account'",
"]",
".",
"kind_of?",
"(",
"String",
")",
"config",
".",
"find_account",
"(",
"token",
"[",
"'account'",
"]",
")",
"else",
"{",
"}",
"end",
"rescue",
"=>",
"ex",
"error",
"{",
"\"Access token refresh exception\"",
"}",
"error",
"{",
"ex",
"}",
"false",
"end"
] |
Accessor to token's account settings
|
[
"Accessor",
"to",
"token",
"s",
"account",
"settings"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L366-L379
|
16,703
|
kontena/kontena
|
cli/lib/kontena/client.rb
|
Kontena.Client.refresh_token
|
def refresh_token
debug { "Performing token refresh" }
return false if token.nil?
return false if token['refresh_token'].nil?
uri = URI.parse(token_account['token_endpoint'])
endpoint_data = { path: uri.path }
endpoint_data[:host] = uri.host if uri.host
endpoint_data[:port] = uri.port if uri.port
debug { "Token refresh endpoint: #{endpoint_data.inspect}" }
return false unless endpoint_data[:path]
response = request(
{
http_method: token_account['token_method'].downcase.to_sym,
body: refresh_request_params,
headers: {
CONTENT_TYPE => token_account['token_post_content_type']
}.merge(
token_account['code_requires_basic_auth'] ? basic_auth_header : {}
),
expects: [200, 201, 400, 401, 403],
auth: false
}.merge(endpoint_data)
)
if response && response['access_token']
debug { "Got response to refresh request" }
token['access_token'] = response['access_token']
token['refresh_token'] = response['refresh_token']
token['expires_at'] = in_to_at(response['expires_in'])
token.config.write if token.respond_to?(:config)
true
else
debug { "Got null or bad response to refresh request: #{last_response.inspect}" }
false
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end
|
ruby
|
def refresh_token
debug { "Performing token refresh" }
return false if token.nil?
return false if token['refresh_token'].nil?
uri = URI.parse(token_account['token_endpoint'])
endpoint_data = { path: uri.path }
endpoint_data[:host] = uri.host if uri.host
endpoint_data[:port] = uri.port if uri.port
debug { "Token refresh endpoint: #{endpoint_data.inspect}" }
return false unless endpoint_data[:path]
response = request(
{
http_method: token_account['token_method'].downcase.to_sym,
body: refresh_request_params,
headers: {
CONTENT_TYPE => token_account['token_post_content_type']
}.merge(
token_account['code_requires_basic_auth'] ? basic_auth_header : {}
),
expects: [200, 201, 400, 401, 403],
auth: false
}.merge(endpoint_data)
)
if response && response['access_token']
debug { "Got response to refresh request" }
token['access_token'] = response['access_token']
token['refresh_token'] = response['refresh_token']
token['expires_at'] = in_to_at(response['expires_in'])
token.config.write if token.respond_to?(:config)
true
else
debug { "Got null or bad response to refresh request: #{last_response.inspect}" }
false
end
rescue => ex
error { "Access token refresh exception" }
error { ex }
false
end
|
[
"def",
"refresh_token",
"debug",
"{",
"\"Performing token refresh\"",
"}",
"return",
"false",
"if",
"token",
".",
"nil?",
"return",
"false",
"if",
"token",
"[",
"'refresh_token'",
"]",
".",
"nil?",
"uri",
"=",
"URI",
".",
"parse",
"(",
"token_account",
"[",
"'token_endpoint'",
"]",
")",
"endpoint_data",
"=",
"{",
"path",
":",
"uri",
".",
"path",
"}",
"endpoint_data",
"[",
":host",
"]",
"=",
"uri",
".",
"host",
"if",
"uri",
".",
"host",
"endpoint_data",
"[",
":port",
"]",
"=",
"uri",
".",
"port",
"if",
"uri",
".",
"port",
"debug",
"{",
"\"Token refresh endpoint: #{endpoint_data.inspect}\"",
"}",
"return",
"false",
"unless",
"endpoint_data",
"[",
":path",
"]",
"response",
"=",
"request",
"(",
"{",
"http_method",
":",
"token_account",
"[",
"'token_method'",
"]",
".",
"downcase",
".",
"to_sym",
",",
"body",
":",
"refresh_request_params",
",",
"headers",
":",
"{",
"CONTENT_TYPE",
"=>",
"token_account",
"[",
"'token_post_content_type'",
"]",
"}",
".",
"merge",
"(",
"token_account",
"[",
"'code_requires_basic_auth'",
"]",
"?",
"basic_auth_header",
":",
"{",
"}",
")",
",",
"expects",
":",
"[",
"200",
",",
"201",
",",
"400",
",",
"401",
",",
"403",
"]",
",",
"auth",
":",
"false",
"}",
".",
"merge",
"(",
"endpoint_data",
")",
")",
"if",
"response",
"&&",
"response",
"[",
"'access_token'",
"]",
"debug",
"{",
"\"Got response to refresh request\"",
"}",
"token",
"[",
"'access_token'",
"]",
"=",
"response",
"[",
"'access_token'",
"]",
"token",
"[",
"'refresh_token'",
"]",
"=",
"response",
"[",
"'refresh_token'",
"]",
"token",
"[",
"'expires_at'",
"]",
"=",
"in_to_at",
"(",
"response",
"[",
"'expires_in'",
"]",
")",
"token",
".",
"config",
".",
"write",
"if",
"token",
".",
"respond_to?",
"(",
":config",
")",
"true",
"else",
"debug",
"{",
"\"Got null or bad response to refresh request: #{last_response.inspect}\"",
"}",
"false",
"end",
"rescue",
"=>",
"ex",
"error",
"{",
"\"Access token refresh exception\"",
"}",
"error",
"{",
"ex",
"}",
"false",
"end"
] |
Perform refresh token request to auth provider.
Updates the client's Token object and writes changes to
configuration.
@param [Boolean] use_basic_auth? When true, use basic auth authentication header
@return [Boolean] success?
|
[
"Perform",
"refresh",
"token",
"request",
"to",
"auth",
"provider",
".",
"Updates",
"the",
"client",
"s",
"Token",
"object",
"and",
"writes",
"changes",
"to",
"configuration",
"."
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L387-L429
|
16,704
|
kontena/kontena
|
cli/lib/kontena/client.rb
|
Kontena.Client.encode_body
|
def encode_body(body, content_type)
if content_type =~ JSON_REGEX # vnd.api+json should pass as json
dump_json(body)
elsif content_type == CONTENT_URLENCODED && body.kind_of?(Hash)
URI.encode_www_form(body)
else
body
end
end
|
ruby
|
def encode_body(body, content_type)
if content_type =~ JSON_REGEX # vnd.api+json should pass as json
dump_json(body)
elsif content_type == CONTENT_URLENCODED && body.kind_of?(Hash)
URI.encode_www_form(body)
else
body
end
end
|
[
"def",
"encode_body",
"(",
"body",
",",
"content_type",
")",
"if",
"content_type",
"=~",
"JSON_REGEX",
"# vnd.api+json should pass as json",
"dump_json",
"(",
"body",
")",
"elsif",
"content_type",
"==",
"CONTENT_URLENCODED",
"&&",
"body",
".",
"kind_of?",
"(",
"Hash",
")",
"URI",
".",
"encode_www_form",
"(",
"body",
")",
"else",
"body",
"end",
"end"
] |
Encode body based on content type.
@param [Object] body
@param [String] content_type
@return [String] encoded_content
|
[
"Encode",
"body",
"based",
"on",
"content",
"type",
"."
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L470-L478
|
16,705
|
kontena/kontena
|
cli/lib/kontena/client.rb
|
Kontena.Client.in_to_at
|
def in_to_at(expires_in)
if expires_in.to_i < 1
0
else
Time.now.utc.to_i + expires_in.to_i
end
end
|
ruby
|
def in_to_at(expires_in)
if expires_in.to_i < 1
0
else
Time.now.utc.to_i + expires_in.to_i
end
end
|
[
"def",
"in_to_at",
"(",
"expires_in",
")",
"if",
"expires_in",
".",
"to_i",
"<",
"1",
"0",
"else",
"Time",
".",
"now",
".",
"utc",
".",
"to_i",
"+",
"expires_in",
".",
"to_i",
"end",
"end"
] |
Convert expires_in into expires_at
@param [Fixnum] seconds_till_expiration
@return [Fixnum] expires_at_unix_timestamp
|
[
"Convert",
"expires_in",
"into",
"expires_at"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/client.rb#L566-L572
|
16,706
|
kontena/kontena
|
agent/lib/kontena/rpc_client.rb
|
Kontena.RpcClient.request
|
def request(method, params, timeout: 30)
if !wait_until("websocket client is connected", timeout: timeout, threshold: 10.0, interval: 0.1) { connected? }
raise TimeoutError.new(500, 'WebsocketClient is not connected')
end
id = request_id
observable = @requests[id] = RequestObservable.new(method, id)
websocket_client.send_request(id, method, params)
begin
result, error = observe(observable, timeout: timeout)
rescue Timeout::Error => exc
raise TimeoutError.new(500, exc.message)
end
@requests.delete(id)
if error
raise Error.new(error['code'], error['message'])
else
return result
end
rescue => exc
warn exc
abort exc
end
|
ruby
|
def request(method, params, timeout: 30)
if !wait_until("websocket client is connected", timeout: timeout, threshold: 10.0, interval: 0.1) { connected? }
raise TimeoutError.new(500, 'WebsocketClient is not connected')
end
id = request_id
observable = @requests[id] = RequestObservable.new(method, id)
websocket_client.send_request(id, method, params)
begin
result, error = observe(observable, timeout: timeout)
rescue Timeout::Error => exc
raise TimeoutError.new(500, exc.message)
end
@requests.delete(id)
if error
raise Error.new(error['code'], error['message'])
else
return result
end
rescue => exc
warn exc
abort exc
end
|
[
"def",
"request",
"(",
"method",
",",
"params",
",",
"timeout",
":",
"30",
")",
"if",
"!",
"wait_until",
"(",
"\"websocket client is connected\"",
",",
"timeout",
":",
"timeout",
",",
"threshold",
":",
"10.0",
",",
"interval",
":",
"0.1",
")",
"{",
"connected?",
"}",
"raise",
"TimeoutError",
".",
"new",
"(",
"500",
",",
"'WebsocketClient is not connected'",
")",
"end",
"id",
"=",
"request_id",
"observable",
"=",
"@requests",
"[",
"id",
"]",
"=",
"RequestObservable",
".",
"new",
"(",
"method",
",",
"id",
")",
"websocket_client",
".",
"send_request",
"(",
"id",
",",
"method",
",",
"params",
")",
"begin",
"result",
",",
"error",
"=",
"observe",
"(",
"observable",
",",
"timeout",
":",
"timeout",
")",
"rescue",
"Timeout",
"::",
"Error",
"=>",
"exc",
"raise",
"TimeoutError",
".",
"new",
"(",
"500",
",",
"exc",
".",
"message",
")",
"end",
"@requests",
".",
"delete",
"(",
"id",
")",
"if",
"error",
"raise",
"Error",
".",
"new",
"(",
"error",
"[",
"'code'",
"]",
",",
"error",
"[",
"'message'",
"]",
")",
"else",
"return",
"result",
"end",
"rescue",
"=>",
"exc",
"warn",
"exc",
"abort",
"exc",
"end"
] |
Aborts caller on errors.
@param [String] method
@param [Array] params
@param [Float] timeout seconds
@raise abort
@return [Object]
|
[
"Aborts",
"caller",
"on",
"errors",
"."
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/rpc_client.rb#L64-L90
|
16,707
|
kontena/kontena
|
server/app/services/agent/node_plugger.rb
|
Agent.NodePlugger.reject!
|
def reject!(connected_at, code, reason)
self.update_node!(connected_at,
connected: false,
updated: false,
websocket_connection: {
opened: false,
close_code: code,
close_reason: reason,
},
)
info "Rejected connection for node #{@node.to_path} at #{connected_at} with code #{code}: #{reason}"
rescue => exc
error exc
end
|
ruby
|
def reject!(connected_at, code, reason)
self.update_node!(connected_at,
connected: false,
updated: false,
websocket_connection: {
opened: false,
close_code: code,
close_reason: reason,
},
)
info "Rejected connection for node #{@node.to_path} at #{connected_at} with code #{code}: #{reason}"
rescue => exc
error exc
end
|
[
"def",
"reject!",
"(",
"connected_at",
",",
"code",
",",
"reason",
")",
"self",
".",
"update_node!",
"(",
"connected_at",
",",
"connected",
":",
"false",
",",
"updated",
":",
"false",
",",
"websocket_connection",
":",
"{",
"opened",
":",
"false",
",",
"close_code",
":",
"code",
",",
"close_reason",
":",
"reason",
",",
"}",
",",
")",
"info",
"\"Rejected connection for node #{@node.to_path} at #{connected_at} with code #{code}: #{reason}\"",
"rescue",
"=>",
"exc",
"error",
"exc",
"end"
] |
Connection was rejected
@param [Time] connected_at
@param [Integer] code websocket close
@param [String] reason websocket close
|
[
"Connection",
"was",
"rejected"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/services/agent/node_plugger.rb#L36-L49
|
16,708
|
kontena/kontena
|
server/app/mutations/stacks/sort_helper.rb
|
Stacks.SortHelper.sort_services
|
def sort_services(services)
# Map of service name to array of deep links, including links of linked services
service_links = {}
# Build hash of service name to shallow array of linked service names
# {service => [linked_service]}
services.each do |service|
service_links[service[:name]] = __links_for_service(service)
end
# Mutate each service's array to add a deep reference to each linked service's own array of linked services
# {service => [linked_service, [linked_service_links, [...]]]}
service_links.each do |service, links|
links.dup.each do |linked_service|
if linked_service_links = service_links[linked_service]
service_links[service] << linked_service_links
else
raise MissingLinkError.new(service, linked_service)
end
end
end
# Flatten the deep array references to a flat array
# In case of recursive references, the Array#flatten! will fail with ArgumentError: tried to flatten recursive array
# {service => [linked_service, linked_service_link, ...]}
service_links.each do |service, links|
begin
service_links[service] = service_links[service].flatten
rescue ArgumentError
raise RecursiveLinkError.new(service, links)
end
end
# Sort using deep service links
services.sort{ |a, b|
a_links = service_links[a[:name]]
b_links = service_links[b[:name]]
if a_links.include? b[:name]
1
elsif b_links.include? a[:name]
-1
else
a_links.size <=> b_links.size
end
}
end
|
ruby
|
def sort_services(services)
# Map of service name to array of deep links, including links of linked services
service_links = {}
# Build hash of service name to shallow array of linked service names
# {service => [linked_service]}
services.each do |service|
service_links[service[:name]] = __links_for_service(service)
end
# Mutate each service's array to add a deep reference to each linked service's own array of linked services
# {service => [linked_service, [linked_service_links, [...]]]}
service_links.each do |service, links|
links.dup.each do |linked_service|
if linked_service_links = service_links[linked_service]
service_links[service] << linked_service_links
else
raise MissingLinkError.new(service, linked_service)
end
end
end
# Flatten the deep array references to a flat array
# In case of recursive references, the Array#flatten! will fail with ArgumentError: tried to flatten recursive array
# {service => [linked_service, linked_service_link, ...]}
service_links.each do |service, links|
begin
service_links[service] = service_links[service].flatten
rescue ArgumentError
raise RecursiveLinkError.new(service, links)
end
end
# Sort using deep service links
services.sort{ |a, b|
a_links = service_links[a[:name]]
b_links = service_links[b[:name]]
if a_links.include? b[:name]
1
elsif b_links.include? a[:name]
-1
else
a_links.size <=> b_links.size
end
}
end
|
[
"def",
"sort_services",
"(",
"services",
")",
"# Map of service name to array of deep links, including links of linked services",
"service_links",
"=",
"{",
"}",
"# Build hash of service name to shallow array of linked service names",
"# {service => [linked_service]}",
"services",
".",
"each",
"do",
"|",
"service",
"|",
"service_links",
"[",
"service",
"[",
":name",
"]",
"]",
"=",
"__links_for_service",
"(",
"service",
")",
"end",
"# Mutate each service's array to add a deep reference to each linked service's own array of linked services",
"# {service => [linked_service, [linked_service_links, [...]]]}",
"service_links",
".",
"each",
"do",
"|",
"service",
",",
"links",
"|",
"links",
".",
"dup",
".",
"each",
"do",
"|",
"linked_service",
"|",
"if",
"linked_service_links",
"=",
"service_links",
"[",
"linked_service",
"]",
"service_links",
"[",
"service",
"]",
"<<",
"linked_service_links",
"else",
"raise",
"MissingLinkError",
".",
"new",
"(",
"service",
",",
"linked_service",
")",
"end",
"end",
"end",
"# Flatten the deep array references to a flat array",
"# In case of recursive references, the Array#flatten! will fail with ArgumentError: tried to flatten recursive array",
"# {service => [linked_service, linked_service_link, ...]}",
"service_links",
".",
"each",
"do",
"|",
"service",
",",
"links",
"|",
"begin",
"service_links",
"[",
"service",
"]",
"=",
"service_links",
"[",
"service",
"]",
".",
"flatten",
"rescue",
"ArgumentError",
"raise",
"RecursiveLinkError",
".",
"new",
"(",
"service",
",",
"links",
")",
"end",
"end",
"# Sort using deep service links",
"services",
".",
"sort",
"{",
"|",
"a",
",",
"b",
"|",
"a_links",
"=",
"service_links",
"[",
"a",
"[",
":name",
"]",
"]",
"b_links",
"=",
"service_links",
"[",
"b",
"[",
":name",
"]",
"]",
"if",
"a_links",
".",
"include?",
"b",
"[",
":name",
"]",
"1",
"elsif",
"b_links",
".",
"include?",
"a",
"[",
":name",
"]",
"-",
"1",
"else",
"a_links",
".",
"size",
"<=>",
"b_links",
".",
"size",
"end",
"}",
"end"
] |
Sort services with a stack, such that services come after any services that they link to.
This can only be used to sort services within the same stack. Links to services in other stacks are ignored.
@param [Array<GridService,Hash>]
@raise [MissingLinkError] service ... has missing links: ...
@raise [RecursiveLinkError] service ... has recursive links: ...
@return [Array<GridService,Hash>]
|
[
"Sort",
"services",
"with",
"a",
"stack",
"such",
"that",
"services",
"come",
"after",
"any",
"services",
"that",
"they",
"link",
"to",
".",
"This",
"can",
"only",
"be",
"used",
"to",
"sort",
"services",
"within",
"the",
"same",
"stack",
".",
"Links",
"to",
"services",
"in",
"other",
"stacks",
"are",
"ignored",
"."
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/server/app/mutations/stacks/sort_helper.rb#L46-L92
|
16,709
|
kontena/kontena
|
cli/lib/kontena/cli/helpers/health_helper.rb
|
Kontena::Cli::Helpers.HealthHelper.grid_health
|
def grid_health(grid, nodes)
initial = grid['initial_size']
minimum = grid['initial_size'] / 2 + 1 # a majority is required for etcd quorum
online = nodes.select{|node| node['initial_member'] && node['connected']}
if online.length < minimum
return :error
elsif online.length < initial
return :warning
else
return :ok
end
end
|
ruby
|
def grid_health(grid, nodes)
initial = grid['initial_size']
minimum = grid['initial_size'] / 2 + 1 # a majority is required for etcd quorum
online = nodes.select{|node| node['initial_member'] && node['connected']}
if online.length < minimum
return :error
elsif online.length < initial
return :warning
else
return :ok
end
end
|
[
"def",
"grid_health",
"(",
"grid",
",",
"nodes",
")",
"initial",
"=",
"grid",
"[",
"'initial_size'",
"]",
"minimum",
"=",
"grid",
"[",
"'initial_size'",
"]",
"/",
"2",
"+",
"1",
"# a majority is required for etcd quorum",
"online",
"=",
"nodes",
".",
"select",
"{",
"|",
"node",
"|",
"node",
"[",
"'initial_member'",
"]",
"&&",
"node",
"[",
"'connected'",
"]",
"}",
"if",
"online",
".",
"length",
"<",
"minimum",
"return",
":error",
"elsif",
"online",
".",
"length",
"<",
"initial",
"return",
":warning",
"else",
"return",
":ok",
"end",
"end"
] |
Validate grid nodes configuration and status
@param grid [Hash] get(/grids/:grid) => { ... }
@param nodes [Array<Hash>] get(/grids/:grid/nodes)[nodes] => [ { ... } ]
@return [Symbol] health
|
[
"Validate",
"grid",
"nodes",
"configuration",
"and",
"status"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/helpers/health_helper.rb#L25-L38
|
16,710
|
kontena/kontena
|
cli/lib/kontena/cli/stacks/common.rb
|
Kontena::Cli::Stacks.Common.stack
|
def stack
@stack ||= reader.execute(
name: stack_name,
parent_name: self.respond_to?(:parent_name) ? self.parent_name : nil,
values: (self.respond_to?(:values_from_options) ? self.values_from_options : {})
)
end
|
ruby
|
def stack
@stack ||= reader.execute(
name: stack_name,
parent_name: self.respond_to?(:parent_name) ? self.parent_name : nil,
values: (self.respond_to?(:values_from_options) ? self.values_from_options : {})
)
end
|
[
"def",
"stack",
"@stack",
"||=",
"reader",
".",
"execute",
"(",
"name",
":",
"stack_name",
",",
"parent_name",
":",
"self",
".",
"respond_to?",
"(",
":parent_name",
")",
"?",
"self",
".",
"parent_name",
":",
"nil",
",",
"values",
":",
"(",
"self",
".",
"respond_to?",
"(",
":values_from_options",
")",
"?",
"self",
".",
"values_from_options",
":",
"{",
"}",
")",
")",
"end"
] |
An accessor to the YAML Reader outcome. Passes parent name, values from command line and
the stackname to the reader.
@return [Hash]
|
[
"An",
"accessor",
"to",
"the",
"YAML",
"Reader",
"outcome",
".",
"Passes",
"parent",
"name",
"values",
"from",
"command",
"line",
"and",
"the",
"stackname",
"to",
"the",
"reader",
"."
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/stacks/common.rb#L32-L38
|
16,711
|
kontena/kontena
|
cli/lib/kontena/cli/stacks/common.rb
|
Kontena::Cli::Stacks.Common.set_env_variables
|
def set_env_variables(stack, grid, platform = grid)
ENV['STACK'] = stack
ENV['GRID'] = grid
ENV['PLATFORM'] = platform
end
|
ruby
|
def set_env_variables(stack, grid, platform = grid)
ENV['STACK'] = stack
ENV['GRID'] = grid
ENV['PLATFORM'] = platform
end
|
[
"def",
"set_env_variables",
"(",
"stack",
",",
"grid",
",",
"platform",
"=",
"grid",
")",
"ENV",
"[",
"'STACK'",
"]",
"=",
"stack",
"ENV",
"[",
"'GRID'",
"]",
"=",
"grid",
"ENV",
"[",
"'PLATFORM'",
"]",
"=",
"platform",
"end"
] |
Sets environment variables from parameters
@param stack [String] current stack name
@param grid [String] current grid name
@param platform [String] current platform name, defaults to param grid value
|
[
"Sets",
"environment",
"variables",
"from",
"parameters"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/stacks/common.rb#L175-L179
|
16,712
|
kontena/kontena
|
cli/lib/kontena/cli/stacks/common.rb
|
Kontena::Cli::Stacks.Common.stacks_client
|
def stacks_client
@stacks_client ||= Kontena::StacksClient.new(current_account.stacks_url, current_account.token, read_requires_token: current_account.stacks_read_authentication)
end
|
ruby
|
def stacks_client
@stacks_client ||= Kontena::StacksClient.new(current_account.stacks_url, current_account.token, read_requires_token: current_account.stacks_read_authentication)
end
|
[
"def",
"stacks_client",
"@stacks_client",
"||=",
"Kontena",
"::",
"StacksClient",
".",
"new",
"(",
"current_account",
".",
"stacks_url",
",",
"current_account",
".",
"token",
",",
"read_requires_token",
":",
"current_account",
".",
"stacks_read_authentication",
")",
"end"
] |
An accessor to stack registry client
@return [Kontena::StacksClient]
|
[
"An",
"accessor",
"to",
"stack",
"registry",
"client"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/stacks/common.rb#L205-L207
|
16,713
|
kontena/kontena
|
cli/lib/kontena/stacks/change_resolver.rb
|
Kontena::Stacks.ChangeResolver.stack_upgraded?
|
def stack_upgraded?(name)
old_stack = old_data.stack(name)
new_stack = new_data.stack(name)
return true if new_stack.root?
return true if old_stack.version != new_stack.version
return true if old_stack.stack_name != new_stack.stack_name
return true if old_stack.variables != new_stack.variables
false
end
|
ruby
|
def stack_upgraded?(name)
old_stack = old_data.stack(name)
new_stack = new_data.stack(name)
return true if new_stack.root?
return true if old_stack.version != new_stack.version
return true if old_stack.stack_name != new_stack.stack_name
return true if old_stack.variables != new_stack.variables
false
end
|
[
"def",
"stack_upgraded?",
"(",
"name",
")",
"old_stack",
"=",
"old_data",
".",
"stack",
"(",
"name",
")",
"new_stack",
"=",
"new_data",
".",
"stack",
"(",
"name",
")",
"return",
"true",
"if",
"new_stack",
".",
"root?",
"return",
"true",
"if",
"old_stack",
".",
"version",
"!=",
"new_stack",
".",
"version",
"return",
"true",
"if",
"old_stack",
".",
"stack_name",
"!=",
"new_stack",
".",
"stack_name",
"return",
"true",
"if",
"old_stack",
".",
"variables",
"!=",
"new_stack",
".",
"variables",
"false",
"end"
] |
Stack is upgraded if version, stack name, variables change or stack is root
@param name [String]
@return [Boolean]
|
[
"Stack",
"is",
"upgraded",
"if",
"version",
"stack",
"name",
"variables",
"change",
"or",
"stack",
"is",
"root"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/stacks/change_resolver.rb#L107-L116
|
16,714
|
kontena/kontena
|
agent/lib/kontena/workers/log_worker.rb
|
Kontena::Workers.LogWorker.process_queue
|
def process_queue
loop do
sleep 1 until processing?
buffer = @queue.shift(BATCH_SIZE)
if buffer.size > 0
rpc_client.notification('/containers/log_batch', [buffer])
sleep 0.01
else
sleep 1
end
end
end
|
ruby
|
def process_queue
loop do
sleep 1 until processing?
buffer = @queue.shift(BATCH_SIZE)
if buffer.size > 0
rpc_client.notification('/containers/log_batch', [buffer])
sleep 0.01
else
sleep 1
end
end
end
|
[
"def",
"process_queue",
"loop",
"do",
"sleep",
"1",
"until",
"processing?",
"buffer",
"=",
"@queue",
".",
"shift",
"(",
"BATCH_SIZE",
")",
"if",
"buffer",
".",
"size",
">",
"0",
"rpc_client",
".",
"notification",
"(",
"'/containers/log_batch'",
",",
"[",
"buffer",
"]",
")",
"sleep",
"0.01",
"else",
"sleep",
"1",
"end",
"end",
"end"
] |
Process items from @queue
|
[
"Process",
"items",
"from"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/log_worker.rb#L62-L73
|
16,715
|
kontena/kontena
|
agent/lib/kontena/workers/log_worker.rb
|
Kontena::Workers.LogWorker.start_streaming
|
def start_streaming
info 'start streaming logs from containers'
Docker::Container.all.each do |container|
begin
self.stream_container_logs(container) unless container.skip_logs?
rescue Docker::Error::NotFoundError => exc
# Could be thrown since container.skip_logs? actually loads the container details
warn exc.message
rescue => exc
error exc
end
end
@streaming = true
end
|
ruby
|
def start_streaming
info 'start streaming logs from containers'
Docker::Container.all.each do |container|
begin
self.stream_container_logs(container) unless container.skip_logs?
rescue Docker::Error::NotFoundError => exc
# Could be thrown since container.skip_logs? actually loads the container details
warn exc.message
rescue => exc
error exc
end
end
@streaming = true
end
|
[
"def",
"start_streaming",
"info",
"'start streaming logs from containers'",
"Docker",
"::",
"Container",
".",
"all",
".",
"each",
"do",
"|",
"container",
"|",
"begin",
"self",
".",
"stream_container_logs",
"(",
"container",
")",
"unless",
"container",
".",
"skip_logs?",
"rescue",
"Docker",
"::",
"Error",
"::",
"NotFoundError",
"=>",
"exc",
"# Could be thrown since container.skip_logs? actually loads the container details",
"warn",
"exc",
".",
"message",
"rescue",
"=>",
"exc",
"error",
"exc",
"end",
"end",
"@streaming",
"=",
"true",
"end"
] |
requires etcd to be available to read log timestamps
|
[
"requires",
"etcd",
"to",
"be",
"available",
"to",
"read",
"log",
"timestamps"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/log_worker.rb#L126-L141
|
16,716
|
kontena/kontena
|
agent/lib/kontena/workers/log_worker.rb
|
Kontena::Workers.LogWorker.stop_streaming
|
def stop_streaming
@streaming = false
info 'stop log streaming'
@workers.keys.dup.each do |id|
queued_item = @queue.find { |i| i[:id] == id }
time = queued_item.nil? ? Time.now.to_i : Time.parse(queued_item[:time]).to_i
self.stop_streaming_container_logs(id)
self.mark_timestamp(id, time)
end
end
|
ruby
|
def stop_streaming
@streaming = false
info 'stop log streaming'
@workers.keys.dup.each do |id|
queued_item = @queue.find { |i| i[:id] == id }
time = queued_item.nil? ? Time.now.to_i : Time.parse(queued_item[:time]).to_i
self.stop_streaming_container_logs(id)
self.mark_timestamp(id, time)
end
end
|
[
"def",
"stop_streaming",
"@streaming",
"=",
"false",
"info",
"'stop log streaming'",
"@workers",
".",
"keys",
".",
"dup",
".",
"each",
"do",
"|",
"id",
"|",
"queued_item",
"=",
"@queue",
".",
"find",
"{",
"|",
"i",
"|",
"i",
"[",
":id",
"]",
"==",
"id",
"}",
"time",
"=",
"queued_item",
".",
"nil?",
"?",
"Time",
".",
"now",
".",
"to_i",
":",
"Time",
".",
"parse",
"(",
"queued_item",
"[",
":time",
"]",
")",
".",
"to_i",
"self",
".",
"stop_streaming_container_logs",
"(",
"id",
")",
"self",
".",
"mark_timestamp",
"(",
"id",
",",
"time",
")",
"end",
"end"
] |
best-effort attempt to write etcd timestamps; may not be possible
|
[
"best",
"-",
"effort",
"attempt",
"to",
"write",
"etcd",
"timestamps",
";",
"may",
"not",
"be",
"possible"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/agent/lib/kontena/workers/log_worker.rb#L169-L180
|
16,717
|
kontena/kontena
|
cli/lib/kontena/cli/stacks/upgrade_command.rb
|
Kontena::Cli::Stacks.UpgradeCommand.process_data
|
def process_data(old_data, new_data)
logger.debug { "Master stacks: #{old_data.keys.join(",")} YAML stacks: #{new_data.keys.join(",")}" }
new_data.reverse_each do |stackname, data|
spinner "Processing stack #{pastel.cyan(stackname)}"
process_stack_data(stackname, data, old_data)
hint_on_validation_notifications(reader.notifications, reader.loader.source)
abort_on_validation_errors(reader.errors, reader.loader.source)
end
old_set = Kontena::Stacks::StackDataSet.new(old_data)
new_set = Kontena::Stacks::StackDataSet.new(new_data)
if skip_dependencies?
[old_set, new_set].each(&:remove_dependencies)
end
spinner "Analyzing upgrade" do
Kontena::Stacks::ChangeResolver.new(old_set, new_set)
end
end
|
ruby
|
def process_data(old_data, new_data)
logger.debug { "Master stacks: #{old_data.keys.join(",")} YAML stacks: #{new_data.keys.join(",")}" }
new_data.reverse_each do |stackname, data|
spinner "Processing stack #{pastel.cyan(stackname)}"
process_stack_data(stackname, data, old_data)
hint_on_validation_notifications(reader.notifications, reader.loader.source)
abort_on_validation_errors(reader.errors, reader.loader.source)
end
old_set = Kontena::Stacks::StackDataSet.new(old_data)
new_set = Kontena::Stacks::StackDataSet.new(new_data)
if skip_dependencies?
[old_set, new_set].each(&:remove_dependencies)
end
spinner "Analyzing upgrade" do
Kontena::Stacks::ChangeResolver.new(old_set, new_set)
end
end
|
[
"def",
"process_data",
"(",
"old_data",
",",
"new_data",
")",
"logger",
".",
"debug",
"{",
"\"Master stacks: #{old_data.keys.join(\",\")} YAML stacks: #{new_data.keys.join(\",\")}\"",
"}",
"new_data",
".",
"reverse_each",
"do",
"|",
"stackname",
",",
"data",
"|",
"spinner",
"\"Processing stack #{pastel.cyan(stackname)}\"",
"process_stack_data",
"(",
"stackname",
",",
"data",
",",
"old_data",
")",
"hint_on_validation_notifications",
"(",
"reader",
".",
"notifications",
",",
"reader",
".",
"loader",
".",
"source",
")",
"abort_on_validation_errors",
"(",
"reader",
".",
"errors",
",",
"reader",
".",
"loader",
".",
"source",
")",
"end",
"old_set",
"=",
"Kontena",
"::",
"Stacks",
"::",
"StackDataSet",
".",
"new",
"(",
"old_data",
")",
"new_set",
"=",
"Kontena",
"::",
"Stacks",
"::",
"StackDataSet",
".",
"new",
"(",
"new_data",
")",
"if",
"skip_dependencies?",
"[",
"old_set",
",",
"new_set",
"]",
".",
"each",
"(",
":remove_dependencies",
")",
"end",
"spinner",
"\"Analyzing upgrade\"",
"do",
"Kontena",
"::",
"Stacks",
"::",
"ChangeResolver",
".",
"new",
"(",
"old_set",
",",
"new_set",
")",
"end",
"end"
] |
Preprocess data and return a ChangeResolver
@param old_data [Hash] data from master
@param new_data [Hash] data from files
@return [Kontena::Cli::Stacks::ChangeRsolver]
|
[
"Preprocess",
"data",
"and",
"return",
"a",
"ChangeResolver"
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/stacks/upgrade_command.rb#L89-L107
|
16,718
|
kontena/kontena
|
cli/lib/kontena/cli/localhost_web_server.rb
|
Kontena.LocalhostWebServer.serve_one
|
def serve_one
Kontena.logger.debug("LHWS") { "Waiting for connection on port #{port}.." }
socket = server.accept
content = socket.recvfrom(2048).first.split(/(?:\r)?\n/)
request = content.shift
headers = {}
while line = content.shift
break if line.nil?
break if line == ''
header, value = line.chomp.split(/:\s{0,}/, 2)
headers[header] = value
end
body = content.join("\n")
Kontena.logger.debug("LHWS") { "Got request: \"#{request.inspect}\n Headers: #{headers.inspect}\n Body: #{body}\"" }
get_request = request[/GET (\/cb.+?) HTTP/, 1]
if get_request
if success_response
socket.print [
'HTTP/1.1 200 OK',
'Content-Type: text/html',
"Content-Length: #{success_response.bytesize}",
"Connection: close",
'',
success_response
].join("\r\n")
else
socket.print [
'HTTP/1.1 302 Found',
"Location: #{SUCCESS_URL}",
"Referrer-Policy: no-referrer",
"Connection: close",
''
].join("\r\n")
end
socket.close
server.close
uri = URI.parse("http://localhost#{get_request}")
Kontena.logger.debug("LHWS") { " * Parsing params: \"#{uri.query}\"" }
params = {}
URI.decode_www_form(uri.query).each do |key, value|
if value.to_s == ''
next
elsif value.to_s =~ /\A\d+\z/
params[key] = value.to_i
else
params[key] = value
end
end
params
else
# Unless it's a query to /cb, send an error message and keep listening,
# it might have been something funny like fetching favicon.ico
socket.print [
'HTTP/1.1 400 Bad request',
'Content-Type: text/plain',
"Content-Length: #{error_response.bytesize}",
'Connection: close',
'',
error_response
].join("\r\n")
socket.close
serve_one # serve more, this one was not proper.
end
end
|
ruby
|
def serve_one
Kontena.logger.debug("LHWS") { "Waiting for connection on port #{port}.." }
socket = server.accept
content = socket.recvfrom(2048).first.split(/(?:\r)?\n/)
request = content.shift
headers = {}
while line = content.shift
break if line.nil?
break if line == ''
header, value = line.chomp.split(/:\s{0,}/, 2)
headers[header] = value
end
body = content.join("\n")
Kontena.logger.debug("LHWS") { "Got request: \"#{request.inspect}\n Headers: #{headers.inspect}\n Body: #{body}\"" }
get_request = request[/GET (\/cb.+?) HTTP/, 1]
if get_request
if success_response
socket.print [
'HTTP/1.1 200 OK',
'Content-Type: text/html',
"Content-Length: #{success_response.bytesize}",
"Connection: close",
'',
success_response
].join("\r\n")
else
socket.print [
'HTTP/1.1 302 Found',
"Location: #{SUCCESS_URL}",
"Referrer-Policy: no-referrer",
"Connection: close",
''
].join("\r\n")
end
socket.close
server.close
uri = URI.parse("http://localhost#{get_request}")
Kontena.logger.debug("LHWS") { " * Parsing params: \"#{uri.query}\"" }
params = {}
URI.decode_www_form(uri.query).each do |key, value|
if value.to_s == ''
next
elsif value.to_s =~ /\A\d+\z/
params[key] = value.to_i
else
params[key] = value
end
end
params
else
# Unless it's a query to /cb, send an error message and keep listening,
# it might have been something funny like fetching favicon.ico
socket.print [
'HTTP/1.1 400 Bad request',
'Content-Type: text/plain',
"Content-Length: #{error_response.bytesize}",
'Connection: close',
'',
error_response
].join("\r\n")
socket.close
serve_one # serve more, this one was not proper.
end
end
|
[
"def",
"serve_one",
"Kontena",
".",
"logger",
".",
"debug",
"(",
"\"LHWS\"",
")",
"{",
"\"Waiting for connection on port #{port}..\"",
"}",
"socket",
"=",
"server",
".",
"accept",
"content",
"=",
"socket",
".",
"recvfrom",
"(",
"2048",
")",
".",
"first",
".",
"split",
"(",
"/",
"\\r",
"\\n",
"/",
")",
"request",
"=",
"content",
".",
"shift",
"headers",
"=",
"{",
"}",
"while",
"line",
"=",
"content",
".",
"shift",
"break",
"if",
"line",
".",
"nil?",
"break",
"if",
"line",
"==",
"''",
"header",
",",
"value",
"=",
"line",
".",
"chomp",
".",
"split",
"(",
"/",
"\\s",
"/",
",",
"2",
")",
"headers",
"[",
"header",
"]",
"=",
"value",
"end",
"body",
"=",
"content",
".",
"join",
"(",
"\"\\n\"",
")",
"Kontena",
".",
"logger",
".",
"debug",
"(",
"\"LHWS\"",
")",
"{",
"\"Got request: \\\"#{request.inspect}\\n Headers: #{headers.inspect}\\n Body: #{body}\\\"\"",
"}",
"get_request",
"=",
"request",
"[",
"/",
"\\/",
"/",
",",
"1",
"]",
"if",
"get_request",
"if",
"success_response",
"socket",
".",
"print",
"[",
"'HTTP/1.1 200 OK'",
",",
"'Content-Type: text/html'",
",",
"\"Content-Length: #{success_response.bytesize}\"",
",",
"\"Connection: close\"",
",",
"''",
",",
"success_response",
"]",
".",
"join",
"(",
"\"\\r\\n\"",
")",
"else",
"socket",
".",
"print",
"[",
"'HTTP/1.1 302 Found'",
",",
"\"Location: #{SUCCESS_URL}\"",
",",
"\"Referrer-Policy: no-referrer\"",
",",
"\"Connection: close\"",
",",
"''",
"]",
".",
"join",
"(",
"\"\\r\\n\"",
")",
"end",
"socket",
".",
"close",
"server",
".",
"close",
"uri",
"=",
"URI",
".",
"parse",
"(",
"\"http://localhost#{get_request}\"",
")",
"Kontena",
".",
"logger",
".",
"debug",
"(",
"\"LHWS\"",
")",
"{",
"\" * Parsing params: \\\"#{uri.query}\\\"\"",
"}",
"params",
"=",
"{",
"}",
"URI",
".",
"decode_www_form",
"(",
"uri",
".",
"query",
")",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"to_s",
"==",
"''",
"next",
"elsif",
"value",
".",
"to_s",
"=~",
"/",
"\\A",
"\\d",
"\\z",
"/",
"params",
"[",
"key",
"]",
"=",
"value",
".",
"to_i",
"else",
"params",
"[",
"key",
"]",
"=",
"value",
"end",
"end",
"params",
"else",
"# Unless it's a query to /cb, send an error message and keep listening,",
"# it might have been something funny like fetching favicon.ico",
"socket",
".",
"print",
"[",
"'HTTP/1.1 400 Bad request'",
",",
"'Content-Type: text/plain'",
",",
"\"Content-Length: #{error_response.bytesize}\"",
",",
"'Connection: close'",
",",
"''",
",",
"error_response",
"]",
".",
"join",
"(",
"\"\\r\\n\"",
")",
"socket",
".",
"close",
"serve_one",
"# serve more, this one was not proper.",
"end",
"end"
] |
Serve one request and return query params.
@return [Hash] query_params
|
[
"Serve",
"one",
"request",
"and",
"return",
"query",
"params",
"."
] |
5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7
|
https://github.com/kontena/kontena/blob/5cb5b4457895985231ac88e78c8cbc5a8ffb5ec7/cli/lib/kontena/cli/localhost_web_server.rb#L41-L111
|
16,719
|
egonSchiele/contracts.ruby
|
lib/contracts/method_handler.rb
|
Contracts.MethodHandler.handle
|
def handle
return unless engine?
return if decorators.empty?
validate_decorators!
validate_pattern_matching!
engine.add_method_decorator(method_type, method_name, decorator)
mark_pattern_matching_decorators
method_reference.make_alias(target)
redefine_method
end
|
ruby
|
def handle
return unless engine?
return if decorators.empty?
validate_decorators!
validate_pattern_matching!
engine.add_method_decorator(method_type, method_name, decorator)
mark_pattern_matching_decorators
method_reference.make_alias(target)
redefine_method
end
|
[
"def",
"handle",
"return",
"unless",
"engine?",
"return",
"if",
"decorators",
".",
"empty?",
"validate_decorators!",
"validate_pattern_matching!",
"engine",
".",
"add_method_decorator",
"(",
"method_type",
",",
"method_name",
",",
"decorator",
")",
"mark_pattern_matching_decorators",
"method_reference",
".",
"make_alias",
"(",
"target",
")",
"redefine_method",
"end"
] |
Creates new instance of MethodHandler
@param [Symbol] method_name
@param [Bool] is_class_method
@param [Class] target - class that method got added to
Handles method addition
|
[
"Creates",
"new",
"instance",
"of",
"MethodHandler"
] |
141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716
|
https://github.com/egonSchiele/contracts.ruby/blob/141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716/lib/contracts/method_handler.rb#L27-L38
|
16,720
|
egonSchiele/contracts.ruby
|
lib/contracts/method_reference.rb
|
Contracts.MethodReference.make_definition
|
def make_definition(this, &blk)
is_private = private?(this)
is_protected = protected?(this)
alias_target(this).send(:define_method, name, &blk)
make_private(this) if is_private
make_protected(this) if is_protected
end
|
ruby
|
def make_definition(this, &blk)
is_private = private?(this)
is_protected = protected?(this)
alias_target(this).send(:define_method, name, &blk)
make_private(this) if is_private
make_protected(this) if is_protected
end
|
[
"def",
"make_definition",
"(",
"this",
",",
"&",
"blk",
")",
"is_private",
"=",
"private?",
"(",
"this",
")",
"is_protected",
"=",
"protected?",
"(",
"this",
")",
"alias_target",
"(",
"this",
")",
".",
"send",
"(",
":define_method",
",",
"name",
",",
"blk",
")",
"make_private",
"(",
"this",
")",
"if",
"is_private",
"make_protected",
"(",
"this",
")",
"if",
"is_protected",
"end"
] |
Makes a method re-definition in proper way
|
[
"Makes",
"a",
"method",
"re",
"-",
"definition",
"in",
"proper",
"way"
] |
141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716
|
https://github.com/egonSchiele/contracts.ruby/blob/141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716/lib/contracts/method_reference.rb#L20-L26
|
16,721
|
egonSchiele/contracts.ruby
|
lib/contracts/method_reference.rb
|
Contracts.MethodReference.make_alias
|
def make_alias(this)
_aliased_name = aliased_name
original_name = name
alias_target(this).class_eval do
alias_method _aliased_name, original_name
end
end
|
ruby
|
def make_alias(this)
_aliased_name = aliased_name
original_name = name
alias_target(this).class_eval do
alias_method _aliased_name, original_name
end
end
|
[
"def",
"make_alias",
"(",
"this",
")",
"_aliased_name",
"=",
"aliased_name",
"original_name",
"=",
"name",
"alias_target",
"(",
"this",
")",
".",
"class_eval",
"do",
"alias_method",
"_aliased_name",
",",
"original_name",
"end",
"end"
] |
Aliases original method to a special unique name, which is known
only to this class. Usually done right before re-defining the
method.
|
[
"Aliases",
"original",
"method",
"to",
"a",
"special",
"unique",
"name",
"which",
"is",
"known",
"only",
"to",
"this",
"class",
".",
"Usually",
"done",
"right",
"before",
"re",
"-",
"defining",
"the",
"method",
"."
] |
141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716
|
https://github.com/egonSchiele/contracts.ruby/blob/141dfb71c2dfb3fe10bda05cdd9f45b96eeb4716/lib/contracts/method_reference.rb#L31-L38
|
16,722
|
kschiess/parslet
|
lib/parslet/atoms/can_flatten.rb
|
Parslet::Atoms.CanFlatten.flatten
|
def flatten(value, named=false)
# Passes through everything that isn't an array of things
return value unless value.instance_of? Array
# Extracts the s-expression tag
tag, *tail = value
# Merges arrays:
result = tail.
map { |e| flatten(e) } # first flatten each element
case tag
when :sequence
return flatten_sequence(result)
when :maybe
return named ? result.first : result.first || ''
when :repetition
return flatten_repetition(result, named)
end
fail "BUG: Unknown tag #{tag.inspect}."
end
|
ruby
|
def flatten(value, named=false)
# Passes through everything that isn't an array of things
return value unless value.instance_of? Array
# Extracts the s-expression tag
tag, *tail = value
# Merges arrays:
result = tail.
map { |e| flatten(e) } # first flatten each element
case tag
when :sequence
return flatten_sequence(result)
when :maybe
return named ? result.first : result.first || ''
when :repetition
return flatten_repetition(result, named)
end
fail "BUG: Unknown tag #{tag.inspect}."
end
|
[
"def",
"flatten",
"(",
"value",
",",
"named",
"=",
"false",
")",
"# Passes through everything that isn't an array of things",
"return",
"value",
"unless",
"value",
".",
"instance_of?",
"Array",
"# Extracts the s-expression tag",
"tag",
",",
"*",
"tail",
"=",
"value",
"# Merges arrays:",
"result",
"=",
"tail",
".",
"map",
"{",
"|",
"e",
"|",
"flatten",
"(",
"e",
")",
"}",
"# first flatten each element",
"case",
"tag",
"when",
":sequence",
"return",
"flatten_sequence",
"(",
"result",
")",
"when",
":maybe",
"return",
"named",
"?",
"result",
".",
"first",
":",
"result",
".",
"first",
"||",
"''",
"when",
":repetition",
"return",
"flatten_repetition",
"(",
"result",
",",
"named",
")",
"end",
"fail",
"\"BUG: Unknown tag #{tag.inspect}.\"",
"end"
] |
Takes a mixed value coming out of a parslet and converts it to a return
value for the user by dropping things and merging hashes.
Named is set to true if this result will be embedded in a Hash result from
naming something using <code>.as(...)</code>. It changes the folding
semantics of repetition.
|
[
"Takes",
"a",
"mixed",
"value",
"coming",
"out",
"of",
"a",
"parslet",
"and",
"converts",
"it",
"to",
"a",
"return",
"value",
"for",
"the",
"user",
"by",
"dropping",
"things",
"and",
"merging",
"hashes",
"."
] |
b108758d76c51a1630f3b13c8f47dcd6637c5477
|
https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/atoms/can_flatten.rb#L23-L44
|
16,723
|
kschiess/parslet
|
lib/parslet/atoms/can_flatten.rb
|
Parslet::Atoms.CanFlatten.foldl
|
def foldl(list, &block)
return '' if list.empty?
list[1..-1].inject(list.first, &block)
end
|
ruby
|
def foldl(list, &block)
return '' if list.empty?
list[1..-1].inject(list.first, &block)
end
|
[
"def",
"foldl",
"(",
"list",
",",
"&",
"block",
")",
"return",
"''",
"if",
"list",
".",
"empty?",
"list",
"[",
"1",
"..",
"-",
"1",
"]",
".",
"inject",
"(",
"list",
".",
"first",
",",
"block",
")",
"end"
] |
Lisp style fold left where the first element builds the basis for
an inject.
|
[
"Lisp",
"style",
"fold",
"left",
"where",
"the",
"first",
"element",
"builds",
"the",
"basis",
"for",
"an",
"inject",
"."
] |
b108758d76c51a1630f3b13c8f47dcd6637c5477
|
https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/atoms/can_flatten.rb#L49-L52
|
16,724
|
kschiess/parslet
|
lib/parslet/atoms/can_flatten.rb
|
Parslet::Atoms.CanFlatten.flatten_sequence
|
def flatten_sequence(list)
foldl(list.compact) { |r, e| # and then merge flat elements
merge_fold(r, e)
}
end
|
ruby
|
def flatten_sequence(list)
foldl(list.compact) { |r, e| # and then merge flat elements
merge_fold(r, e)
}
end
|
[
"def",
"flatten_sequence",
"(",
"list",
")",
"foldl",
"(",
"list",
".",
"compact",
")",
"{",
"|",
"r",
",",
"e",
"|",
"# and then merge flat elements",
"merge_fold",
"(",
"r",
",",
"e",
")",
"}",
"end"
] |
Flatten results from a sequence of parslets.
@api private
|
[
"Flatten",
"results",
"from",
"a",
"sequence",
"of",
"parslets",
"."
] |
b108758d76c51a1630f3b13c8f47dcd6637c5477
|
https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/atoms/can_flatten.rb#L58-L62
|
16,725
|
kschiess/parslet
|
lib/parslet/atoms/can_flatten.rb
|
Parslet::Atoms.CanFlatten.flatten_repetition
|
def flatten_repetition(list, named)
if list.any? { |e| e.instance_of?(Hash) }
# If keyed subtrees are in the array, we'll want to discard all
# strings inbetween. To keep them, name them.
return list.select { |e| e.instance_of?(Hash) }
end
if list.any? { |e| e.instance_of?(Array) }
# If any arrays are nested in this array, flatten all arrays to this
# level.
return list.
select { |e| e.instance_of?(Array) }.
flatten(1)
end
# Consistent handling of empty lists, when we act on a named result
return [] if named && list.empty?
# If there are only strings, concatenate them and return that.
foldl(list.compact) { |s,e| s+e }
end
|
ruby
|
def flatten_repetition(list, named)
if list.any? { |e| e.instance_of?(Hash) }
# If keyed subtrees are in the array, we'll want to discard all
# strings inbetween. To keep them, name them.
return list.select { |e| e.instance_of?(Hash) }
end
if list.any? { |e| e.instance_of?(Array) }
# If any arrays are nested in this array, flatten all arrays to this
# level.
return list.
select { |e| e.instance_of?(Array) }.
flatten(1)
end
# Consistent handling of empty lists, when we act on a named result
return [] if named && list.empty?
# If there are only strings, concatenate them and return that.
foldl(list.compact) { |s,e| s+e }
end
|
[
"def",
"flatten_repetition",
"(",
"list",
",",
"named",
")",
"if",
"list",
".",
"any?",
"{",
"|",
"e",
"|",
"e",
".",
"instance_of?",
"(",
"Hash",
")",
"}",
"# If keyed subtrees are in the array, we'll want to discard all ",
"# strings inbetween. To keep them, name them. ",
"return",
"list",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"instance_of?",
"(",
"Hash",
")",
"}",
"end",
"if",
"list",
".",
"any?",
"{",
"|",
"e",
"|",
"e",
".",
"instance_of?",
"(",
"Array",
")",
"}",
"# If any arrays are nested in this array, flatten all arrays to this",
"# level. ",
"return",
"list",
".",
"select",
"{",
"|",
"e",
"|",
"e",
".",
"instance_of?",
"(",
"Array",
")",
"}",
".",
"flatten",
"(",
"1",
")",
"end",
"# Consistent handling of empty lists, when we act on a named result ",
"return",
"[",
"]",
"if",
"named",
"&&",
"list",
".",
"empty?",
"# If there are only strings, concatenate them and return that. ",
"foldl",
"(",
"list",
".",
"compact",
")",
"{",
"|",
"s",
",",
"e",
"|",
"s",
"+",
"e",
"}",
"end"
] |
Flatten results from a repetition of a single parslet. named indicates
whether the user has named the result or not. If the user has named
the results, we want to leave an empty list alone - otherwise it is
turned into an empty string.
@api private
|
[
"Flatten",
"results",
"from",
"a",
"repetition",
"of",
"a",
"single",
"parslet",
".",
"named",
"indicates",
"whether",
"the",
"user",
"has",
"named",
"the",
"result",
"or",
"not",
".",
"If",
"the",
"user",
"has",
"named",
"the",
"results",
"we",
"want",
"to",
"leave",
"an",
"empty",
"list",
"alone",
"-",
"otherwise",
"it",
"is",
"turned",
"into",
"an",
"empty",
"string",
"."
] |
b108758d76c51a1630f3b13c8f47dcd6637c5477
|
https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/atoms/can_flatten.rb#L104-L124
|
16,726
|
kschiess/parslet
|
lib/parslet.rb
|
Parslet.ClassMethods.rule
|
def rule(name, opts={}, &definition)
undef_method name if method_defined? name
define_method(name) do
@rules ||= {} # <name, rule> memoization
return @rules[name] if @rules.has_key?(name)
# Capture the self of the parser class along with the definition.
definition_closure = proc {
self.instance_eval(&definition)
}
@rules[name] = Atoms::Entity.new(name, opts[:label], &definition_closure)
end
end
|
ruby
|
def rule(name, opts={}, &definition)
undef_method name if method_defined? name
define_method(name) do
@rules ||= {} # <name, rule> memoization
return @rules[name] if @rules.has_key?(name)
# Capture the self of the parser class along with the definition.
definition_closure = proc {
self.instance_eval(&definition)
}
@rules[name] = Atoms::Entity.new(name, opts[:label], &definition_closure)
end
end
|
[
"def",
"rule",
"(",
"name",
",",
"opts",
"=",
"{",
"}",
",",
"&",
"definition",
")",
"undef_method",
"name",
"if",
"method_defined?",
"name",
"define_method",
"(",
"name",
")",
"do",
"@rules",
"||=",
"{",
"}",
"# <name, rule> memoization",
"return",
"@rules",
"[",
"name",
"]",
"if",
"@rules",
".",
"has_key?",
"(",
"name",
")",
"# Capture the self of the parser class along with the definition.",
"definition_closure",
"=",
"proc",
"{",
"self",
".",
"instance_eval",
"(",
"definition",
")",
"}",
"@rules",
"[",
"name",
"]",
"=",
"Atoms",
"::",
"Entity",
".",
"new",
"(",
"name",
",",
"opts",
"[",
":label",
"]",
",",
"definition_closure",
")",
"end",
"end"
] |
Define an entity for the parser. This generates a method of the same
name that can be used as part of other patterns. Those methods can be
freely mixed in your parser class with real ruby methods.
class MyParser
include Parslet
rule(:bar) { str('bar') }
rule(:twobar) do
bar >> bar
end
root :twobar
end
|
[
"Define",
"an",
"entity",
"for",
"the",
"parser",
".",
"This",
"generates",
"a",
"method",
"of",
"the",
"same",
"name",
"that",
"can",
"be",
"used",
"as",
"part",
"of",
"other",
"patterns",
".",
"Those",
"methods",
"can",
"be",
"freely",
"mixed",
"in",
"your",
"parser",
"class",
"with",
"real",
"ruby",
"methods",
"."
] |
b108758d76c51a1630f3b13c8f47dcd6637c5477
|
https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet.rb#L102-L115
|
16,727
|
kschiess/parslet
|
lib/parslet/cause.rb
|
Parslet.Cause.raise
|
def raise(exception_klass=Parslet::ParseFailed)
exception = exception_klass.new(self.to_s, self)
Kernel.raise exception
end
|
ruby
|
def raise(exception_klass=Parslet::ParseFailed)
exception = exception_klass.new(self.to_s, self)
Kernel.raise exception
end
|
[
"def",
"raise",
"(",
"exception_klass",
"=",
"Parslet",
"::",
"ParseFailed",
")",
"exception",
"=",
"exception_klass",
".",
"new",
"(",
"self",
".",
"to_s",
",",
"self",
")",
"Kernel",
".",
"raise",
"exception",
"end"
] |
Signals to the outside that the parse has failed. Use this in
conjunction with .format for nice error messages.
|
[
"Signals",
"to",
"the",
"outside",
"that",
"the",
"parse",
"has",
"failed",
".",
"Use",
"this",
"in",
"conjunction",
"with",
".",
"format",
"for",
"nice",
"error",
"messages",
"."
] |
b108758d76c51a1630f3b13c8f47dcd6637c5477
|
https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/cause.rb#L68-L71
|
16,728
|
kschiess/parslet
|
lib/parslet/source.rb
|
Parslet.Source.consume
|
def consume(n)
position = self.pos
slice_str = @str.scan(@re_cache[n])
slice = Parslet::Slice.new(
position,
slice_str,
@line_cache)
return slice
end
|
ruby
|
def consume(n)
position = self.pos
slice_str = @str.scan(@re_cache[n])
slice = Parslet::Slice.new(
position,
slice_str,
@line_cache)
return slice
end
|
[
"def",
"consume",
"(",
"n",
")",
"position",
"=",
"self",
".",
"pos",
"slice_str",
"=",
"@str",
".",
"scan",
"(",
"@re_cache",
"[",
"n",
"]",
")",
"slice",
"=",
"Parslet",
"::",
"Slice",
".",
"new",
"(",
"position",
",",
"slice_str",
",",
"@line_cache",
")",
"return",
"slice",
"end"
] |
Consumes n characters from the input, returning them as a slice of the
input.
|
[
"Consumes",
"n",
"characters",
"from",
"the",
"input",
"returning",
"them",
"as",
"a",
"slice",
"of",
"the",
"input",
"."
] |
b108758d76c51a1630f3b13c8f47dcd6637c5477
|
https://github.com/kschiess/parslet/blob/b108758d76c51a1630f3b13c8f47dcd6637c5477/lib/parslet/source.rb#L41-L50
|
16,729
|
nesaulov/surrealist
|
lib/surrealist/builder.rb
|
Surrealist.Builder.construct_collection
|
def construct_collection(schema, instance, key, value)
schema[key] = instance.send(key).map do |inst|
call(Copier.deep_copy(value), inst)
end
end
|
ruby
|
def construct_collection(schema, instance, key, value)
schema[key] = instance.send(key).map do |inst|
call(Copier.deep_copy(value), inst)
end
end
|
[
"def",
"construct_collection",
"(",
"schema",
",",
"instance",
",",
"key",
",",
"value",
")",
"schema",
"[",
"key",
"]",
"=",
"instance",
".",
"send",
"(",
"key",
")",
".",
"map",
"do",
"|",
"inst",
"|",
"call",
"(",
"Copier",
".",
"deep_copy",
"(",
"value",
")",
",",
"inst",
")",
"end",
"end"
] |
Makes the value of appropriate key of the schema an array and pushes in results of iterating through
records and surrealizing them
@param [Hash] schema the schema defined in the object's class.
@param [Object] instance the instance of the object which methods from the schema are called on.
@param [Symbol] key the symbol that represents method on the instance
@param [Any] value returned when key is called on instance
@return [Hash] the schema hash
|
[
"Makes",
"the",
"value",
"of",
"appropriate",
"key",
"of",
"the",
"schema",
"an",
"array",
"and",
"pushes",
"in",
"results",
"of",
"iterating",
"through",
"records",
"and",
"surrealizing",
"them"
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/builder.rb#L81-L85
|
16,730
|
nesaulov/surrealist
|
lib/surrealist/instance_methods.rb
|
Surrealist.InstanceMethods.surrealize
|
def surrealize(**args)
return args[:serializer].new(self).surrealize(args) if args[:serializer]
if (serializer = find_serializer(args[:for]))
return serializer.new(self).surrealize(args)
end
Oj.dump(Surrealist.build_schema(instance: self, **args), mode: :compat)
end
|
ruby
|
def surrealize(**args)
return args[:serializer].new(self).surrealize(args) if args[:serializer]
if (serializer = find_serializer(args[:for]))
return serializer.new(self).surrealize(args)
end
Oj.dump(Surrealist.build_schema(instance: self, **args), mode: :compat)
end
|
[
"def",
"surrealize",
"(",
"**",
"args",
")",
"return",
"args",
"[",
":serializer",
"]",
".",
"new",
"(",
"self",
")",
".",
"surrealize",
"(",
"args",
")",
"if",
"args",
"[",
":serializer",
"]",
"if",
"(",
"serializer",
"=",
"find_serializer",
"(",
"args",
"[",
":for",
"]",
")",
")",
"return",
"serializer",
".",
"new",
"(",
"self",
")",
".",
"surrealize",
"(",
"args",
")",
"end",
"Oj",
".",
"dump",
"(",
"Surrealist",
".",
"build_schema",
"(",
"instance",
":",
"self",
",",
"**",
"args",
")",
",",
"mode",
":",
":compat",
")",
"end"
] |
Dumps the object's methods corresponding to the schema
provided in the object's class and type-checks the values.
@param [Boolean] [optional] camelize optional argument for converting hash to camelBack.
@param [Boolean] [optional] include_root optional argument for having the root key of the resulting hash
as instance's class name.
@param [Boolean] [optional] include_namespaces optional argument for having root key as a nested hash of
instance's namespaces. Animal::Cat.new.surrealize -> (animal: { cat: { weight: '3 kilos' } })
@param [String] [optional] root optional argument for using a specified root key for the hash
@param [Integer] [optional] namespaces_nesting_level level of namespaces nesting.
@return [String] a json-formatted string corresponding to the schema
provided in the object's class. Values will be taken from the return values
of appropriate methods from the object.
@raise +Surrealist::UnknownSchemaError+ if no schema was provided in the object's class.
@raise +Surrealist::InvalidTypeError+ if type-check failed at some point.
@raise +Surrealist::UndefinedMethodError+ if a key defined in the schema
does not have a corresponding method on the object.
@example Define a schema and surrealize the object
class User
include Surrealist
json_schema do
{
name: String,
age: Integer,
}
end
def name
'Nikita'
end
def age
23
end
end
User.new.surrealize
# => "{\"name\":\"Nikita\",\"age\":23}"
# For more examples see README
|
[
"Dumps",
"the",
"object",
"s",
"methods",
"corresponding",
"to",
"the",
"schema",
"provided",
"in",
"the",
"object",
"s",
"class",
"and",
"type",
"-",
"checks",
"the",
"values",
"."
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/instance_methods.rb#L51-L59
|
16,731
|
nesaulov/surrealist
|
lib/surrealist/instance_methods.rb
|
Surrealist.InstanceMethods.build_schema
|
def build_schema(**args)
return args[:serializer].new(self).build_schema(args) if args[:serializer]
if (serializer = find_serializer(args[:for]))
return serializer.new(self).build_schema(args)
end
Surrealist.build_schema(instance: self, **args)
end
|
ruby
|
def build_schema(**args)
return args[:serializer].new(self).build_schema(args) if args[:serializer]
if (serializer = find_serializer(args[:for]))
return serializer.new(self).build_schema(args)
end
Surrealist.build_schema(instance: self, **args)
end
|
[
"def",
"build_schema",
"(",
"**",
"args",
")",
"return",
"args",
"[",
":serializer",
"]",
".",
"new",
"(",
"self",
")",
".",
"build_schema",
"(",
"args",
")",
"if",
"args",
"[",
":serializer",
"]",
"if",
"(",
"serializer",
"=",
"find_serializer",
"(",
"args",
"[",
":for",
"]",
")",
")",
"return",
"serializer",
".",
"new",
"(",
"self",
")",
".",
"build_schema",
"(",
"args",
")",
"end",
"Surrealist",
".",
"build_schema",
"(",
"instance",
":",
"self",
",",
"**",
"args",
")",
"end"
] |
Invokes +Surrealist+'s class method +build_schema+
|
[
"Invokes",
"+",
"Surrealist",
"+",
"s",
"class",
"method",
"+",
"build_schema",
"+"
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/instance_methods.rb#L62-L70
|
16,732
|
nesaulov/surrealist
|
lib/surrealist/serializer.rb
|
Surrealist.Serializer.build_schema
|
def build_schema(**args)
if Helper.collection?(object)
build_collection_schema(args)
else
Surrealist.build_schema(instance: self, **args)
end
end
|
ruby
|
def build_schema(**args)
if Helper.collection?(object)
build_collection_schema(args)
else
Surrealist.build_schema(instance: self, **args)
end
end
|
[
"def",
"build_schema",
"(",
"**",
"args",
")",
"if",
"Helper",
".",
"collection?",
"(",
"object",
")",
"build_collection_schema",
"(",
"args",
")",
"else",
"Surrealist",
".",
"build_schema",
"(",
"instance",
":",
"self",
",",
"**",
"args",
")",
"end",
"end"
] |
Passes build_schema to Surrealist
|
[
"Passes",
"build_schema",
"to",
"Surrealist"
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/serializer.rb#L91-L97
|
16,733
|
nesaulov/surrealist
|
lib/surrealist/serializer.rb
|
Surrealist.Serializer.build_collection_schema
|
def build_collection_schema(**args)
object.map { |object| self.class.new(object, context).build_schema(args) }
end
|
ruby
|
def build_collection_schema(**args)
object.map { |object| self.class.new(object, context).build_schema(args) }
end
|
[
"def",
"build_collection_schema",
"(",
"**",
"args",
")",
"object",
".",
"map",
"{",
"|",
"object",
"|",
"self",
".",
"class",
".",
"new",
"(",
"object",
",",
"context",
")",
".",
"build_schema",
"(",
"args",
")",
"}",
"end"
] |
Maps collection and builds schema for each instance.
|
[
"Maps",
"collection",
"and",
"builds",
"schema",
"for",
"each",
"instance",
"."
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/serializer.rb#L104-L106
|
16,734
|
nesaulov/surrealist
|
lib/surrealist/carrier.rb
|
Surrealist.Carrier.parameters
|
def parameters
{ camelize: camelize, include_root: include_root, include_namespaces: include_namespaces,
root: root, namespaces_nesting_level: namespaces_nesting_level }
end
|
ruby
|
def parameters
{ camelize: camelize, include_root: include_root, include_namespaces: include_namespaces,
root: root, namespaces_nesting_level: namespaces_nesting_level }
end
|
[
"def",
"parameters",
"{",
"camelize",
":",
"camelize",
",",
"include_root",
":",
"include_root",
",",
"include_namespaces",
":",
"include_namespaces",
",",
"root",
":",
"root",
",",
"namespaces_nesting_level",
":",
"namespaces_nesting_level",
"}",
"end"
] |
Returns all arguments
@return [Hash]
|
[
"Returns",
"all",
"arguments"
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/carrier.rb#L55-L58
|
16,735
|
nesaulov/surrealist
|
lib/surrealist/carrier.rb
|
Surrealist.Carrier.check_booleans!
|
def check_booleans!
booleans_hash.each do |key, value|
unless BOOLEANS.include?(value)
raise ArgumentError, "Expected `#{key}` to be either true, false or nil, got #{value}"
end
end
end
|
ruby
|
def check_booleans!
booleans_hash.each do |key, value|
unless BOOLEANS.include?(value)
raise ArgumentError, "Expected `#{key}` to be either true, false or nil, got #{value}"
end
end
end
|
[
"def",
"check_booleans!",
"booleans_hash",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"unless",
"BOOLEANS",
".",
"include?",
"(",
"value",
")",
"raise",
"ArgumentError",
",",
"\"Expected `#{key}` to be either true, false or nil, got #{value}\"",
"end",
"end",
"end"
] |
Checks all boolean arguments
@raise ArgumentError
|
[
"Checks",
"all",
"boolean",
"arguments"
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/carrier.rb#L64-L70
|
16,736
|
nesaulov/surrealist
|
lib/surrealist/carrier.rb
|
Surrealist.Carrier.check_root!
|
def check_root!
unless root.nil? || (root.is_a?(String) && !root.strip.empty?) || root.is_a?(Symbol)
Surrealist::ExceptionRaiser.raise_invalid_root!(root)
end
end
|
ruby
|
def check_root!
unless root.nil? || (root.is_a?(String) && !root.strip.empty?) || root.is_a?(Symbol)
Surrealist::ExceptionRaiser.raise_invalid_root!(root)
end
end
|
[
"def",
"check_root!",
"unless",
"root",
".",
"nil?",
"||",
"(",
"root",
".",
"is_a?",
"(",
"String",
")",
"&&",
"!",
"root",
".",
"strip",
".",
"empty?",
")",
"||",
"root",
".",
"is_a?",
"(",
"Symbol",
")",
"Surrealist",
"::",
"ExceptionRaiser",
".",
"raise_invalid_root!",
"(",
"root",
")",
"end",
"end"
] |
Checks if root is not nil, a non-empty string, or symbol
@raise ArgumentError
|
[
"Checks",
"if",
"root",
"is",
"not",
"nil",
"a",
"non",
"-",
"empty",
"string",
"or",
"symbol"
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/carrier.rb#L87-L91
|
16,737
|
nesaulov/surrealist
|
lib/surrealist/class_methods.rb
|
Surrealist.ClassMethods.delegate_surrealization_to
|
def delegate_surrealization_to(klass)
raise TypeError, "Expected type of Class got #{klass.class} instead" unless klass.is_a?(Class)
Surrealist::ExceptionRaiser.raise_invalid_schema_delegation! unless Helper.surrealist?(klass)
hash = Surrealist::VarsHelper.find_schema(klass)
Surrealist::VarsHelper.set_schema(self, hash)
end
|
ruby
|
def delegate_surrealization_to(klass)
raise TypeError, "Expected type of Class got #{klass.class} instead" unless klass.is_a?(Class)
Surrealist::ExceptionRaiser.raise_invalid_schema_delegation! unless Helper.surrealist?(klass)
hash = Surrealist::VarsHelper.find_schema(klass)
Surrealist::VarsHelper.set_schema(self, hash)
end
|
[
"def",
"delegate_surrealization_to",
"(",
"klass",
")",
"raise",
"TypeError",
",",
"\"Expected type of Class got #{klass.class} instead\"",
"unless",
"klass",
".",
"is_a?",
"(",
"Class",
")",
"Surrealist",
"::",
"ExceptionRaiser",
".",
"raise_invalid_schema_delegation!",
"unless",
"Helper",
".",
"surrealist?",
"(",
"klass",
")",
"hash",
"=",
"Surrealist",
"::",
"VarsHelper",
".",
"find_schema",
"(",
"klass",
")",
"Surrealist",
"::",
"VarsHelper",
".",
"set_schema",
"(",
"self",
",",
"hash",
")",
"end"
] |
A DSL method to delegate schema in a declarative style. Must reference a valid
class that includes Surrealist
@param [Class] klass
@example DSL usage example
class Host
include Surrealist
json_schema do
{ name: String }
end
def name
'Parent'
end
end
class Guest < Host
delegate_surrealization_to Host
def name
'Child'
end
end
Guest.new.surrealize
# => "{\"name\":\"Child\"}"
# For more examples see README
|
[
"A",
"DSL",
"method",
"to",
"delegate",
"schema",
"in",
"a",
"declarative",
"style",
".",
"Must",
"reference",
"a",
"valid",
"class",
"that",
"includes",
"Surrealist"
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/class_methods.rb#L109-L116
|
16,738
|
nesaulov/surrealist
|
lib/surrealist/class_methods.rb
|
Surrealist.ClassMethods.surrealize_with
|
def surrealize_with(klass, tag: Surrealist::VarsHelper::DEFAULT_TAG)
if klass < Surrealist::Serializer
Surrealist::VarsHelper.add_serializer(self, klass, tag: tag)
instance_variable_set(VarsHelper::PARENT_VARIABLE, klass.defined_schema)
else
raise ArgumentError, "#{klass} should be inherited from Surrealist::Serializer"
end
end
|
ruby
|
def surrealize_with(klass, tag: Surrealist::VarsHelper::DEFAULT_TAG)
if klass < Surrealist::Serializer
Surrealist::VarsHelper.add_serializer(self, klass, tag: tag)
instance_variable_set(VarsHelper::PARENT_VARIABLE, klass.defined_schema)
else
raise ArgumentError, "#{klass} should be inherited from Surrealist::Serializer"
end
end
|
[
"def",
"surrealize_with",
"(",
"klass",
",",
"tag",
":",
"Surrealist",
"::",
"VarsHelper",
"::",
"DEFAULT_TAG",
")",
"if",
"klass",
"<",
"Surrealist",
"::",
"Serializer",
"Surrealist",
"::",
"VarsHelper",
".",
"add_serializer",
"(",
"self",
",",
"klass",
",",
"tag",
":",
"tag",
")",
"instance_variable_set",
"(",
"VarsHelper",
"::",
"PARENT_VARIABLE",
",",
"klass",
".",
"defined_schema",
")",
"else",
"raise",
"ArgumentError",
",",
"\"#{klass} should be inherited from Surrealist::Serializer\"",
"end",
"end"
] |
A DSL method for defining a class that holds serialization logic.
@param [Class] klass a class that should inherit form Surrealist::Serializer
@raise ArgumentError if Surrealist::Serializer is not found in the ancestors chain
|
[
"A",
"DSL",
"method",
"for",
"defining",
"a",
"class",
"that",
"holds",
"serialization",
"logic",
"."
] |
428b44043b879571be03fbab1f3e1800b939fc5e
|
https://github.com/nesaulov/surrealist/blob/428b44043b879571be03fbab1f3e1800b939fc5e/lib/surrealist/class_methods.rb#L123-L130
|
16,739
|
contribsys/faktory_worker_ruby
|
lib/faktory/client.rb
|
Faktory.Client.fetch
|
def fetch(*queues)
job = nil
transaction do
command("FETCH", *queues)
job = result!
end
JSON.parse(job) if job
end
|
ruby
|
def fetch(*queues)
job = nil
transaction do
command("FETCH", *queues)
job = result!
end
JSON.parse(job) if job
end
|
[
"def",
"fetch",
"(",
"*",
"queues",
")",
"job",
"=",
"nil",
"transaction",
"do",
"command",
"(",
"\"FETCH\"",
",",
"queues",
")",
"job",
"=",
"result!",
"end",
"JSON",
".",
"parse",
"(",
"job",
")",
"if",
"job",
"end"
] |
Returns either a job hash or falsy.
|
[
"Returns",
"either",
"a",
"job",
"hash",
"or",
"falsy",
"."
] |
8b9e4fe278886fba6b8a251ccd5342dd61038ba5
|
https://github.com/contribsys/faktory_worker_ruby/blob/8b9e4fe278886fba6b8a251ccd5342dd61038ba5/lib/faktory/client.rb#L83-L90
|
16,740
|
contribsys/faktory_worker_ruby
|
lib/faktory/client.rb
|
Faktory.Client.beat
|
def beat
transaction do
command("BEAT", %Q[{"wid":"#{@@random_process_wid}"}])
str = result!
if str == "OK"
str
else
hash = JSON.parse(str)
hash["state"]
end
end
end
|
ruby
|
def beat
transaction do
command("BEAT", %Q[{"wid":"#{@@random_process_wid}"}])
str = result!
if str == "OK"
str
else
hash = JSON.parse(str)
hash["state"]
end
end
end
|
[
"def",
"beat",
"transaction",
"do",
"command",
"(",
"\"BEAT\"",
",",
"%Q[{\"wid\":\"#{@@random_process_wid}\"}]",
")",
"str",
"=",
"result!",
"if",
"str",
"==",
"\"OK\"",
"str",
"else",
"hash",
"=",
"JSON",
".",
"parse",
"(",
"str",
")",
"hash",
"[",
"\"state\"",
"]",
"end",
"end",
"end"
] |
Sends a heartbeat to the server, in order to prove this
worker process is still alive.
Return a string signal to process, legal values are "quiet" or "terminate".
The quiet signal is informative: the server won't allow this process to FETCH
any more jobs anyways.
|
[
"Sends",
"a",
"heartbeat",
"to",
"the",
"server",
"in",
"order",
"to",
"prove",
"this",
"worker",
"process",
"is",
"still",
"alive",
"."
] |
8b9e4fe278886fba6b8a251ccd5342dd61038ba5
|
https://github.com/contribsys/faktory_worker_ruby/blob/8b9e4fe278886fba6b8a251ccd5342dd61038ba5/lib/faktory/client.rb#L115-L126
|
16,741
|
excid3/simple_discussion
|
lib/simple_discussion/will_paginate.rb
|
SimpleDiscussion.BootstrapLinkRenderer.url
|
def url(page)
@base_url_params ||= begin
url_params = merge_get_params(default_url_params)
merge_optional_params(url_params)
end
url_params = @base_url_params.dup
add_current_page_param(url_params, page)
# Add optional url_builder support
(@options[:url_builder] || @template).url_for(url_params)
end
|
ruby
|
def url(page)
@base_url_params ||= begin
url_params = merge_get_params(default_url_params)
merge_optional_params(url_params)
end
url_params = @base_url_params.dup
add_current_page_param(url_params, page)
# Add optional url_builder support
(@options[:url_builder] || @template).url_for(url_params)
end
|
[
"def",
"url",
"(",
"page",
")",
"@base_url_params",
"||=",
"begin",
"url_params",
"=",
"merge_get_params",
"(",
"default_url_params",
")",
"merge_optional_params",
"(",
"url_params",
")",
"end",
"url_params",
"=",
"@base_url_params",
".",
"dup",
"add_current_page_param",
"(",
"url_params",
",",
"page",
")",
"# Add optional url_builder support",
"(",
"@options",
"[",
":url_builder",
"]",
"||",
"@template",
")",
".",
"url_for",
"(",
"url_params",
")",
"end"
] |
This method adds the `url_builder` option so we can pass in the
mounted Rails engine's scope for will_paginate
|
[
"This",
"method",
"adds",
"the",
"url_builder",
"option",
"so",
"we",
"can",
"pass",
"in",
"the",
"mounted",
"Rails",
"engine",
"s",
"scope",
"for",
"will_paginate"
] |
a14181e7eceb64fc69becb2a8f350963f20ed0ff
|
https://github.com/excid3/simple_discussion/blob/a14181e7eceb64fc69becb2a8f350963f20ed0ff/lib/simple_discussion/will_paginate.rb#L13-L24
|
16,742
|
PierreRambaud/gemirro
|
lib/gemirro/source.rb
|
Gemirro.Source.fetch_prerelease_versions
|
def fetch_prerelease_versions
Utils.logger.info(
"Fetching #{Configuration.prerelease_versions_file}" \
" on #{@name} (#{@host})"
)
Http.get(host + '/' + Configuration.prerelease_versions_file).body
end
|
ruby
|
def fetch_prerelease_versions
Utils.logger.info(
"Fetching #{Configuration.prerelease_versions_file}" \
" on #{@name} (#{@host})"
)
Http.get(host + '/' + Configuration.prerelease_versions_file).body
end
|
[
"def",
"fetch_prerelease_versions",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Fetching #{Configuration.prerelease_versions_file}\"",
"\" on #{@name} (#{@host})\"",
")",
"Http",
".",
"get",
"(",
"host",
"+",
"'/'",
"+",
"Configuration",
".",
"prerelease_versions_file",
")",
".",
"body",
"end"
] |
Fetches a list of all the available Gems and their versions.
@return [String]
|
[
"Fetches",
"a",
"list",
"of",
"all",
"the",
"available",
"Gems",
"and",
"their",
"versions",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/source.rb#L45-L51
|
16,743
|
PierreRambaud/gemirro
|
lib/gemirro/mirror_directory.rb
|
Gemirro.MirrorDirectory.add_file
|
def add_file(name, content)
full_path = File.join(@path, name)
file = MirrorFile.new(full_path)
file.write(content)
file
end
|
ruby
|
def add_file(name, content)
full_path = File.join(@path, name)
file = MirrorFile.new(full_path)
file.write(content)
file
end
|
[
"def",
"add_file",
"(",
"name",
",",
"content",
")",
"full_path",
"=",
"File",
".",
"join",
"(",
"@path",
",",
"name",
")",
"file",
"=",
"MirrorFile",
".",
"new",
"(",
"full_path",
")",
"file",
".",
"write",
"(",
"content",
")",
"file",
"end"
] |
Creates a new file with the given name and content.
@param [String] name
@param [String] content
@return [Gem::MirrorFile]
|
[
"Creates",
"a",
"new",
"file",
"with",
"the",
"given",
"name",
"and",
"content",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/mirror_directory.rb#L39-L46
|
16,744
|
PierreRambaud/gemirro
|
lib/gemirro/gems_fetcher.rb
|
Gemirro.GemsFetcher.versions_for
|
def versions_for(gem)
available = @versions_file.versions_for(gem.name)
return [available.last] if gem.only_latest?
versions = available.select do |v|
gem.requirement.satisfied_by?(v[0])
end
versions = [available.last] if versions.empty?
versions
end
|
ruby
|
def versions_for(gem)
available = @versions_file.versions_for(gem.name)
return [available.last] if gem.only_latest?
versions = available.select do |v|
gem.requirement.satisfied_by?(v[0])
end
versions = [available.last] if versions.empty?
versions
end
|
[
"def",
"versions_for",
"(",
"gem",
")",
"available",
"=",
"@versions_file",
".",
"versions_for",
"(",
"gem",
".",
"name",
")",
"return",
"[",
"available",
".",
"last",
"]",
"if",
"gem",
".",
"only_latest?",
"versions",
"=",
"available",
".",
"select",
"do",
"|",
"v",
"|",
"gem",
".",
"requirement",
".",
"satisfied_by?",
"(",
"v",
"[",
"0",
"]",
")",
"end",
"versions",
"=",
"[",
"available",
".",
"last",
"]",
"if",
"versions",
".",
"empty?",
"versions",
"end"
] |
Returns an Array containing the versions that should be fetched for a
Gem.
@param [Gemirro::Gem] gem
@return [Array]
|
[
"Returns",
"an",
"Array",
"containing",
"the",
"versions",
"that",
"should",
"be",
"fetched",
"for",
"a",
"Gem",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gems_fetcher.rb#L55-L66
|
16,745
|
PierreRambaud/gemirro
|
lib/gemirro/gems_fetcher.rb
|
Gemirro.GemsFetcher.fetch_gemspec
|
def fetch_gemspec(gem, version)
filename = gem.gemspec_filename(version)
satisfied = if gem.only_latest?
true
else
gem.requirement.satisfied_by?(version)
end
if gemspec_exists?(filename) || !satisfied
Utils.logger.debug("Skipping #{filename}")
return
end
Utils.logger.info("Fetching #{filename}")
fetch_from_source(filename, gem, version, true)
end
|
ruby
|
def fetch_gemspec(gem, version)
filename = gem.gemspec_filename(version)
satisfied = if gem.only_latest?
true
else
gem.requirement.satisfied_by?(version)
end
if gemspec_exists?(filename) || !satisfied
Utils.logger.debug("Skipping #{filename}")
return
end
Utils.logger.info("Fetching #{filename}")
fetch_from_source(filename, gem, version, true)
end
|
[
"def",
"fetch_gemspec",
"(",
"gem",
",",
"version",
")",
"filename",
"=",
"gem",
".",
"gemspec_filename",
"(",
"version",
")",
"satisfied",
"=",
"if",
"gem",
".",
"only_latest?",
"true",
"else",
"gem",
".",
"requirement",
".",
"satisfied_by?",
"(",
"version",
")",
"end",
"if",
"gemspec_exists?",
"(",
"filename",
")",
"||",
"!",
"satisfied",
"Utils",
".",
"logger",
".",
"debug",
"(",
"\"Skipping #{filename}\"",
")",
"return",
"end",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Fetching #{filename}\"",
")",
"fetch_from_source",
"(",
"filename",
",",
"gem",
",",
"version",
",",
"true",
")",
"end"
] |
Tries to download gemspec from a given name and version
@param [Gemirro::Gem] gem
@param [Gem::Version] version
@return [String]
|
[
"Tries",
"to",
"download",
"gemspec",
"from",
"a",
"given",
"name",
"and",
"version"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gems_fetcher.rb#L75-L90
|
16,746
|
PierreRambaud/gemirro
|
lib/gemirro/gems_fetcher.rb
|
Gemirro.GemsFetcher.fetch_gem
|
def fetch_gem(gem, version)
filename = gem.filename(version)
satisfied = if gem.only_latest?
true
else
gem.requirement.satisfied_by?(version)
end
name = gem.name
if gem_exists?(filename) || ignore_gem?(name, version, gem.platform) ||
!satisfied
Utils.logger.debug("Skipping #{filename}")
return
end
Utils.configuration.ignore_gem(gem.name, version, gem.platform)
Utils.logger.info("Fetching #{filename}")
fetch_from_source(filename, gem, version)
end
|
ruby
|
def fetch_gem(gem, version)
filename = gem.filename(version)
satisfied = if gem.only_latest?
true
else
gem.requirement.satisfied_by?(version)
end
name = gem.name
if gem_exists?(filename) || ignore_gem?(name, version, gem.platform) ||
!satisfied
Utils.logger.debug("Skipping #{filename}")
return
end
Utils.configuration.ignore_gem(gem.name, version, gem.platform)
Utils.logger.info("Fetching #{filename}")
fetch_from_source(filename, gem, version)
end
|
[
"def",
"fetch_gem",
"(",
"gem",
",",
"version",
")",
"filename",
"=",
"gem",
".",
"filename",
"(",
"version",
")",
"satisfied",
"=",
"if",
"gem",
".",
"only_latest?",
"true",
"else",
"gem",
".",
"requirement",
".",
"satisfied_by?",
"(",
"version",
")",
"end",
"name",
"=",
"gem",
".",
"name",
"if",
"gem_exists?",
"(",
"filename",
")",
"||",
"ignore_gem?",
"(",
"name",
",",
"version",
",",
"gem",
".",
"platform",
")",
"||",
"!",
"satisfied",
"Utils",
".",
"logger",
".",
"debug",
"(",
"\"Skipping #{filename}\"",
")",
"return",
"end",
"Utils",
".",
"configuration",
".",
"ignore_gem",
"(",
"gem",
".",
"name",
",",
"version",
",",
"gem",
".",
"platform",
")",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Fetching #{filename}\"",
")",
"fetch_from_source",
"(",
"filename",
",",
"gem",
",",
"version",
")",
"end"
] |
Tries to download the gem file from a given nam and version
@param [Gemirro::Gem] gem
@param [Gem::Version] version
@return [String]
|
[
"Tries",
"to",
"download",
"the",
"gem",
"file",
"from",
"a",
"given",
"nam",
"and",
"version"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gems_fetcher.rb#L99-L118
|
16,747
|
PierreRambaud/gemirro
|
lib/gemirro/versions_fetcher.rb
|
Gemirro.VersionsFetcher.read_file
|
def read_file(file, prerelease = false)
destination = Gemirro.configuration.destination
file_dst = File.join(destination, file)
unless File.exist?(file_dst)
File.write(file_dst, @source.fetch_versions) unless prerelease
File.write(file_dst, @source.fetch_prerelease_versions) if prerelease
end
File.read(file_dst)
end
|
ruby
|
def read_file(file, prerelease = false)
destination = Gemirro.configuration.destination
file_dst = File.join(destination, file)
unless File.exist?(file_dst)
File.write(file_dst, @source.fetch_versions) unless prerelease
File.write(file_dst, @source.fetch_prerelease_versions) if prerelease
end
File.read(file_dst)
end
|
[
"def",
"read_file",
"(",
"file",
",",
"prerelease",
"=",
"false",
")",
"destination",
"=",
"Gemirro",
".",
"configuration",
".",
"destination",
"file_dst",
"=",
"File",
".",
"join",
"(",
"destination",
",",
"file",
")",
"unless",
"File",
".",
"exist?",
"(",
"file_dst",
")",
"File",
".",
"write",
"(",
"file_dst",
",",
"@source",
".",
"fetch_versions",
")",
"unless",
"prerelease",
"File",
".",
"write",
"(",
"file_dst",
",",
"@source",
".",
"fetch_prerelease_versions",
")",
"if",
"prerelease",
"end",
"File",
".",
"read",
"(",
"file_dst",
")",
"end"
] |
Read file if exists otherwise download its from source
@param [String] file name
@param [TrueClass|FalseClass] prerelease Is prerelease or not
|
[
"Read",
"file",
"if",
"exists",
"otherwise",
"download",
"its",
"from",
"source"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/versions_fetcher.rb#L33-L42
|
16,748
|
PierreRambaud/gemirro
|
lib/gemirro/gem.rb
|
Gemirro.Gem.filename
|
def filename(gem_version = nil)
gem_version ||= version.to_s
n = [name, gem_version]
n.push(@platform) if @platform != 'ruby'
"#{n.join('-')}.gem"
end
|
ruby
|
def filename(gem_version = nil)
gem_version ||= version.to_s
n = [name, gem_version]
n.push(@platform) if @platform != 'ruby'
"#{n.join('-')}.gem"
end
|
[
"def",
"filename",
"(",
"gem_version",
"=",
"nil",
")",
"gem_version",
"||=",
"version",
".",
"to_s",
"n",
"=",
"[",
"name",
",",
"gem_version",
"]",
"n",
".",
"push",
"(",
"@platform",
")",
"if",
"@platform",
"!=",
"'ruby'",
"\"#{n.join('-')}.gem\"",
"end"
] |
Returns the filename of the gem file.
@param [String] gem_version
@return [String]
|
[
"Returns",
"the",
"filename",
"of",
"the",
"gem",
"file",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gem.rb#L87-L92
|
16,749
|
PierreRambaud/gemirro
|
lib/gemirro/gem.rb
|
Gemirro.Gem.gemspec_filename
|
def gemspec_filename(gem_version = nil)
gem_version ||= version.to_s
n = [name, gem_version]
n.push(@platform) if @platform != 'ruby'
"#{n.join('-')}.gemspec.rz"
end
|
ruby
|
def gemspec_filename(gem_version = nil)
gem_version ||= version.to_s
n = [name, gem_version]
n.push(@platform) if @platform != 'ruby'
"#{n.join('-')}.gemspec.rz"
end
|
[
"def",
"gemspec_filename",
"(",
"gem_version",
"=",
"nil",
")",
"gem_version",
"||=",
"version",
".",
"to_s",
"n",
"=",
"[",
"name",
",",
"gem_version",
"]",
"n",
".",
"push",
"(",
"@platform",
")",
"if",
"@platform",
"!=",
"'ruby'",
"\"#{n.join('-')}.gemspec.rz\"",
"end"
] |
Returns the filename of the gemspec file.
@param [String] gem_version
@return [String]
|
[
"Returns",
"the",
"filename",
"of",
"the",
"gemspec",
"file",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gem.rb#L100-L105
|
16,750
|
PierreRambaud/gemirro
|
lib/gemirro/server.rb
|
Gemirro.Server.fetch_gem
|
def fetch_gem(resource)
return unless Utils.configuration.fetch_gem
name = File.basename(resource)
result = name.match(URI_REGEXP)
return unless result
gem_name, gem_version, gem_platform, gem_type = result.captures
return unless gem_name && gem_version
begin
gem = Utils.stored_gem(gem_name, gem_version, gem_platform)
gem.gemspec = true if gem_type == GEMSPEC_TYPE
# rubocop:disable Metrics/LineLength
return if Utils.gems_fetcher.gem_exists?(gem.filename(gem_version)) && gem_type == GEM_TYPE
return if Utils.gems_fetcher.gemspec_exists?(gem.gemspec_filename(gem_version)) && gem_type == GEMSPEC_TYPE
# rubocop:enable Metrics/LineLength
Utils.logger
.info("Try to download #{gem_name} with version #{gem_version}")
Utils.gems_fetcher.source.gems.clear
Utils.gems_fetcher.source.gems.push(gem)
Utils.gems_fetcher.fetch
update_indexes if Utils.configuration.update_on_fetch
rescue StandardError => e
Utils.logger.error(e)
end
end
|
ruby
|
def fetch_gem(resource)
return unless Utils.configuration.fetch_gem
name = File.basename(resource)
result = name.match(URI_REGEXP)
return unless result
gem_name, gem_version, gem_platform, gem_type = result.captures
return unless gem_name && gem_version
begin
gem = Utils.stored_gem(gem_name, gem_version, gem_platform)
gem.gemspec = true if gem_type == GEMSPEC_TYPE
# rubocop:disable Metrics/LineLength
return if Utils.gems_fetcher.gem_exists?(gem.filename(gem_version)) && gem_type == GEM_TYPE
return if Utils.gems_fetcher.gemspec_exists?(gem.gemspec_filename(gem_version)) && gem_type == GEMSPEC_TYPE
# rubocop:enable Metrics/LineLength
Utils.logger
.info("Try to download #{gem_name} with version #{gem_version}")
Utils.gems_fetcher.source.gems.clear
Utils.gems_fetcher.source.gems.push(gem)
Utils.gems_fetcher.fetch
update_indexes if Utils.configuration.update_on_fetch
rescue StandardError => e
Utils.logger.error(e)
end
end
|
[
"def",
"fetch_gem",
"(",
"resource",
")",
"return",
"unless",
"Utils",
".",
"configuration",
".",
"fetch_gem",
"name",
"=",
"File",
".",
"basename",
"(",
"resource",
")",
"result",
"=",
"name",
".",
"match",
"(",
"URI_REGEXP",
")",
"return",
"unless",
"result",
"gem_name",
",",
"gem_version",
",",
"gem_platform",
",",
"gem_type",
"=",
"result",
".",
"captures",
"return",
"unless",
"gem_name",
"&&",
"gem_version",
"begin",
"gem",
"=",
"Utils",
".",
"stored_gem",
"(",
"gem_name",
",",
"gem_version",
",",
"gem_platform",
")",
"gem",
".",
"gemspec",
"=",
"true",
"if",
"gem_type",
"==",
"GEMSPEC_TYPE",
"# rubocop:disable Metrics/LineLength",
"return",
"if",
"Utils",
".",
"gems_fetcher",
".",
"gem_exists?",
"(",
"gem",
".",
"filename",
"(",
"gem_version",
")",
")",
"&&",
"gem_type",
"==",
"GEM_TYPE",
"return",
"if",
"Utils",
".",
"gems_fetcher",
".",
"gemspec_exists?",
"(",
"gem",
".",
"gemspec_filename",
"(",
"gem_version",
")",
")",
"&&",
"gem_type",
"==",
"GEMSPEC_TYPE",
"# rubocop:enable Metrics/LineLength",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Try to download #{gem_name} with version #{gem_version}\"",
")",
"Utils",
".",
"gems_fetcher",
".",
"source",
".",
"gems",
".",
"clear",
"Utils",
".",
"gems_fetcher",
".",
"source",
".",
"gems",
".",
"push",
"(",
"gem",
")",
"Utils",
".",
"gems_fetcher",
".",
"fetch",
"update_indexes",
"if",
"Utils",
".",
"configuration",
".",
"update_on_fetch",
"rescue",
"StandardError",
"=>",
"e",
"Utils",
".",
"logger",
".",
"error",
"(",
"e",
")",
"end",
"end"
] |
Try to fetch gem and download its if it's possible, and
build and install indicies.
@param [String] resource
@return [Indexer]
|
[
"Try",
"to",
"fetch",
"gem",
"and",
"download",
"its",
"if",
"it",
"s",
"possible",
"and",
"build",
"and",
"install",
"indicies",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/server.rb#L129-L157
|
16,751
|
PierreRambaud/gemirro
|
lib/gemirro/server.rb
|
Gemirro.Server.update_indexes
|
def update_indexes
indexer = Gemirro::Indexer.new(Utils.configuration.destination)
indexer.only_origin = true
indexer.ui = ::Gem::SilentUI.new
Utils.logger.info('Generating indexes')
indexer.update_index
indexer.updated_gems.each do |gem|
Utils.cache.flush_key(File.basename(gem))
end
rescue SystemExit => e
Utils.logger.info(e.message)
end
|
ruby
|
def update_indexes
indexer = Gemirro::Indexer.new(Utils.configuration.destination)
indexer.only_origin = true
indexer.ui = ::Gem::SilentUI.new
Utils.logger.info('Generating indexes')
indexer.update_index
indexer.updated_gems.each do |gem|
Utils.cache.flush_key(File.basename(gem))
end
rescue SystemExit => e
Utils.logger.info(e.message)
end
|
[
"def",
"update_indexes",
"indexer",
"=",
"Gemirro",
"::",
"Indexer",
".",
"new",
"(",
"Utils",
".",
"configuration",
".",
"destination",
")",
"indexer",
".",
"only_origin",
"=",
"true",
"indexer",
".",
"ui",
"=",
"::",
"Gem",
"::",
"SilentUI",
".",
"new",
"Utils",
".",
"logger",
".",
"info",
"(",
"'Generating indexes'",
")",
"indexer",
".",
"update_index",
"indexer",
".",
"updated_gems",
".",
"each",
"do",
"|",
"gem",
"|",
"Utils",
".",
"cache",
".",
"flush_key",
"(",
"File",
".",
"basename",
"(",
"gem",
")",
")",
"end",
"rescue",
"SystemExit",
"=>",
"e",
"Utils",
".",
"logger",
".",
"info",
"(",
"e",
".",
"message",
")",
"end"
] |
Update indexes files
@return [Indexer]
|
[
"Update",
"indexes",
"files"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/server.rb#L164-L176
|
16,752
|
PierreRambaud/gemirro
|
lib/gemirro/server.rb
|
Gemirro.Server.query_gems_list
|
def query_gems_list
Utils.gems_collection(false) # load collection
gems = Parallel.map(query_gems, in_threads: 4) do |query_gem|
gem_dependencies(query_gem)
end
gems.flatten!
gems.reject!(&:empty?)
gems
end
|
ruby
|
def query_gems_list
Utils.gems_collection(false) # load collection
gems = Parallel.map(query_gems, in_threads: 4) do |query_gem|
gem_dependencies(query_gem)
end
gems.flatten!
gems.reject!(&:empty?)
gems
end
|
[
"def",
"query_gems_list",
"Utils",
".",
"gems_collection",
"(",
"false",
")",
"# load collection",
"gems",
"=",
"Parallel",
".",
"map",
"(",
"query_gems",
",",
"in_threads",
":",
"4",
")",
"do",
"|",
"query_gem",
"|",
"gem_dependencies",
"(",
"query_gem",
")",
"end",
"gems",
".",
"flatten!",
"gems",
".",
"reject!",
"(",
":empty?",
")",
"gems",
"end"
] |
Return gems list from query params
@return [Array]
|
[
"Return",
"gems",
"list",
"from",
"query",
"params"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/server.rb#L192-L201
|
16,753
|
PierreRambaud/gemirro
|
lib/gemirro/server.rb
|
Gemirro.Server.gem_dependencies
|
def gem_dependencies(gem_name)
Utils.cache.cache(gem_name) do
gems = Utils.gems_collection(false)
gem_collection = gems.find_by_name(gem_name)
return '' if gem_collection.nil?
gem_collection = Parallel.map(gem_collection, in_threads: 4) do |gem|
[gem, spec_for(gem.name, gem.number, gem.platform)]
end
gem_collection.reject! do |_, spec|
spec.nil?
end
Parallel.map(gem_collection, in_threads: 4) do |gem, spec|
dependencies = spec.dependencies.select do |d|
d.type == :runtime
end
dependencies = Parallel.map(dependencies, in_threads: 4) do |d|
[d.name.is_a?(Array) ? d.name.first : d.name, d.requirement.to_s]
end
{
name: gem.name,
number: gem.number,
platform: gem.platform,
dependencies: dependencies
}
end
end
end
|
ruby
|
def gem_dependencies(gem_name)
Utils.cache.cache(gem_name) do
gems = Utils.gems_collection(false)
gem_collection = gems.find_by_name(gem_name)
return '' if gem_collection.nil?
gem_collection = Parallel.map(gem_collection, in_threads: 4) do |gem|
[gem, spec_for(gem.name, gem.number, gem.platform)]
end
gem_collection.reject! do |_, spec|
spec.nil?
end
Parallel.map(gem_collection, in_threads: 4) do |gem, spec|
dependencies = spec.dependencies.select do |d|
d.type == :runtime
end
dependencies = Parallel.map(dependencies, in_threads: 4) do |d|
[d.name.is_a?(Array) ? d.name.first : d.name, d.requirement.to_s]
end
{
name: gem.name,
number: gem.number,
platform: gem.platform,
dependencies: dependencies
}
end
end
end
|
[
"def",
"gem_dependencies",
"(",
"gem_name",
")",
"Utils",
".",
"cache",
".",
"cache",
"(",
"gem_name",
")",
"do",
"gems",
"=",
"Utils",
".",
"gems_collection",
"(",
"false",
")",
"gem_collection",
"=",
"gems",
".",
"find_by_name",
"(",
"gem_name",
")",
"return",
"''",
"if",
"gem_collection",
".",
"nil?",
"gem_collection",
"=",
"Parallel",
".",
"map",
"(",
"gem_collection",
",",
"in_threads",
":",
"4",
")",
"do",
"|",
"gem",
"|",
"[",
"gem",
",",
"spec_for",
"(",
"gem",
".",
"name",
",",
"gem",
".",
"number",
",",
"gem",
".",
"platform",
")",
"]",
"end",
"gem_collection",
".",
"reject!",
"do",
"|",
"_",
",",
"spec",
"|",
"spec",
".",
"nil?",
"end",
"Parallel",
".",
"map",
"(",
"gem_collection",
",",
"in_threads",
":",
"4",
")",
"do",
"|",
"gem",
",",
"spec",
"|",
"dependencies",
"=",
"spec",
".",
"dependencies",
".",
"select",
"do",
"|",
"d",
"|",
"d",
".",
"type",
"==",
":runtime",
"end",
"dependencies",
"=",
"Parallel",
".",
"map",
"(",
"dependencies",
",",
"in_threads",
":",
"4",
")",
"do",
"|",
"d",
"|",
"[",
"d",
".",
"name",
".",
"is_a?",
"(",
"Array",
")",
"?",
"d",
".",
"name",
".",
"first",
":",
"d",
".",
"name",
",",
"d",
".",
"requirement",
".",
"to_s",
"]",
"end",
"{",
"name",
":",
"gem",
".",
"name",
",",
"number",
":",
"gem",
".",
"number",
",",
"platform",
":",
"gem",
".",
"platform",
",",
"dependencies",
":",
"dependencies",
"}",
"end",
"end",
"end"
] |
List of versions and dependencies of each version
from a gem name.
@return [Array]
|
[
"List",
"of",
"versions",
"and",
"dependencies",
"of",
"each",
"version",
"from",
"a",
"gem",
"name",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/server.rb#L209-L240
|
16,754
|
PierreRambaud/gemirro
|
lib/gemirro/indexer.rb
|
Gemirro.Indexer.download_from_source
|
def download_from_source(file)
source_host = Gemirro.configuration.source.host
Utils.logger.info("Download from source: #{file}")
resp = Http.get("#{source_host}/#{File.basename(file)}")
return unless resp.code == 200
resp.body
end
|
ruby
|
def download_from_source(file)
source_host = Gemirro.configuration.source.host
Utils.logger.info("Download from source: #{file}")
resp = Http.get("#{source_host}/#{File.basename(file)}")
return unless resp.code == 200
resp.body
end
|
[
"def",
"download_from_source",
"(",
"file",
")",
"source_host",
"=",
"Gemirro",
".",
"configuration",
".",
"source",
".",
"host",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"Download from source: #{file}\"",
")",
"resp",
"=",
"Http",
".",
"get",
"(",
"\"#{source_host}/#{File.basename(file)}\"",
")",
"return",
"unless",
"resp",
".",
"code",
"==",
"200",
"resp",
".",
"body",
"end"
] |
Download file from source
@param [String] file File path
@return [String]
|
[
"Download",
"file",
"from",
"source"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/indexer.rb#L134-L140
|
16,755
|
PierreRambaud/gemirro
|
lib/gemirro/indexer.rb
|
Gemirro.Indexer.map_gems_to_specs
|
def map_gems_to_specs(gems)
gems.map.with_index do |gemfile, index|
# rubocop:disable Metrics/LineLength
Utils.logger.info("[#{index + 1}/#{gems.size}]: Processing #{gemfile.split('/')[-1]}")
# rubocop:enable Metrics/LineLength
if File.size(gemfile).zero?
Utils.logger.warn("Skipping zero-length gem: #{gemfile}")
next
end
begin
spec = if ::Gem::Package.respond_to? :open
::Gem::Package
.open(File.open(gemfile, 'rb'), 'r', &:metadata)
else
::Gem::Package.new(gemfile).spec
end
spec.loaded_from = gemfile
# HACK: fuck this shit - borks all tests that use pl1
if File.basename(gemfile, '.gem') != spec.original_name
exp = spec.full_name
exp << " (#{spec.original_name})" if
spec.original_name != spec.full_name
msg = "Skipping misnamed gem: #{gemfile} should be named #{exp}"
Utils.logger.warn(msg)
next
end
version = spec.version.version
unless version =~ /^\d+\.\d+\.\d+.*/
msg = "Skipping gem #{spec.full_name} - invalid version #{version}"
Utils.logger.warn(msg)
next
end
if ::Gem::VERSION >= '2.5.0'
spec.abbreviate
spec.sanitize
else
abbreviate spec
sanitize spec
end
spec
rescue SignalException
msg = 'Received signal, exiting'
Utils.logger.error(msg)
raise
rescue StandardError => e
msg = ["Unable to process #{gemfile}",
"#{e.message} (#{e.class})",
"\t#{e.backtrace.join "\n\t"}"].join("\n")
Utils.logger.debug(msg)
end
end.compact
end
|
ruby
|
def map_gems_to_specs(gems)
gems.map.with_index do |gemfile, index|
# rubocop:disable Metrics/LineLength
Utils.logger.info("[#{index + 1}/#{gems.size}]: Processing #{gemfile.split('/')[-1]}")
# rubocop:enable Metrics/LineLength
if File.size(gemfile).zero?
Utils.logger.warn("Skipping zero-length gem: #{gemfile}")
next
end
begin
spec = if ::Gem::Package.respond_to? :open
::Gem::Package
.open(File.open(gemfile, 'rb'), 'r', &:metadata)
else
::Gem::Package.new(gemfile).spec
end
spec.loaded_from = gemfile
# HACK: fuck this shit - borks all tests that use pl1
if File.basename(gemfile, '.gem') != spec.original_name
exp = spec.full_name
exp << " (#{spec.original_name})" if
spec.original_name != spec.full_name
msg = "Skipping misnamed gem: #{gemfile} should be named #{exp}"
Utils.logger.warn(msg)
next
end
version = spec.version.version
unless version =~ /^\d+\.\d+\.\d+.*/
msg = "Skipping gem #{spec.full_name} - invalid version #{version}"
Utils.logger.warn(msg)
next
end
if ::Gem::VERSION >= '2.5.0'
spec.abbreviate
spec.sanitize
else
abbreviate spec
sanitize spec
end
spec
rescue SignalException
msg = 'Received signal, exiting'
Utils.logger.error(msg)
raise
rescue StandardError => e
msg = ["Unable to process #{gemfile}",
"#{e.message} (#{e.class})",
"\t#{e.backtrace.join "\n\t"}"].join("\n")
Utils.logger.debug(msg)
end
end.compact
end
|
[
"def",
"map_gems_to_specs",
"(",
"gems",
")",
"gems",
".",
"map",
".",
"with_index",
"do",
"|",
"gemfile",
",",
"index",
"|",
"# rubocop:disable Metrics/LineLength",
"Utils",
".",
"logger",
".",
"info",
"(",
"\"[#{index + 1}/#{gems.size}]: Processing #{gemfile.split('/')[-1]}\"",
")",
"# rubocop:enable Metrics/LineLength",
"if",
"File",
".",
"size",
"(",
"gemfile",
")",
".",
"zero?",
"Utils",
".",
"logger",
".",
"warn",
"(",
"\"Skipping zero-length gem: #{gemfile}\"",
")",
"next",
"end",
"begin",
"spec",
"=",
"if",
"::",
"Gem",
"::",
"Package",
".",
"respond_to?",
":open",
"::",
"Gem",
"::",
"Package",
".",
"open",
"(",
"File",
".",
"open",
"(",
"gemfile",
",",
"'rb'",
")",
",",
"'r'",
",",
":metadata",
")",
"else",
"::",
"Gem",
"::",
"Package",
".",
"new",
"(",
"gemfile",
")",
".",
"spec",
"end",
"spec",
".",
"loaded_from",
"=",
"gemfile",
"# HACK: fuck this shit - borks all tests that use pl1",
"if",
"File",
".",
"basename",
"(",
"gemfile",
",",
"'.gem'",
")",
"!=",
"spec",
".",
"original_name",
"exp",
"=",
"spec",
".",
"full_name",
"exp",
"<<",
"\" (#{spec.original_name})\"",
"if",
"spec",
".",
"original_name",
"!=",
"spec",
".",
"full_name",
"msg",
"=",
"\"Skipping misnamed gem: #{gemfile} should be named #{exp}\"",
"Utils",
".",
"logger",
".",
"warn",
"(",
"msg",
")",
"next",
"end",
"version",
"=",
"spec",
".",
"version",
".",
"version",
"unless",
"version",
"=~",
"/",
"\\d",
"\\.",
"\\d",
"\\.",
"\\d",
"/",
"msg",
"=",
"\"Skipping gem #{spec.full_name} - invalid version #{version}\"",
"Utils",
".",
"logger",
".",
"warn",
"(",
"msg",
")",
"next",
"end",
"if",
"::",
"Gem",
"::",
"VERSION",
">=",
"'2.5.0'",
"spec",
".",
"abbreviate",
"spec",
".",
"sanitize",
"else",
"abbreviate",
"spec",
"sanitize",
"spec",
"end",
"spec",
"rescue",
"SignalException",
"msg",
"=",
"'Received signal, exiting'",
"Utils",
".",
"logger",
".",
"error",
"(",
"msg",
")",
"raise",
"rescue",
"StandardError",
"=>",
"e",
"msg",
"=",
"[",
"\"Unable to process #{gemfile}\"",
",",
"\"#{e.message} (#{e.class})\"",
",",
"\"\\t#{e.backtrace.join \"\\n\\t\"}\"",
"]",
".",
"join",
"(",
"\"\\n\"",
")",
"Utils",
".",
"logger",
".",
"debug",
"(",
"msg",
")",
"end",
"end",
".",
"compact",
"end"
] |
Map gems file to specs
@param [Array] gems Gems list
@return [Array]
|
[
"Map",
"gems",
"file",
"to",
"specs"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/indexer.rb#L179-L237
|
16,756
|
PierreRambaud/gemirro
|
lib/gemirro/gem_version_collection.rb
|
Gemirro.GemVersionCollection.by_name
|
def by_name(&block)
if @grouped.nil?
@grouped = @gems.group_by(&:name).map do |name, collection|
[name, GemVersionCollection.new(collection)]
end
@grouped.reject! do |name, _collection|
name.nil?
end
@grouped.sort_by! do |name, _collection|
name.downcase
end
end
if block_given?
@grouped.each(&block)
else
@grouped
end
end
|
ruby
|
def by_name(&block)
if @grouped.nil?
@grouped = @gems.group_by(&:name).map do |name, collection|
[name, GemVersionCollection.new(collection)]
end
@grouped.reject! do |name, _collection|
name.nil?
end
@grouped.sort_by! do |name, _collection|
name.downcase
end
end
if block_given?
@grouped.each(&block)
else
@grouped
end
end
|
[
"def",
"by_name",
"(",
"&",
"block",
")",
"if",
"@grouped",
".",
"nil?",
"@grouped",
"=",
"@gems",
".",
"group_by",
"(",
":name",
")",
".",
"map",
"do",
"|",
"name",
",",
"collection",
"|",
"[",
"name",
",",
"GemVersionCollection",
".",
"new",
"(",
"collection",
")",
"]",
"end",
"@grouped",
".",
"reject!",
"do",
"|",
"name",
",",
"_collection",
"|",
"name",
".",
"nil?",
"end",
"@grouped",
".",
"sort_by!",
"do",
"|",
"name",
",",
"_collection",
"|",
"name",
".",
"downcase",
"end",
"end",
"if",
"block_given?",
"@grouped",
".",
"each",
"(",
"block",
")",
"else",
"@grouped",
"end",
"end"
] |
Group gems by name
@param [Proc] block
@return [Array]
|
[
"Group",
"gems",
"by",
"name"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gem_version_collection.rb#L71-L91
|
16,757
|
PierreRambaud/gemirro
|
lib/gemirro/gem_version_collection.rb
|
Gemirro.GemVersionCollection.find_by_name
|
def find_by_name(gemname)
gem = by_name.select do |name, _collection|
name == gemname
end
gem.first.last if gem.any?
end
|
ruby
|
def find_by_name(gemname)
gem = by_name.select do |name, _collection|
name == gemname
end
gem.first.last if gem.any?
end
|
[
"def",
"find_by_name",
"(",
"gemname",
")",
"gem",
"=",
"by_name",
".",
"select",
"do",
"|",
"name",
",",
"_collection",
"|",
"name",
"==",
"gemname",
"end",
"gem",
".",
"first",
".",
"last",
"if",
"gem",
".",
"any?",
"end"
] |
Find gem by name
@param [String] gemname
@return [Array]
|
[
"Find",
"gem",
"by",
"name"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/gem_version_collection.rb#L99-L105
|
16,758
|
PierreRambaud/gemirro
|
lib/gemirro/configuration.rb
|
Gemirro.Configuration.logger_level=
|
def logger_level=(level)
logger.level = LOGGER_LEVEL[level] if LOGGER_LEVEL.key?(level)
logger
end
|
ruby
|
def logger_level=(level)
logger.level = LOGGER_LEVEL[level] if LOGGER_LEVEL.key?(level)
logger
end
|
[
"def",
"logger_level",
"=",
"(",
"level",
")",
"logger",
".",
"level",
"=",
"LOGGER_LEVEL",
"[",
"level",
"]",
"if",
"LOGGER_LEVEL",
".",
"key?",
"(",
"level",
")",
"logger",
"end"
] |
Set log level
@param [string]
@return [Logger]
|
[
"Set",
"log",
"level"
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/configuration.rb#L53-L56
|
16,759
|
PierreRambaud/gemirro
|
lib/gemirro/configuration.rb
|
Gemirro.Configuration.ignore_gem
|
def ignore_gem(name, version, platform)
ignored_gems[platform] ||= {}
ignored_gems[platform][name] ||= []
ignored_gems[platform][name] << version
end
|
ruby
|
def ignore_gem(name, version, platform)
ignored_gems[platform] ||= {}
ignored_gems[platform][name] ||= []
ignored_gems[platform][name] << version
end
|
[
"def",
"ignore_gem",
"(",
"name",
",",
"version",
",",
"platform",
")",
"ignored_gems",
"[",
"platform",
"]",
"||=",
"{",
"}",
"ignored_gems",
"[",
"platform",
"]",
"[",
"name",
"]",
"||=",
"[",
"]",
"ignored_gems",
"[",
"platform",
"]",
"[",
"name",
"]",
"<<",
"version",
"end"
] |
Adds a Gem to the list of Gems to ignore.
@param [String] name
@param [String] version
|
[
"Adds",
"a",
"Gem",
"to",
"the",
"list",
"of",
"Gems",
"to",
"ignore",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/configuration.rb#L174-L178
|
16,760
|
PierreRambaud/gemirro
|
lib/gemirro/configuration.rb
|
Gemirro.Configuration.ignore_gem?
|
def ignore_gem?(name, version, platform)
if ignored_gems[platform][name]
ignored_gems[platform][name].include?(version)
else
false
end
end
|
ruby
|
def ignore_gem?(name, version, platform)
if ignored_gems[platform][name]
ignored_gems[platform][name].include?(version)
else
false
end
end
|
[
"def",
"ignore_gem?",
"(",
"name",
",",
"version",
",",
"platform",
")",
"if",
"ignored_gems",
"[",
"platform",
"]",
"[",
"name",
"]",
"ignored_gems",
"[",
"platform",
"]",
"[",
"name",
"]",
".",
"include?",
"(",
"version",
")",
"else",
"false",
"end",
"end"
] |
Checks if a Gem should be ignored.
@param [String] name
@param [String] version
@return [TrueClass|FalseClass]
|
[
"Checks",
"if",
"a",
"Gem",
"should",
"be",
"ignored",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/configuration.rb#L187-L193
|
16,761
|
PierreRambaud/gemirro
|
lib/gemirro/configuration.rb
|
Gemirro.Configuration.define_source
|
def define_source(name, url, &block)
source = Source.new(name, url)
source.instance_eval(&block)
@source = source
end
|
ruby
|
def define_source(name, url, &block)
source = Source.new(name, url)
source.instance_eval(&block)
@source = source
end
|
[
"def",
"define_source",
"(",
"name",
",",
"url",
",",
"&",
"block",
")",
"source",
"=",
"Source",
".",
"new",
"(",
"name",
",",
"url",
")",
"source",
".",
"instance_eval",
"(",
"block",
")",
"@source",
"=",
"source",
"end"
] |
Define the source to mirror.
@param [String] name
@param [String] url
@param [Proc] block
|
[
"Define",
"the",
"source",
"to",
"mirror",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/configuration.rb#L202-L207
|
16,762
|
PierreRambaud/gemirro
|
lib/gemirro/mirror_file.rb
|
Gemirro.MirrorFile.read
|
def read
handle = File.open(@path, 'r')
content = handle.read
handle.close
content
end
|
ruby
|
def read
handle = File.open(@path, 'r')
content = handle.read
handle.close
content
end
|
[
"def",
"read",
"handle",
"=",
"File",
".",
"open",
"(",
"@path",
",",
"'r'",
")",
"content",
"=",
"handle",
".",
"read",
"handle",
".",
"close",
"content",
"end"
] |
Reads the content of the current file.
@return [String]
|
[
"Reads",
"the",
"content",
"of",
"the",
"current",
"file",
"."
] |
5c6b5abb5334ed3beb256f6764bc336e2cf2dc21
|
https://github.com/PierreRambaud/gemirro/blob/5c6b5abb5334ed3beb256f6764bc336e2cf2dc21/lib/gemirro/mirror_file.rb#L38-L45
|
16,763
|
propublica/upton
|
lib/upton.rb
|
Upton.Scraper.next_index_page_url
|
def next_index_page_url(url, pagination_index)
return url unless @paginated
if pagination_index > @pagination_max_pages
puts "Exceeded pagination limit of #{@pagination_max_pages}" if @verbose
EMPTY_STRING
else
uri = URI.parse(url)
query = uri.query ? Hash[URI.decode_www_form(uri.query)] : {}
# update the pagination query string parameter
query[@pagination_param] = pagination_index
uri.query = URI.encode_www_form(query)
puts "Next index pagination url is #{uri}" if @verbose
uri.to_s
end
end
|
ruby
|
def next_index_page_url(url, pagination_index)
return url unless @paginated
if pagination_index > @pagination_max_pages
puts "Exceeded pagination limit of #{@pagination_max_pages}" if @verbose
EMPTY_STRING
else
uri = URI.parse(url)
query = uri.query ? Hash[URI.decode_www_form(uri.query)] : {}
# update the pagination query string parameter
query[@pagination_param] = pagination_index
uri.query = URI.encode_www_form(query)
puts "Next index pagination url is #{uri}" if @verbose
uri.to_s
end
end
|
[
"def",
"next_index_page_url",
"(",
"url",
",",
"pagination_index",
")",
"return",
"url",
"unless",
"@paginated",
"if",
"pagination_index",
">",
"@pagination_max_pages",
"puts",
"\"Exceeded pagination limit of #{@pagination_max_pages}\"",
"if",
"@verbose",
"EMPTY_STRING",
"else",
"uri",
"=",
"URI",
".",
"parse",
"(",
"url",
")",
"query",
"=",
"uri",
".",
"query",
"?",
"Hash",
"[",
"URI",
".",
"decode_www_form",
"(",
"uri",
".",
"query",
")",
"]",
":",
"{",
"}",
"# update the pagination query string parameter",
"query",
"[",
"@pagination_param",
"]",
"=",
"pagination_index",
"uri",
".",
"query",
"=",
"URI",
".",
"encode_www_form",
"(",
"query",
")",
"puts",
"\"Next index pagination url is #{uri}\"",
"if",
"@verbose",
"uri",
".",
"to_s",
"end",
"end"
] |
Return the next URL to scrape, given the current URL and its index.
Recursion stops if the fetching URL returns an empty string or an error.
If @paginated is not set (the default), this method returns an empty string.
If @paginated is set, this method will return the next pagination URL
to scrape using @pagination_param and the pagination_index.
If the pagination_index is greater than @pagination_max_pages, then the
method will return an empty string.
Override this method to handle pagination is an alternative way
e.g. next_index_page_url("http://whatever.com/articles?page=1", 2)
ought to return "http://whatever.com/articles?page=2"
|
[
"Return",
"the",
"next",
"URL",
"to",
"scrape",
"given",
"the",
"current",
"URL",
"and",
"its",
"index",
"."
] |
29c90206317a6a8327a59f63d8117c56db6395eb
|
https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L149-L164
|
16,764
|
propublica/upton
|
lib/upton.rb
|
Upton.Scraper.scrape_to_csv
|
def scrape_to_csv filename, &blk
require 'csv'
self.url_array = self.get_index unless self.url_array
CSV.open filename, 'wb' do |csv|
#this is a conscious choice: each document is a list of things, either single elements or rows (as lists).
self.scrape_from_list(self.url_array, blk).compact.each do |document|
if document[0].respond_to? :map
document.each{|row| csv << row }
else
csv << document
end
end
#self.scrape_from_list(self.url_array, blk).compact.each{|document| csv << document }
end
end
|
ruby
|
def scrape_to_csv filename, &blk
require 'csv'
self.url_array = self.get_index unless self.url_array
CSV.open filename, 'wb' do |csv|
#this is a conscious choice: each document is a list of things, either single elements or rows (as lists).
self.scrape_from_list(self.url_array, blk).compact.each do |document|
if document[0].respond_to? :map
document.each{|row| csv << row }
else
csv << document
end
end
#self.scrape_from_list(self.url_array, blk).compact.each{|document| csv << document }
end
end
|
[
"def",
"scrape_to_csv",
"filename",
",",
"&",
"blk",
"require",
"'csv'",
"self",
".",
"url_array",
"=",
"self",
".",
"get_index",
"unless",
"self",
".",
"url_array",
"CSV",
".",
"open",
"filename",
",",
"'wb'",
"do",
"|",
"csv",
"|",
"#this is a conscious choice: each document is a list of things, either single elements or rows (as lists).",
"self",
".",
"scrape_from_list",
"(",
"self",
".",
"url_array",
",",
"blk",
")",
".",
"compact",
".",
"each",
"do",
"|",
"document",
"|",
"if",
"document",
"[",
"0",
"]",
".",
"respond_to?",
":map",
"document",
".",
"each",
"{",
"|",
"row",
"|",
"csv",
"<<",
"row",
"}",
"else",
"csv",
"<<",
"document",
"end",
"end",
"#self.scrape_from_list(self.url_array, blk).compact.each{|document| csv << document }",
"end",
"end"
] |
Writes the scraped result to a CSV at the given filename.
|
[
"Writes",
"the",
"scraped",
"result",
"to",
"a",
"CSV",
"at",
"the",
"given",
"filename",
"."
] |
29c90206317a6a8327a59f63d8117c56db6395eb
|
https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L169-L183
|
16,765
|
propublica/upton
|
lib/upton.rb
|
Upton.Scraper.get_page
|
def get_page(url, stash=false, options={})
return EMPTY_STRING if url.nil? || url.empty? #url is nil if the <a> lacks an `href` attribute.
global_options = {
:cache => stash,
:verbose => @verbose
}
if @readable_filenames
global_options[:readable_filenames] = true
end
if @stash_folder
global_options[:readable_filenames] = true
global_options[:cache_location] = @stash_folder
end
resp_and_cache = Downloader.new(url, global_options.merge(options)).get
if resp_and_cache[:from_resource]
puts "sleeping #{@sleep_time_between_requests} secs" if @verbose
sleep @sleep_time_between_requests
end
resp_and_cache[:resp]
end
|
ruby
|
def get_page(url, stash=false, options={})
return EMPTY_STRING if url.nil? || url.empty? #url is nil if the <a> lacks an `href` attribute.
global_options = {
:cache => stash,
:verbose => @verbose
}
if @readable_filenames
global_options[:readable_filenames] = true
end
if @stash_folder
global_options[:readable_filenames] = true
global_options[:cache_location] = @stash_folder
end
resp_and_cache = Downloader.new(url, global_options.merge(options)).get
if resp_and_cache[:from_resource]
puts "sleeping #{@sleep_time_between_requests} secs" if @verbose
sleep @sleep_time_between_requests
end
resp_and_cache[:resp]
end
|
[
"def",
"get_page",
"(",
"url",
",",
"stash",
"=",
"false",
",",
"options",
"=",
"{",
"}",
")",
"return",
"EMPTY_STRING",
"if",
"url",
".",
"nil?",
"||",
"url",
".",
"empty?",
"#url is nil if the <a> lacks an `href` attribute.",
"global_options",
"=",
"{",
":cache",
"=>",
"stash",
",",
":verbose",
"=>",
"@verbose",
"}",
"if",
"@readable_filenames",
"global_options",
"[",
":readable_filenames",
"]",
"=",
"true",
"end",
"if",
"@stash_folder",
"global_options",
"[",
":readable_filenames",
"]",
"=",
"true",
"global_options",
"[",
":cache_location",
"]",
"=",
"@stash_folder",
"end",
"resp_and_cache",
"=",
"Downloader",
".",
"new",
"(",
"url",
",",
"global_options",
".",
"merge",
"(",
"options",
")",
")",
".",
"get",
"if",
"resp_and_cache",
"[",
":from_resource",
"]",
"puts",
"\"sleeping #{@sleep_time_between_requests} secs\"",
"if",
"@verbose",
"sleep",
"@sleep_time_between_requests",
"end",
"resp_and_cache",
"[",
":resp",
"]",
"end"
] |
Handles getting pages with Downlader, which handles stashing.
|
[
"Handles",
"getting",
"pages",
"with",
"Downlader",
"which",
"handles",
"stashing",
"."
] |
29c90206317a6a8327a59f63d8117c56db6395eb
|
https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L206-L225
|
16,766
|
propublica/upton
|
lib/upton.rb
|
Upton.Scraper.get_instance
|
def get_instance(url, pagination_index=0, options={})
resps = [self.get_page(url, @debug, options)]
pagination_index = pagination_index.to_i
prev_url = url
while !resps.last.empty?
next_url = self.next_instance_page_url(url, pagination_index + 1)
break if next_url == prev_url || next_url.empty?
next_resp = self.get_page(next_url, @debug, options)
prev_url = next_url
resps << next_resp
end
resps
end
|
ruby
|
def get_instance(url, pagination_index=0, options={})
resps = [self.get_page(url, @debug, options)]
pagination_index = pagination_index.to_i
prev_url = url
while !resps.last.empty?
next_url = self.next_instance_page_url(url, pagination_index + 1)
break if next_url == prev_url || next_url.empty?
next_resp = self.get_page(next_url, @debug, options)
prev_url = next_url
resps << next_resp
end
resps
end
|
[
"def",
"get_instance",
"(",
"url",
",",
"pagination_index",
"=",
"0",
",",
"options",
"=",
"{",
"}",
")",
"resps",
"=",
"[",
"self",
".",
"get_page",
"(",
"url",
",",
"@debug",
",",
"options",
")",
"]",
"pagination_index",
"=",
"pagination_index",
".",
"to_i",
"prev_url",
"=",
"url",
"while",
"!",
"resps",
".",
"last",
".",
"empty?",
"next_url",
"=",
"self",
".",
"next_instance_page_url",
"(",
"url",
",",
"pagination_index",
"+",
"1",
")",
"break",
"if",
"next_url",
"==",
"prev_url",
"||",
"next_url",
".",
"empty?",
"next_resp",
"=",
"self",
".",
"get_page",
"(",
"next_url",
",",
"@debug",
",",
"options",
")",
"prev_url",
"=",
"next_url",
"resps",
"<<",
"next_resp",
"end",
"resps",
"end"
] |
Returns the instance at `url`.
If the page is stashed, returns that, otherwise, fetches it from the web.
If an instance is paginated, returns the concatenated output of each
page, e.g. if a news article has two pages.
|
[
"Returns",
"the",
"instance",
"at",
"url",
"."
] |
29c90206317a6a8327a59f63d8117c56db6395eb
|
https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L321-L334
|
16,767
|
propublica/upton
|
lib/upton.rb
|
Upton.Scraper.scrape_from_list
|
def scrape_from_list(list, blk)
puts "Scraping #{list.size} instances" if @verbose
list.each_with_index.map do |instance_url, instance_index|
instance_resps = get_instance instance_url, nil, :instance_index => instance_index
instance_resps.each_with_index.map do |instance_resp, pagination_index|
blk.call(instance_resp, instance_url, instance_index, pagination_index)
end
end.flatten(1)
end
|
ruby
|
def scrape_from_list(list, blk)
puts "Scraping #{list.size} instances" if @verbose
list.each_with_index.map do |instance_url, instance_index|
instance_resps = get_instance instance_url, nil, :instance_index => instance_index
instance_resps.each_with_index.map do |instance_resp, pagination_index|
blk.call(instance_resp, instance_url, instance_index, pagination_index)
end
end.flatten(1)
end
|
[
"def",
"scrape_from_list",
"(",
"list",
",",
"blk",
")",
"puts",
"\"Scraping #{list.size} instances\"",
"if",
"@verbose",
"list",
".",
"each_with_index",
".",
"map",
"do",
"|",
"instance_url",
",",
"instance_index",
"|",
"instance_resps",
"=",
"get_instance",
"instance_url",
",",
"nil",
",",
":instance_index",
"=>",
"instance_index",
"instance_resps",
".",
"each_with_index",
".",
"map",
"do",
"|",
"instance_resp",
",",
"pagination_index",
"|",
"blk",
".",
"call",
"(",
"instance_resp",
",",
"instance_url",
",",
"instance_index",
",",
"pagination_index",
")",
"end",
"end",
".",
"flatten",
"(",
"1",
")",
"end"
] |
Just a helper for +scrape+.
|
[
"Just",
"a",
"helper",
"for",
"+",
"scrape",
"+",
"."
] |
29c90206317a6a8327a59f63d8117c56db6395eb
|
https://github.com/propublica/upton/blob/29c90206317a6a8327a59f63d8117c56db6395eb/lib/upton.rb#L337-L345
|
16,768
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/info.rb
|
CF::UAA.Info.varz
|
def varz(name, pwd)
json_get(target, "/varz", key_style, "authorization" => Http.basic_auth(name, pwd))
end
|
ruby
|
def varz(name, pwd)
json_get(target, "/varz", key_style, "authorization" => Http.basic_auth(name, pwd))
end
|
[
"def",
"varz",
"(",
"name",
",",
"pwd",
")",
"json_get",
"(",
"target",
",",
"\"/varz\"",
",",
"key_style",
",",
"\"authorization\"",
"=>",
"Http",
".",
"basic_auth",
"(",
"name",
",",
"pwd",
")",
")",
"end"
] |
Gets various monitoring and status variables from the server.
Authenticates using +name+ and +pwd+ for basic authentication.
@param (see Misc.server)
@return [Hash]
|
[
"Gets",
"various",
"monitoring",
"and",
"status",
"variables",
"from",
"the",
"server",
".",
"Authenticates",
"using",
"+",
"name",
"+",
"and",
"+",
"pwd",
"+",
"for",
"basic",
"authentication",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L61-L63
|
16,769
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/info.rb
|
CF::UAA.Info.server
|
def server
reply = json_get(target, '/login', key_style)
return reply if reply && (reply[:prompts] || reply['prompts'])
raise BadResponse, "Invalid response from target #{target}"
end
|
ruby
|
def server
reply = json_get(target, '/login', key_style)
return reply if reply && (reply[:prompts] || reply['prompts'])
raise BadResponse, "Invalid response from target #{target}"
end
|
[
"def",
"server",
"reply",
"=",
"json_get",
"(",
"target",
",",
"'/login'",
",",
"key_style",
")",
"return",
"reply",
"if",
"reply",
"&&",
"(",
"reply",
"[",
":prompts",
"]",
"||",
"reply",
"[",
"'prompts'",
"]",
")",
"raise",
"BadResponse",
",",
"\"Invalid response from target #{target}\"",
"end"
] |
Gets basic information about the target server, including version number,
commit ID, and links to API endpoints.
@return [Hash]
|
[
"Gets",
"basic",
"information",
"about",
"the",
"target",
"server",
"including",
"version",
"number",
"commit",
"ID",
"and",
"links",
"to",
"API",
"endpoints",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L68-L72
|
16,770
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/info.rb
|
CF::UAA.Info.discover_uaa
|
def discover_uaa
info = server
links = info['links'] || info[:links]
uaa = links && (links['uaa'] || links[:uaa])
uaa || target
end
|
ruby
|
def discover_uaa
info = server
links = info['links'] || info[:links]
uaa = links && (links['uaa'] || links[:uaa])
uaa || target
end
|
[
"def",
"discover_uaa",
"info",
"=",
"server",
"links",
"=",
"info",
"[",
"'links'",
"]",
"||",
"info",
"[",
":links",
"]",
"uaa",
"=",
"links",
"&&",
"(",
"links",
"[",
"'uaa'",
"]",
"||",
"links",
"[",
":uaa",
"]",
")",
"uaa",
"||",
"target",
"end"
] |
Gets a base url for the associated UAA from the target server by inspecting the
links returned from its info endpoint.
@return [String] url of UAA (or the target itself if it didn't provide a response)
|
[
"Gets",
"a",
"base",
"url",
"for",
"the",
"associated",
"UAA",
"from",
"the",
"target",
"server",
"by",
"inspecting",
"the",
"links",
"returned",
"from",
"its",
"info",
"endpoint",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L77-L83
|
16,771
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/info.rb
|
CF::UAA.Info.validation_key
|
def validation_key(client_id = nil, client_secret = nil)
hdrs = client_id && client_secret ?
{ "authorization" => Http.basic_auth(client_id, client_secret)} : {}
json_get(target, "/token_key", key_style, hdrs)
end
|
ruby
|
def validation_key(client_id = nil, client_secret = nil)
hdrs = client_id && client_secret ?
{ "authorization" => Http.basic_auth(client_id, client_secret)} : {}
json_get(target, "/token_key", key_style, hdrs)
end
|
[
"def",
"validation_key",
"(",
"client_id",
"=",
"nil",
",",
"client_secret",
"=",
"nil",
")",
"hdrs",
"=",
"client_id",
"&&",
"client_secret",
"?",
"{",
"\"authorization\"",
"=>",
"Http",
".",
"basic_auth",
"(",
"client_id",
",",
"client_secret",
")",
"}",
":",
"{",
"}",
"json_get",
"(",
"target",
",",
"\"/token_key\"",
",",
"key_style",
",",
"hdrs",
")",
"end"
] |
Gets the key from the server that is used to validate token signatures. If
the server is configured to use a symetric key, the caller must authenticate
by providing a a +client_id+ and +client_secret+. If the server
is configured to sign with a private key, this call will retrieve the
public key and +client_id+ must be nil.
@param (see Misc.server)
@return [Hash]
|
[
"Gets",
"the",
"key",
"from",
"the",
"server",
"that",
"is",
"used",
"to",
"validate",
"token",
"signatures",
".",
"If",
"the",
"server",
"is",
"configured",
"to",
"use",
"a",
"symetric",
"key",
"the",
"caller",
"must",
"authenticate",
"by",
"providing",
"a",
"a",
"+",
"client_id",
"+",
"and",
"+",
"client_secret",
"+",
".",
"If",
"the",
"server",
"is",
"configured",
"to",
"sign",
"with",
"a",
"private",
"key",
"this",
"call",
"will",
"retrieve",
"the",
"public",
"key",
"and",
"+",
"client_id",
"+",
"must",
"be",
"nil",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L92-L96
|
16,772
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/info.rb
|
CF::UAA.Info.password_strength
|
def password_strength(password)
json_parse_reply(key_style, *request(target, :post, '/password/score',
Util.encode_form(:password => password), "content-type" => Http::FORM_UTF8,
"accept" => Http::JSON_UTF8))
end
|
ruby
|
def password_strength(password)
json_parse_reply(key_style, *request(target, :post, '/password/score',
Util.encode_form(:password => password), "content-type" => Http::FORM_UTF8,
"accept" => Http::JSON_UTF8))
end
|
[
"def",
"password_strength",
"(",
"password",
")",
"json_parse_reply",
"(",
"key_style",
",",
"request",
"(",
"target",
",",
":post",
",",
"'/password/score'",
",",
"Util",
".",
"encode_form",
"(",
":password",
"=>",
"password",
")",
",",
"\"content-type\"",
"=>",
"Http",
"::",
"FORM_UTF8",
",",
"\"accept\"",
"=>",
"Http",
"::",
"JSON_UTF8",
")",
")",
"end"
] |
Gets information about the given password, including a strength score and
an indication of what strength is required.
@param (see Misc.server)
@return [Hash]
|
[
"Gets",
"information",
"about",
"the",
"given",
"password",
"including",
"a",
"strength",
"score",
"and",
"an",
"indication",
"of",
"what",
"strength",
"is",
"required",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/info.rb#L147-L151
|
16,773
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/scim.rb
|
CF::UAA.Scim.type_info
|
def type_info(type, elem)
scimfo = {
user: {
path: '/Users',
name_attr: 'userName',
origin_attr: 'origin'
},
group: {
path: '/Groups',
name_attr: 'displayName',
origin_attr: 'zoneid'
},
client: {
path: '/oauth/clients',
name_attr: 'client_id'
},
user_id: {
path: '/ids/Users',
name_attr: 'userName',
origin_attr: 'origin',
},
group_mapping: {
path: '/Groups/External',
name_attr: 'externalGroup',
origin_attr: 'origin'
}
}
type_info = scimfo[type]
unless type_info
raise ArgumentError, "scim resource type must be one of #{scimfo.keys.inspect}"
end
value = type_info[elem]
unless value
raise ArgumentError, "scim schema element must be one of #{type_info.keys.inspect}"
end
value
end
|
ruby
|
def type_info(type, elem)
scimfo = {
user: {
path: '/Users',
name_attr: 'userName',
origin_attr: 'origin'
},
group: {
path: '/Groups',
name_attr: 'displayName',
origin_attr: 'zoneid'
},
client: {
path: '/oauth/clients',
name_attr: 'client_id'
},
user_id: {
path: '/ids/Users',
name_attr: 'userName',
origin_attr: 'origin',
},
group_mapping: {
path: '/Groups/External',
name_attr: 'externalGroup',
origin_attr: 'origin'
}
}
type_info = scimfo[type]
unless type_info
raise ArgumentError, "scim resource type must be one of #{scimfo.keys.inspect}"
end
value = type_info[elem]
unless value
raise ArgumentError, "scim schema element must be one of #{type_info.keys.inspect}"
end
value
end
|
[
"def",
"type_info",
"(",
"type",
",",
"elem",
")",
"scimfo",
"=",
"{",
"user",
":",
"{",
"path",
":",
"'/Users'",
",",
"name_attr",
":",
"'userName'",
",",
"origin_attr",
":",
"'origin'",
"}",
",",
"group",
":",
"{",
"path",
":",
"'/Groups'",
",",
"name_attr",
":",
"'displayName'",
",",
"origin_attr",
":",
"'zoneid'",
"}",
",",
"client",
":",
"{",
"path",
":",
"'/oauth/clients'",
",",
"name_attr",
":",
"'client_id'",
"}",
",",
"user_id",
":",
"{",
"path",
":",
"'/ids/Users'",
",",
"name_attr",
":",
"'userName'",
",",
"origin_attr",
":",
"'origin'",
",",
"}",
",",
"group_mapping",
":",
"{",
"path",
":",
"'/Groups/External'",
",",
"name_attr",
":",
"'externalGroup'",
",",
"origin_attr",
":",
"'origin'",
"}",
"}",
"type_info",
"=",
"scimfo",
"[",
"type",
"]",
"unless",
"type_info",
"raise",
"ArgumentError",
",",
"\"scim resource type must be one of #{scimfo.keys.inspect}\"",
"end",
"value",
"=",
"type_info",
"[",
"elem",
"]",
"unless",
"value",
"raise",
"ArgumentError",
",",
"\"scim schema element must be one of #{type_info.keys.inspect}\"",
"end",
"value",
"end"
] |
an attempt to hide some scim and uaa oddities
|
[
"an",
"attempt",
"to",
"hide",
"some",
"scim",
"and",
"uaa",
"oddities"
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/scim.rb#L90-L131
|
16,774
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/scim.rb
|
CF::UAA.Scim.add
|
def add(type, info)
path, info = type_info(type, :path), force_case(info)
reply = json_parse_reply(@key_style, *json_post(@target, path, info,
headers))
fake_client_id(reply) if type == :client # hide client reply, not quite scim
reply
end
|
ruby
|
def add(type, info)
path, info = type_info(type, :path), force_case(info)
reply = json_parse_reply(@key_style, *json_post(@target, path, info,
headers))
fake_client_id(reply) if type == :client # hide client reply, not quite scim
reply
end
|
[
"def",
"add",
"(",
"type",
",",
"info",
")",
"path",
",",
"info",
"=",
"type_info",
"(",
"type",
",",
":path",
")",
",",
"force_case",
"(",
"info",
")",
"reply",
"=",
"json_parse_reply",
"(",
"@key_style",
",",
"json_post",
"(",
"@target",
",",
"path",
",",
"info",
",",
"headers",
")",
")",
"fake_client_id",
"(",
"reply",
")",
"if",
"type",
"==",
":client",
"# hide client reply, not quite scim",
"reply",
"end"
] |
Creates a SCIM resource.
@param [Symbol] type can be :user, :group, :client, :user_id.
@param [Hash] info converted to json and sent to the scim endpoint. For schema of
each type of object see {Scim}.
@return [Hash] contents of the object, including its +id+ and meta-data.
|
[
"Creates",
"a",
"SCIM",
"resource",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/scim.rb#L167-L173
|
16,775
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/scim.rb
|
CF::UAA.Scim.put
|
def put(type, info)
path, info = type_info(type, :path), force_case(info)
ida = type == :client ? 'client_id' : 'id'
raise ArgumentError, "info must include #{ida}" unless id = info[ida]
hdrs = headers
if info && info['meta'] && (etag = info['meta']['version'])
hdrs.merge!('if-match' => etag)
end
reply = json_parse_reply(@key_style,
*json_put(@target, "#{path}/#{URI.encode(id)}", info, hdrs))
# hide client endpoints that are not quite scim compatible
type == :client && !reply ? get(type, info['client_id']): reply
end
|
ruby
|
def put(type, info)
path, info = type_info(type, :path), force_case(info)
ida = type == :client ? 'client_id' : 'id'
raise ArgumentError, "info must include #{ida}" unless id = info[ida]
hdrs = headers
if info && info['meta'] && (etag = info['meta']['version'])
hdrs.merge!('if-match' => etag)
end
reply = json_parse_reply(@key_style,
*json_put(@target, "#{path}/#{URI.encode(id)}", info, hdrs))
# hide client endpoints that are not quite scim compatible
type == :client && !reply ? get(type, info['client_id']): reply
end
|
[
"def",
"put",
"(",
"type",
",",
"info",
")",
"path",
",",
"info",
"=",
"type_info",
"(",
"type",
",",
":path",
")",
",",
"force_case",
"(",
"info",
")",
"ida",
"=",
"type",
"==",
":client",
"?",
"'client_id'",
":",
"'id'",
"raise",
"ArgumentError",
",",
"\"info must include #{ida}\"",
"unless",
"id",
"=",
"info",
"[",
"ida",
"]",
"hdrs",
"=",
"headers",
"if",
"info",
"&&",
"info",
"[",
"'meta'",
"]",
"&&",
"(",
"etag",
"=",
"info",
"[",
"'meta'",
"]",
"[",
"'version'",
"]",
")",
"hdrs",
".",
"merge!",
"(",
"'if-match'",
"=>",
"etag",
")",
"end",
"reply",
"=",
"json_parse_reply",
"(",
"@key_style",
",",
"json_put",
"(",
"@target",
",",
"\"#{path}/#{URI.encode(id)}\"",
",",
"info",
",",
"hdrs",
")",
")",
"# hide client endpoints that are not quite scim compatible",
"type",
"==",
":client",
"&&",
"!",
"reply",
"?",
"get",
"(",
"type",
",",
"info",
"[",
"'client_id'",
"]",
")",
":",
"reply",
"end"
] |
Replaces the contents of a SCIM object.
@param (see #add)
@return (see #add)
|
[
"Replaces",
"the",
"contents",
"of",
"a",
"SCIM",
"object",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/scim.rb#L186-L199
|
16,776
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/scim.rb
|
CF::UAA.Scim.query
|
def query(type, query = {})
query = force_case(query).reject {|k, v| v.nil? }
if attrs = query['attributes']
attrs = Util.arglist(attrs).map {|a| force_attr(a)}
query['attributes'] = Util.strlist(attrs, ",")
end
qstr = query.empty?? '': "?#{Util.encode_form(query)}"
info = json_get(@target, "#{type_info(type, :path)}#{qstr}",
@key_style, headers)
unless info.is_a?(Hash) && info[rk = jkey(:resources)].is_a?(Array)
# hide client endpoints that are not yet scim compatible
if type == :client && info.is_a?(Hash)
info = info.each{ |k, v| fake_client_id(v) }.values
if m = /^client_id\s+eq\s+"([^"]+)"$/i.match(query['filter'])
idk = jkey(:client_id)
info = info.select { |c| c[idk].casecmp(m[1]) == 0 }
end
return {rk => info}
end
raise BadResponse, "invalid reply to #{type} query of #{@target}"
end
info
end
|
ruby
|
def query(type, query = {})
query = force_case(query).reject {|k, v| v.nil? }
if attrs = query['attributes']
attrs = Util.arglist(attrs).map {|a| force_attr(a)}
query['attributes'] = Util.strlist(attrs, ",")
end
qstr = query.empty?? '': "?#{Util.encode_form(query)}"
info = json_get(@target, "#{type_info(type, :path)}#{qstr}",
@key_style, headers)
unless info.is_a?(Hash) && info[rk = jkey(:resources)].is_a?(Array)
# hide client endpoints that are not yet scim compatible
if type == :client && info.is_a?(Hash)
info = info.each{ |k, v| fake_client_id(v) }.values
if m = /^client_id\s+eq\s+"([^"]+)"$/i.match(query['filter'])
idk = jkey(:client_id)
info = info.select { |c| c[idk].casecmp(m[1]) == 0 }
end
return {rk => info}
end
raise BadResponse, "invalid reply to #{type} query of #{@target}"
end
info
end
|
[
"def",
"query",
"(",
"type",
",",
"query",
"=",
"{",
"}",
")",
"query",
"=",
"force_case",
"(",
"query",
")",
".",
"reject",
"{",
"|",
"k",
",",
"v",
"|",
"v",
".",
"nil?",
"}",
"if",
"attrs",
"=",
"query",
"[",
"'attributes'",
"]",
"attrs",
"=",
"Util",
".",
"arglist",
"(",
"attrs",
")",
".",
"map",
"{",
"|",
"a",
"|",
"force_attr",
"(",
"a",
")",
"}",
"query",
"[",
"'attributes'",
"]",
"=",
"Util",
".",
"strlist",
"(",
"attrs",
",",
"\",\"",
")",
"end",
"qstr",
"=",
"query",
".",
"empty?",
"?",
"''",
":",
"\"?#{Util.encode_form(query)}\"",
"info",
"=",
"json_get",
"(",
"@target",
",",
"\"#{type_info(type, :path)}#{qstr}\"",
",",
"@key_style",
",",
"headers",
")",
"unless",
"info",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"info",
"[",
"rk",
"=",
"jkey",
"(",
":resources",
")",
"]",
".",
"is_a?",
"(",
"Array",
")",
"# hide client endpoints that are not yet scim compatible",
"if",
"type",
"==",
":client",
"&&",
"info",
".",
"is_a?",
"(",
"Hash",
")",
"info",
"=",
"info",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"fake_client_id",
"(",
"v",
")",
"}",
".",
"values",
"if",
"m",
"=",
"/",
"\\s",
"\\s",
"/i",
".",
"match",
"(",
"query",
"[",
"'filter'",
"]",
")",
"idk",
"=",
"jkey",
"(",
":client_id",
")",
"info",
"=",
"info",
".",
"select",
"{",
"|",
"c",
"|",
"c",
"[",
"idk",
"]",
".",
"casecmp",
"(",
"m",
"[",
"1",
"]",
")",
"==",
"0",
"}",
"end",
"return",
"{",
"rk",
"=>",
"info",
"}",
"end",
"raise",
"BadResponse",
",",
"\"invalid reply to #{type} query of #{@target}\"",
"end",
"info",
"end"
] |
Gets a set of attributes for each object that matches a given filter.
@param (see #add)
@param [Hash] query may contain the following keys:
* +attributes+: a comma or space separated list of attribute names to be
returned for each object that matches the filter. If no attribute
list is given, all attributes are returned.
* +filter+: a filter to select which objects are returned. See
{http://www.simplecloud.info/specs/draft-scim-api-01.html#query-resources}
* +startIndex+: for paged output, start index of requested result set.
* +count+: maximum number of results per reply
@return [Hash] including a +resources+ array of results and
pagination data.
|
[
"Gets",
"a",
"set",
"of",
"attributes",
"for",
"each",
"object",
"that",
"matches",
"a",
"given",
"filter",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/scim.rb#L231-L255
|
16,777
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/scim.rb
|
CF::UAA.Scim.get
|
def get(type, id)
info = json_get(@target, "#{type_info(type, :path)}/#{URI.encode(id)}",
@key_style, headers)
fake_client_id(info) if type == :client # hide client reply, not quite scim
info
end
|
ruby
|
def get(type, id)
info = json_get(@target, "#{type_info(type, :path)}/#{URI.encode(id)}",
@key_style, headers)
fake_client_id(info) if type == :client # hide client reply, not quite scim
info
end
|
[
"def",
"get",
"(",
"type",
",",
"id",
")",
"info",
"=",
"json_get",
"(",
"@target",
",",
"\"#{type_info(type, :path)}/#{URI.encode(id)}\"",
",",
"@key_style",
",",
"headers",
")",
"fake_client_id",
"(",
"info",
")",
"if",
"type",
"==",
":client",
"# hide client reply, not quite scim",
"info",
"end"
] |
Get information about a specific object.
@param (see #delete)
@return (see #add)
|
[
"Get",
"information",
"about",
"a",
"specific",
"object",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/scim.rb#L260-L266
|
16,778
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/token_issuer.rb
|
CF::UAA.TokenIssuer.implicit_grant_with_creds
|
def implicit_grant_with_creds(credentials, scope = nil)
# this manufactured redirect_uri is a convention here, not part of OAuth2
redir_uri = "https://uaa.cloudfoundry.com/redirect/#{@client_id}"
response_type = "token"
response_type = "#{response_type} id_token" if scope && (scope.include? "openid")
uri = authorize_path_args(response_type, redir_uri, scope, state = random_state)
# the accept header is only here so the uaa will issue error replies in json to aid debugging
headers = {'content-type' => FORM_UTF8, 'accept' => JSON_UTF8 }
body = Util.encode_form(credentials.merge(:source => 'credentials'))
status, body, headers = request(@target, :post, uri, body, headers)
raise BadResponse, "status #{status}" unless status == 302
req_uri, reply_uri = URI.parse(redir_uri), URI.parse(headers['location'])
fragment, reply_uri.fragment = reply_uri.fragment, nil
raise BadResponse, "bad location header" unless req_uri == reply_uri
parse_implicit_params(fragment, state)
rescue URI::Error => e
raise BadResponse, "bad location header in reply: #{e.message}"
end
|
ruby
|
def implicit_grant_with_creds(credentials, scope = nil)
# this manufactured redirect_uri is a convention here, not part of OAuth2
redir_uri = "https://uaa.cloudfoundry.com/redirect/#{@client_id}"
response_type = "token"
response_type = "#{response_type} id_token" if scope && (scope.include? "openid")
uri = authorize_path_args(response_type, redir_uri, scope, state = random_state)
# the accept header is only here so the uaa will issue error replies in json to aid debugging
headers = {'content-type' => FORM_UTF8, 'accept' => JSON_UTF8 }
body = Util.encode_form(credentials.merge(:source => 'credentials'))
status, body, headers = request(@target, :post, uri, body, headers)
raise BadResponse, "status #{status}" unless status == 302
req_uri, reply_uri = URI.parse(redir_uri), URI.parse(headers['location'])
fragment, reply_uri.fragment = reply_uri.fragment, nil
raise BadResponse, "bad location header" unless req_uri == reply_uri
parse_implicit_params(fragment, state)
rescue URI::Error => e
raise BadResponse, "bad location header in reply: #{e.message}"
end
|
[
"def",
"implicit_grant_with_creds",
"(",
"credentials",
",",
"scope",
"=",
"nil",
")",
"# this manufactured redirect_uri is a convention here, not part of OAuth2",
"redir_uri",
"=",
"\"https://uaa.cloudfoundry.com/redirect/#{@client_id}\"",
"response_type",
"=",
"\"token\"",
"response_type",
"=",
"\"#{response_type} id_token\"",
"if",
"scope",
"&&",
"(",
"scope",
".",
"include?",
"\"openid\"",
")",
"uri",
"=",
"authorize_path_args",
"(",
"response_type",
",",
"redir_uri",
",",
"scope",
",",
"state",
"=",
"random_state",
")",
"# the accept header is only here so the uaa will issue error replies in json to aid debugging",
"headers",
"=",
"{",
"'content-type'",
"=>",
"FORM_UTF8",
",",
"'accept'",
"=>",
"JSON_UTF8",
"}",
"body",
"=",
"Util",
".",
"encode_form",
"(",
"credentials",
".",
"merge",
"(",
":source",
"=>",
"'credentials'",
")",
")",
"status",
",",
"body",
",",
"headers",
"=",
"request",
"(",
"@target",
",",
":post",
",",
"uri",
",",
"body",
",",
"headers",
")",
"raise",
"BadResponse",
",",
"\"status #{status}\"",
"unless",
"status",
"==",
"302",
"req_uri",
",",
"reply_uri",
"=",
"URI",
".",
"parse",
"(",
"redir_uri",
")",
",",
"URI",
".",
"parse",
"(",
"headers",
"[",
"'location'",
"]",
")",
"fragment",
",",
"reply_uri",
".",
"fragment",
"=",
"reply_uri",
".",
"fragment",
",",
"nil",
"raise",
"BadResponse",
",",
"\"bad location header\"",
"unless",
"req_uri",
"==",
"reply_uri",
"parse_implicit_params",
"(",
"fragment",
",",
"state",
")",
"rescue",
"URI",
"::",
"Error",
"=>",
"e",
"raise",
"BadResponse",
",",
"\"bad location header in reply: #{e.message}\"",
"end"
] |
Gets an access token in a single call to the UAA with the user
credentials used for authentication.
@param credentials should be an object such as a hash that can be converted
to a json representation of the credential name/value pairs corresponding to
the keys retrieved by {#prompts}.
@return [TokenInfo]
|
[
"Gets",
"an",
"access",
"token",
"in",
"a",
"single",
"call",
"to",
"the",
"UAA",
"with",
"the",
"user",
"credentials",
"used",
"for",
"authentication",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/token_issuer.rb#L131-L149
|
16,779
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/token_issuer.rb
|
CF::UAA.TokenIssuer.implicit_uri
|
def implicit_uri(redirect_uri, scope = nil)
response_type = "token"
response_type = "#{response_type} id_token" if scope && (scope.include? "openid")
@target + authorize_path_args(response_type, redirect_uri, scope)
end
|
ruby
|
def implicit_uri(redirect_uri, scope = nil)
response_type = "token"
response_type = "#{response_type} id_token" if scope && (scope.include? "openid")
@target + authorize_path_args(response_type, redirect_uri, scope)
end
|
[
"def",
"implicit_uri",
"(",
"redirect_uri",
",",
"scope",
"=",
"nil",
")",
"response_type",
"=",
"\"token\"",
"response_type",
"=",
"\"#{response_type} id_token\"",
"if",
"scope",
"&&",
"(",
"scope",
".",
"include?",
"\"openid\"",
")",
"@target",
"+",
"authorize_path_args",
"(",
"response_type",
",",
"redirect_uri",
",",
"scope",
")",
"end"
] |
Constructs a uri that the client is to return to the browser to direct
the user to the authorization server to get an authcode.
@param [String] redirect_uri (see #authcode_uri)
@return [String]
|
[
"Constructs",
"a",
"uri",
"that",
"the",
"client",
"is",
"to",
"return",
"to",
"the",
"browser",
"to",
"direct",
"the",
"user",
"to",
"the",
"authorization",
"server",
"to",
"get",
"an",
"authcode",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/token_issuer.rb#L155-L159
|
16,780
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/token_issuer.rb
|
CF::UAA.TokenIssuer.implicit_grant
|
def implicit_grant(implicit_uri, callback_fragment)
in_params = Util.decode_form(URI.parse(implicit_uri).query)
unless in_params['state'] && in_params['redirect_uri']
raise ArgumentError, "redirect must happen before implicit grant"
end
parse_implicit_params(callback_fragment, in_params['state'])
end
|
ruby
|
def implicit_grant(implicit_uri, callback_fragment)
in_params = Util.decode_form(URI.parse(implicit_uri).query)
unless in_params['state'] && in_params['redirect_uri']
raise ArgumentError, "redirect must happen before implicit grant"
end
parse_implicit_params(callback_fragment, in_params['state'])
end
|
[
"def",
"implicit_grant",
"(",
"implicit_uri",
",",
"callback_fragment",
")",
"in_params",
"=",
"Util",
".",
"decode_form",
"(",
"URI",
".",
"parse",
"(",
"implicit_uri",
")",
".",
"query",
")",
"unless",
"in_params",
"[",
"'state'",
"]",
"&&",
"in_params",
"[",
"'redirect_uri'",
"]",
"raise",
"ArgumentError",
",",
"\"redirect must happen before implicit grant\"",
"end",
"parse_implicit_params",
"(",
"callback_fragment",
",",
"in_params",
"[",
"'state'",
"]",
")",
"end"
] |
Gets a token via an implicit grant.
@param [String] implicit_uri must be from a previous call to
{#implicit_uri}, contains state used to validate the contents of the
reply from the server.
@param [String] callback_fragment must be the fragment portion of the URL
received by the user's browser after the server redirects back to the
+redirect_uri+ that was given to {#implicit_uri}. How the application
gets the contents of the fragment is application specific -- usually
some javascript in the page at the +redirect_uri+.
@see http://tools.ietf.org/html/rfc6749#section-4.2
@return [TokenInfo]
|
[
"Gets",
"a",
"token",
"via",
"an",
"implicit",
"grant",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/token_issuer.rb#L172-L178
|
16,781
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/token_issuer.rb
|
CF::UAA.TokenIssuer.autologin_uri
|
def autologin_uri(redirect_uri, credentials, scope = nil)
headers = {'content-type' => FORM_UTF8, 'accept' => JSON_UTF8,
'authorization' => Http.basic_auth(@client_id, @client_secret) }
body = Util.encode_form(credentials)
reply = json_parse_reply(nil, *request(@target, :post, "/autologin", body, headers))
raise BadResponse, "no autologin code in reply" unless reply['code']
@target + authorize_path_args('code', redirect_uri, scope,
random_state, :code => reply['code'])
end
|
ruby
|
def autologin_uri(redirect_uri, credentials, scope = nil)
headers = {'content-type' => FORM_UTF8, 'accept' => JSON_UTF8,
'authorization' => Http.basic_auth(@client_id, @client_secret) }
body = Util.encode_form(credentials)
reply = json_parse_reply(nil, *request(@target, :post, "/autologin", body, headers))
raise BadResponse, "no autologin code in reply" unless reply['code']
@target + authorize_path_args('code', redirect_uri, scope,
random_state, :code => reply['code'])
end
|
[
"def",
"autologin_uri",
"(",
"redirect_uri",
",",
"credentials",
",",
"scope",
"=",
"nil",
")",
"headers",
"=",
"{",
"'content-type'",
"=>",
"FORM_UTF8",
",",
"'accept'",
"=>",
"JSON_UTF8",
",",
"'authorization'",
"=>",
"Http",
".",
"basic_auth",
"(",
"@client_id",
",",
"@client_secret",
")",
"}",
"body",
"=",
"Util",
".",
"encode_form",
"(",
"credentials",
")",
"reply",
"=",
"json_parse_reply",
"(",
"nil",
",",
"request",
"(",
"@target",
",",
":post",
",",
"\"/autologin\"",
",",
"body",
",",
"headers",
")",
")",
"raise",
"BadResponse",
",",
"\"no autologin code in reply\"",
"unless",
"reply",
"[",
"'code'",
"]",
"@target",
"+",
"authorize_path_args",
"(",
"'code'",
",",
"redirect_uri",
",",
"scope",
",",
"random_state",
",",
":code",
"=>",
"reply",
"[",
"'code'",
"]",
")",
"end"
] |
A UAA extension to OAuth2 that allows a client to pre-authenticate a
user at the start of an authorization code flow. By passing in the
user's credentials the server can establish a session with the user's
browser without reprompting for authentication. This is useful for
user account management apps so that they can create a user account,
or reset a password for the user, without requiring the user to type
in their credentials again.
@param [String] credentials (see #implicit_grant_with_creds)
@param [String] redirect_uri (see #authcode_uri)
@return (see #authcode_uri)
|
[
"A",
"UAA",
"extension",
"to",
"OAuth2",
"that",
"allows",
"a",
"client",
"to",
"pre",
"-",
"authenticate",
"a",
"user",
"at",
"the",
"start",
"of",
"an",
"authorization",
"code",
"flow",
".",
"By",
"passing",
"in",
"the",
"user",
"s",
"credentials",
"the",
"server",
"can",
"establish",
"a",
"session",
"with",
"the",
"user",
"s",
"browser",
"without",
"reprompting",
"for",
"authentication",
".",
"This",
"is",
"useful",
"for",
"user",
"account",
"management",
"apps",
"so",
"that",
"they",
"can",
"create",
"a",
"user",
"account",
"or",
"reset",
"a",
"password",
"for",
"the",
"user",
"without",
"requiring",
"the",
"user",
"to",
"type",
"in",
"their",
"credentials",
"again",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/token_issuer.rb#L190-L198
|
16,782
|
cloudfoundry/cf-uaa-lib
|
lib/uaa/token_issuer.rb
|
CF::UAA.TokenIssuer.authcode_grant
|
def authcode_grant(authcode_uri, callback_query)
ac_params = Util.decode_form(URI.parse(authcode_uri).query)
unless ac_params['state'] && ac_params['redirect_uri']
raise ArgumentError, "authcode redirect must happen before authcode grant"
end
begin
params = Util.decode_form(callback_query)
authcode = params['code']
raise BadResponse unless params['state'] == ac_params['state'] && authcode
rescue URI::InvalidURIError, ArgumentError, BadResponse
raise BadResponse, "received invalid response from target #{@target}"
end
request_token(:grant_type => 'authorization_code', :code => authcode,
:redirect_uri => ac_params['redirect_uri'])
end
|
ruby
|
def authcode_grant(authcode_uri, callback_query)
ac_params = Util.decode_form(URI.parse(authcode_uri).query)
unless ac_params['state'] && ac_params['redirect_uri']
raise ArgumentError, "authcode redirect must happen before authcode grant"
end
begin
params = Util.decode_form(callback_query)
authcode = params['code']
raise BadResponse unless params['state'] == ac_params['state'] && authcode
rescue URI::InvalidURIError, ArgumentError, BadResponse
raise BadResponse, "received invalid response from target #{@target}"
end
request_token(:grant_type => 'authorization_code', :code => authcode,
:redirect_uri => ac_params['redirect_uri'])
end
|
[
"def",
"authcode_grant",
"(",
"authcode_uri",
",",
"callback_query",
")",
"ac_params",
"=",
"Util",
".",
"decode_form",
"(",
"URI",
".",
"parse",
"(",
"authcode_uri",
")",
".",
"query",
")",
"unless",
"ac_params",
"[",
"'state'",
"]",
"&&",
"ac_params",
"[",
"'redirect_uri'",
"]",
"raise",
"ArgumentError",
",",
"\"authcode redirect must happen before authcode grant\"",
"end",
"begin",
"params",
"=",
"Util",
".",
"decode_form",
"(",
"callback_query",
")",
"authcode",
"=",
"params",
"[",
"'code'",
"]",
"raise",
"BadResponse",
"unless",
"params",
"[",
"'state'",
"]",
"==",
"ac_params",
"[",
"'state'",
"]",
"&&",
"authcode",
"rescue",
"URI",
"::",
"InvalidURIError",
",",
"ArgumentError",
",",
"BadResponse",
"raise",
"BadResponse",
",",
"\"received invalid response from target #{@target}\"",
"end",
"request_token",
"(",
":grant_type",
"=>",
"'authorization_code'",
",",
":code",
"=>",
"authcode",
",",
":redirect_uri",
"=>",
"ac_params",
"[",
"'redirect_uri'",
"]",
")",
"end"
] |
Uses the instance client credentials in addition to +callback_query+
to get a token via the authorization code grant.
@param [String] authcode_uri must be from a previous call to {#authcode_uri}
and contains state used to validate the contents of the reply from the
server.
@param [String] callback_query must be the query portion of the URL
received by the client after the user's browser is redirected back from
the server. It contains the authorization code.
@see http://tools.ietf.org/html/rfc6749#section-4.1
@return [TokenInfo]
|
[
"Uses",
"the",
"instance",
"client",
"credentials",
"in",
"addition",
"to",
"+",
"callback_query",
"+",
"to",
"get",
"a",
"token",
"via",
"the",
"authorization",
"code",
"grant",
"."
] |
e071d69ad5f16053321dfbb95835cf6a9b48227c
|
https://github.com/cloudfoundry/cf-uaa-lib/blob/e071d69ad5f16053321dfbb95835cf6a9b48227c/lib/uaa/token_issuer.rb#L219-L233
|
16,783
|
piotrmurach/finite_machine
|
lib/finite_machine/events_map.rb
|
FiniteMachine.EventsMap.choice_transition?
|
def choice_transition?(name, from_state)
find(name).select { |trans| trans.matches?(from_state) }.size > 1
end
|
ruby
|
def choice_transition?(name, from_state)
find(name).select { |trans| trans.matches?(from_state) }.size > 1
end
|
[
"def",
"choice_transition?",
"(",
"name",
",",
"from_state",
")",
"find",
"(",
"name",
")",
".",
"select",
"{",
"|",
"trans",
"|",
"trans",
".",
"matches?",
"(",
"from_state",
")",
"}",
".",
"size",
">",
"1",
"end"
] |
Check if event has branching choice transitions or not
@example
events_map.choice_transition?(:go, :green) # => true
@param [Symbol] name
the event name
@param [Symbol] from_state
the transition from state
@return [Boolean]
true if transition has any branches, false otherwise
@api public
|
[
"Check",
"if",
"event",
"has",
"branching",
"choice",
"transitions",
"or",
"not"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/events_map.rb#L150-L152
|
16,784
|
piotrmurach/finite_machine
|
lib/finite_machine/events_map.rb
|
FiniteMachine.EventsMap.match_transition
|
def match_transition(name, from_state)
find(name).find { |trans| trans.matches?(from_state) }
end
|
ruby
|
def match_transition(name, from_state)
find(name).find { |trans| trans.matches?(from_state) }
end
|
[
"def",
"match_transition",
"(",
"name",
",",
"from_state",
")",
"find",
"(",
"name",
")",
".",
"find",
"{",
"|",
"trans",
"|",
"trans",
".",
"matches?",
"(",
"from_state",
")",
"}",
"end"
] |
Find transition without checking conditions
@param [Symbol] name
the event name
@param [Symbol] from_state
the transition from state
@return [Transition, nil]
returns transition, nil otherwise
@api private
|
[
"Find",
"transition",
"without",
"checking",
"conditions"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/events_map.rb#L166-L168
|
16,785
|
piotrmurach/finite_machine
|
lib/finite_machine/events_map.rb
|
FiniteMachine.EventsMap.match_transition_with
|
def match_transition_with(name, from_state, *conditions)
find(name).find do |trans|
trans.matches?(from_state) &&
trans.check_conditions(*conditions)
end
end
|
ruby
|
def match_transition_with(name, from_state, *conditions)
find(name).find do |trans|
trans.matches?(from_state) &&
trans.check_conditions(*conditions)
end
end
|
[
"def",
"match_transition_with",
"(",
"name",
",",
"from_state",
",",
"*",
"conditions",
")",
"find",
"(",
"name",
")",
".",
"find",
"do",
"|",
"trans",
"|",
"trans",
".",
"matches?",
"(",
"from_state",
")",
"&&",
"trans",
".",
"check_conditions",
"(",
"conditions",
")",
"end",
"end"
] |
Examine transitions for event name that start in from state
and find one matching condition.
@param [Symbol] name
the event name
@param [Symbol] from_state
the current context from_state
@return [Transition]
The choice transition that matches
@api public
|
[
"Examine",
"transitions",
"for",
"event",
"name",
"that",
"start",
"in",
"from",
"state",
"and",
"find",
"one",
"matching",
"condition",
"."
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/events_map.rb#L183-L188
|
16,786
|
piotrmurach/finite_machine
|
lib/finite_machine/events_map.rb
|
FiniteMachine.EventsMap.select_transition
|
def select_transition(name, from_state, *conditions)
if choice_transition?(name, from_state)
match_transition_with(name, from_state, *conditions)
else
match_transition(name, from_state)
end
end
|
ruby
|
def select_transition(name, from_state, *conditions)
if choice_transition?(name, from_state)
match_transition_with(name, from_state, *conditions)
else
match_transition(name, from_state)
end
end
|
[
"def",
"select_transition",
"(",
"name",
",",
"from_state",
",",
"*",
"conditions",
")",
"if",
"choice_transition?",
"(",
"name",
",",
"from_state",
")",
"match_transition_with",
"(",
"name",
",",
"from_state",
",",
"conditions",
")",
"else",
"match_transition",
"(",
"name",
",",
"from_state",
")",
"end",
"end"
] |
Select transition that matches conditions
@param [Symbol] name
the event name
@param [Symbol] from_state
the transition from state
@param [Array[Object]] conditions
the conditional data
@return [Transition]
@api public
|
[
"Select",
"transition",
"that",
"matches",
"conditions"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/events_map.rb#L202-L208
|
16,787
|
piotrmurach/finite_machine
|
lib/finite_machine/events_map.rb
|
FiniteMachine.EventsMap.move_to
|
def move_to(name, from_state, *conditions)
transition = select_transition(name, from_state, *conditions)
transition ||= UndefinedTransition.new(name)
transition.to_state(from_state)
end
|
ruby
|
def move_to(name, from_state, *conditions)
transition = select_transition(name, from_state, *conditions)
transition ||= UndefinedTransition.new(name)
transition.to_state(from_state)
end
|
[
"def",
"move_to",
"(",
"name",
",",
"from_state",
",",
"*",
"conditions",
")",
"transition",
"=",
"select_transition",
"(",
"name",
",",
"from_state",
",",
"conditions",
")",
"transition",
"||=",
"UndefinedTransition",
".",
"new",
"(",
"name",
")",
"transition",
".",
"to_state",
"(",
"from_state",
")",
"end"
] |
Find state that this machine can move to
@example
evenst_map.move_to(:go, :green) # => :red
@param [Symbol] name
the event name
@param [Symbol] from_state
the transition from state
@param [Array] conditions
the data associated with this transition
@return [Symbol]
the transition `to` state
@api public
|
[
"Find",
"state",
"that",
"this",
"machine",
"can",
"move",
"to"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/events_map.rb#L228-L232
|
16,788
|
piotrmurach/finite_machine
|
lib/finite_machine/events_map.rb
|
FiniteMachine.EventsMap.to_s
|
def to_s
hash = {}
@events_map.each_pair do |name, trans|
hash[name] = trans
end
hash.to_s
end
|
ruby
|
def to_s
hash = {}
@events_map.each_pair do |name, trans|
hash[name] = trans
end
hash.to_s
end
|
[
"def",
"to_s",
"hash",
"=",
"{",
"}",
"@events_map",
".",
"each_pair",
"do",
"|",
"name",
",",
"trans",
"|",
"hash",
"[",
"name",
"]",
"=",
"trans",
"end",
"hash",
".",
"to_s",
"end"
] |
Return string representation of this map
@return [String]
@api public
|
[
"Return",
"string",
"representation",
"of",
"this",
"map"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/events_map.rb#L249-L255
|
16,789
|
piotrmurach/finite_machine
|
lib/finite_machine/transition.rb
|
FiniteMachine.Transition.make_conditions
|
def make_conditions
@if.map { |c| Callable.new(c) } +
@unless.map { |c| Callable.new(c).invert }
end
|
ruby
|
def make_conditions
@if.map { |c| Callable.new(c) } +
@unless.map { |c| Callable.new(c).invert }
end
|
[
"def",
"make_conditions",
"@if",
".",
"map",
"{",
"|",
"c",
"|",
"Callable",
".",
"new",
"(",
"c",
")",
"}",
"+",
"@unless",
".",
"map",
"{",
"|",
"c",
"|",
"Callable",
".",
"new",
"(",
"c",
")",
".",
"invert",
"}",
"end"
] |
Initialize a Transition
@example
attributes = {states: {green: :yellow}}
Transition.new(context, :go, attributes)
@param [Object] context
the context this transition evaluets conditions in
@param [Hash] attrs
@return [Transition]
@api public
Reduce conditions
@return [Array[Callable]]
@api private
|
[
"Initialize",
"a",
"Transition"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/transition.rb#L63-L66
|
16,790
|
piotrmurach/finite_machine
|
lib/finite_machine/transition.rb
|
FiniteMachine.Transition.matches?
|
def matches?(from)
states.keys.any? { |state| [ANY_STATE, from].include?(state) }
end
|
ruby
|
def matches?(from)
states.keys.any? { |state| [ANY_STATE, from].include?(state) }
end
|
[
"def",
"matches?",
"(",
"from",
")",
"states",
".",
"keys",
".",
"any?",
"{",
"|",
"state",
"|",
"[",
"ANY_STATE",
",",
"from",
"]",
".",
"include?",
"(",
"state",
")",
"}",
"end"
] |
Check if this transition matches from state
@param [Symbol] from
the from state to match against
@example
transition = Transition.new(context, states: {:green => :red})
transition.matches?(:green) # => true
@return [Boolean]
Return true if match is found, false otherwise.
@api public
|
[
"Check",
"if",
"this",
"transition",
"matches",
"from",
"state"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/transition.rb#L95-L97
|
16,791
|
piotrmurach/finite_machine
|
lib/finite_machine/choice_merger.rb
|
FiniteMachine.ChoiceMerger.choice
|
def choice(to, **conditions)
transition_builder = TransitionBuilder.new(@machine, @name,
@transitions.merge(conditions))
transition_builder.call(@transitions[:from] => to)
end
|
ruby
|
def choice(to, **conditions)
transition_builder = TransitionBuilder.new(@machine, @name,
@transitions.merge(conditions))
transition_builder.call(@transitions[:from] => to)
end
|
[
"def",
"choice",
"(",
"to",
",",
"**",
"conditions",
")",
"transition_builder",
"=",
"TransitionBuilder",
".",
"new",
"(",
"@machine",
",",
"@name",
",",
"@transitions",
".",
"merge",
"(",
"conditions",
")",
")",
"transition_builder",
".",
"call",
"(",
"@transitions",
"[",
":from",
"]",
"=>",
"to",
")",
"end"
] |
Initialize a ChoiceMerger
@param [StateMachine] machine
@param [String] name
@param [Hash] transitions
the transitions and attributes
@api private
Create choice transition
@example
event :stop, from: :green do
choice :yellow
end
@param [Symbol] to
the to state
@param [Hash] conditions
the conditions associated with this choice
@return [FiniteMachine::Transition]
@api public
|
[
"Initialize",
"a",
"ChoiceMerger"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/choice_merger.rb#L37-L41
|
16,792
|
piotrmurach/finite_machine
|
lib/finite_machine/state_definition.rb
|
FiniteMachine.StateDefinition.define_state_query_method
|
def define_state_query_method(state)
return if machine.respond_to?("#{state}?")
machine.send(:define_singleton_method, "#{state}?") do
machine.is?(state.to_sym)
end
end
|
ruby
|
def define_state_query_method(state)
return if machine.respond_to?("#{state}?")
machine.send(:define_singleton_method, "#{state}?") do
machine.is?(state.to_sym)
end
end
|
[
"def",
"define_state_query_method",
"(",
"state",
")",
"return",
"if",
"machine",
".",
"respond_to?",
"(",
"\"#{state}?\"",
")",
"machine",
".",
"send",
"(",
":define_singleton_method",
",",
"\"#{state}?\"",
")",
"do",
"machine",
".",
"is?",
"(",
"state",
".",
"to_sym",
")",
"end",
"end"
] |
Define state helper method
@param [Symbol] state
the state to define helper for
@api private
|
[
"Define",
"state",
"helper",
"method"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/state_definition.rb#L57-L62
|
16,793
|
piotrmurach/finite_machine
|
lib/finite_machine/observer.rb
|
FiniteMachine.Observer.on
|
def on(hook_type, state_or_event_name = nil, async = nil, &callback)
sync_exclusive do
if state_or_event_name.nil?
state_or_event_name = HookEvent.any_state_or_event(hook_type)
end
async = false if async.nil?
ensure_valid_callback_name!(hook_type, state_or_event_name)
callback.extend(Async) if async == :async
hooks.register(hook_type, state_or_event_name, callback)
end
end
|
ruby
|
def on(hook_type, state_or_event_name = nil, async = nil, &callback)
sync_exclusive do
if state_or_event_name.nil?
state_or_event_name = HookEvent.any_state_or_event(hook_type)
end
async = false if async.nil?
ensure_valid_callback_name!(hook_type, state_or_event_name)
callback.extend(Async) if async == :async
hooks.register(hook_type, state_or_event_name, callback)
end
end
|
[
"def",
"on",
"(",
"hook_type",
",",
"state_or_event_name",
"=",
"nil",
",",
"async",
"=",
"nil",
",",
"&",
"callback",
")",
"sync_exclusive",
"do",
"if",
"state_or_event_name",
".",
"nil?",
"state_or_event_name",
"=",
"HookEvent",
".",
"any_state_or_event",
"(",
"hook_type",
")",
"end",
"async",
"=",
"false",
"if",
"async",
".",
"nil?",
"ensure_valid_callback_name!",
"(",
"hook_type",
",",
"state_or_event_name",
")",
"callback",
".",
"extend",
"(",
"Async",
")",
"if",
"async",
"==",
":async",
"hooks",
".",
"register",
"(",
"hook_type",
",",
"state_or_event_name",
",",
"callback",
")",
"end",
"end"
] |
Register callback for a given hook type
@param [HookEvent] hook_type
@param [Symbol] state_or_event_name
@param [Proc] callback
@example
observer.on HookEvent::Enter, :green
@api public
|
[
"Register",
"callback",
"for",
"a",
"given",
"hook",
"type"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/observer.rb#L71-L81
|
16,794
|
piotrmurach/finite_machine
|
lib/finite_machine/observer.rb
|
FiniteMachine.Observer.off
|
def off(hook_type, name = ANY_STATE, &callback)
sync_exclusive do
hooks.unregister hook_type, name, callback
end
end
|
ruby
|
def off(hook_type, name = ANY_STATE, &callback)
sync_exclusive do
hooks.unregister hook_type, name, callback
end
end
|
[
"def",
"off",
"(",
"hook_type",
",",
"name",
"=",
"ANY_STATE",
",",
"&",
"callback",
")",
"sync_exclusive",
"do",
"hooks",
".",
"unregister",
"hook_type",
",",
"name",
",",
"callback",
"end",
"end"
] |
Unregister callback for a given event
@api public
|
[
"Unregister",
"callback",
"for",
"a",
"given",
"event"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/observer.rb#L86-L90
|
16,795
|
piotrmurach/finite_machine
|
lib/finite_machine/observer.rb
|
FiniteMachine.Observer.emit
|
def emit(event, *data)
sync_exclusive do
[event.type].each do |hook_type|
any_state_or_event = HookEvent.any_state_or_event(hook_type)
[any_state_or_event, event.name].each do |event_name|
hooks[hook_type][event_name].each do |hook|
handle_callback(hook, event, *data)
off(hook_type, event_name, &hook) if hook.is_a?(Once)
end
end
end
end
end
|
ruby
|
def emit(event, *data)
sync_exclusive do
[event.type].each do |hook_type|
any_state_or_event = HookEvent.any_state_or_event(hook_type)
[any_state_or_event, event.name].each do |event_name|
hooks[hook_type][event_name].each do |hook|
handle_callback(hook, event, *data)
off(hook_type, event_name, &hook) if hook.is_a?(Once)
end
end
end
end
end
|
[
"def",
"emit",
"(",
"event",
",",
"*",
"data",
")",
"sync_exclusive",
"do",
"[",
"event",
".",
"type",
"]",
".",
"each",
"do",
"|",
"hook_type",
"|",
"any_state_or_event",
"=",
"HookEvent",
".",
"any_state_or_event",
"(",
"hook_type",
")",
"[",
"any_state_or_event",
",",
"event",
".",
"name",
"]",
".",
"each",
"do",
"|",
"event_name",
"|",
"hooks",
"[",
"hook_type",
"]",
"[",
"event_name",
"]",
".",
"each",
"do",
"|",
"hook",
"|",
"handle_callback",
"(",
"hook",
",",
"event",
",",
"data",
")",
"off",
"(",
"hook_type",
",",
"event_name",
",",
"hook",
")",
"if",
"hook",
".",
"is_a?",
"(",
"Once",
")",
"end",
"end",
"end",
"end",
"end"
] |
Execute each of the hooks in order with supplied data
@param [HookEvent] event
the hook event
@param [Array[Object]] data
@return [nil]
@api public
|
[
"Execute",
"each",
"of",
"the",
"hooks",
"in",
"order",
"with",
"supplied",
"data"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/observer.rb#L146-L158
|
16,796
|
piotrmurach/finite_machine
|
lib/finite_machine/observer.rb
|
FiniteMachine.Observer.handle_callback
|
def handle_callback(hook, event, *data)
to = machine.events_map.move_to(event.event_name, event.from, *data)
trans_event = TransitionEvent.new(event.event_name, event.from, to)
callable = create_callable(hook)
if hook.is_a?(Async)
defer(callable, trans_event, *data)
else
callable.(trans_event, *data)
end
end
|
ruby
|
def handle_callback(hook, event, *data)
to = machine.events_map.move_to(event.event_name, event.from, *data)
trans_event = TransitionEvent.new(event.event_name, event.from, to)
callable = create_callable(hook)
if hook.is_a?(Async)
defer(callable, trans_event, *data)
else
callable.(trans_event, *data)
end
end
|
[
"def",
"handle_callback",
"(",
"hook",
",",
"event",
",",
"*",
"data",
")",
"to",
"=",
"machine",
".",
"events_map",
".",
"move_to",
"(",
"event",
".",
"event_name",
",",
"event",
".",
"from",
",",
"data",
")",
"trans_event",
"=",
"TransitionEvent",
".",
"new",
"(",
"event",
".",
"event_name",
",",
"event",
".",
"from",
",",
"to",
")",
"callable",
"=",
"create_callable",
"(",
"hook",
")",
"if",
"hook",
".",
"is_a?",
"(",
"Async",
")",
"defer",
"(",
"callable",
",",
"trans_event",
",",
"data",
")",
"else",
"callable",
".",
"(",
"trans_event",
",",
"data",
")",
"end",
"end"
] |
Handle callback and decide if run synchronously or asynchronously
@param [Proc] :hook
The hook to evaluate
@param [HookEvent] :event
The event for which the hook is called
@param [Array[Object]] :data
@api private
|
[
"Handle",
"callback",
"and",
"decide",
"if",
"run",
"synchronously",
"or",
"asynchronously"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/observer.rb#L186-L196
|
16,797
|
piotrmurach/finite_machine
|
lib/finite_machine/observer.rb
|
FiniteMachine.Observer.defer
|
def defer(callable, trans_event, *data)
async_call = AsyncCall.new(machine, callable, trans_event, *data)
callback_queue.start unless callback_queue.running?
callback_queue << async_call
end
|
ruby
|
def defer(callable, trans_event, *data)
async_call = AsyncCall.new(machine, callable, trans_event, *data)
callback_queue.start unless callback_queue.running?
callback_queue << async_call
end
|
[
"def",
"defer",
"(",
"callable",
",",
"trans_event",
",",
"*",
"data",
")",
"async_call",
"=",
"AsyncCall",
".",
"new",
"(",
"machine",
",",
"callable",
",",
"trans_event",
",",
"data",
")",
"callback_queue",
".",
"start",
"unless",
"callback_queue",
".",
"running?",
"callback_queue",
"<<",
"async_call",
"end"
] |
Defer callback execution
@api private
|
[
"Defer",
"callback",
"execution"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/observer.rb#L201-L205
|
16,798
|
piotrmurach/finite_machine
|
lib/finite_machine/observer.rb
|
FiniteMachine.Observer.create_callable
|
def create_callable(hook)
callback = proc do |trans_event, *data|
machine.instance_exec(trans_event, *data, &hook)
end
Callable.new(callback)
end
|
ruby
|
def create_callable(hook)
callback = proc do |trans_event, *data|
machine.instance_exec(trans_event, *data, &hook)
end
Callable.new(callback)
end
|
[
"def",
"create_callable",
"(",
"hook",
")",
"callback",
"=",
"proc",
"do",
"|",
"trans_event",
",",
"*",
"data",
"|",
"machine",
".",
"instance_exec",
"(",
"trans_event",
",",
"data",
",",
"hook",
")",
"end",
"Callable",
".",
"new",
"(",
"callback",
")",
"end"
] |
Create callable instance
@api private
|
[
"Create",
"callable",
"instance"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/observer.rb#L210-L215
|
16,799
|
piotrmurach/finite_machine
|
lib/finite_machine/hook_event.rb
|
FiniteMachine.HookEvent.notify
|
def notify(subscriber, *data)
return unless subscriber.respond_to?(MESSAGE)
subscriber.public_send(MESSAGE, self, *data)
end
|
ruby
|
def notify(subscriber, *data)
return unless subscriber.respond_to?(MESSAGE)
subscriber.public_send(MESSAGE, self, *data)
end
|
[
"def",
"notify",
"(",
"subscriber",
",",
"*",
"data",
")",
"return",
"unless",
"subscriber",
".",
"respond_to?",
"(",
"MESSAGE",
")",
"subscriber",
".",
"public_send",
"(",
"MESSAGE",
",",
"self",
",",
"data",
")",
"end"
] |
Instantiate a new HookEvent object
@param [Symbol] name
The action or state name
@param [Symbol] event_name
The event name associated with this hook event.
@example
HookEvent.new(:green, :move, :green)
@return [self]
@api public
Notify subscriber about this event
@param [Observer] subscriber
the object subscribed to be notified about this event
@param [Array] data
the data associated with the triggered event
@return [nil]
@api public
|
[
"Instantiate",
"a",
"new",
"HookEvent",
"object"
] |
e54b9397e74aabd502672afb838a5ceb2d3caa2f
|
https://github.com/piotrmurach/finite_machine/blob/e54b9397e74aabd502672afb838a5ceb2d3caa2f/lib/finite_machine/hook_event.rb#L123-L127
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.