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
11,000
zendesk/ruby-kafka
lib/kafka/connection.rb
Kafka.Connection.write_request
def write_request(request, notification) message = Kafka::Protocol::RequestMessage.new( api_key: request.api_key, api_version: request.respond_to?(:api_version) ? request.api_version : 0, correlation_id: @correlation_id, client_id: @client_id, request: request, ) data = Kafka::Protocol::Encoder.encode_with(message) notification[:request_size] = data.bytesize @encoder.write_bytes(data) nil rescue Errno::ETIMEDOUT @logger.error "Timed out while writing request #{@correlation_id}" raise end
ruby
def write_request(request, notification) message = Kafka::Protocol::RequestMessage.new( api_key: request.api_key, api_version: request.respond_to?(:api_version) ? request.api_version : 0, correlation_id: @correlation_id, client_id: @client_id, request: request, ) data = Kafka::Protocol::Encoder.encode_with(message) notification[:request_size] = data.bytesize @encoder.write_bytes(data) nil rescue Errno::ETIMEDOUT @logger.error "Timed out while writing request #{@correlation_id}" raise end
[ "def", "write_request", "(", "request", ",", "notification", ")", "message", "=", "Kafka", "::", "Protocol", "::", "RequestMessage", ".", "new", "(", "api_key", ":", "request", ".", "api_key", ",", "api_version", ":", "request", ".", "respond_to?", "(", ":api_version", ")", "?", "request", ".", "api_version", ":", "0", ",", "correlation_id", ":", "@correlation_id", ",", "client_id", ":", "@client_id", ",", "request", ":", "request", ",", ")", "data", "=", "Kafka", "::", "Protocol", "::", "Encoder", ".", "encode_with", "(", "message", ")", "notification", "[", ":request_size", "]", "=", "data", ".", "bytesize", "@encoder", ".", "write_bytes", "(", "data", ")", "nil", "rescue", "Errno", "::", "ETIMEDOUT", "@logger", ".", "error", "\"Timed out while writing request #{@correlation_id}\"", "raise", "end" ]
Writes a request over the connection. @param request [#encode] the request that should be encoded and written. @return [nil]
[ "Writes", "a", "request", "over", "the", "connection", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/connection.rb#L156-L174
11,001
zendesk/ruby-kafka
lib/kafka/connection.rb
Kafka.Connection.read_response
def read_response(response_class, notification) @logger.debug "Waiting for response #{@correlation_id} from #{to_s}" data = @decoder.bytes notification[:response_size] = data.bytesize buffer = StringIO.new(data) response_decoder = Kafka::Protocol::Decoder.new(buffer) correlation_id = response_decoder.int32 response = response_class.decode(response_decoder) @logger.debug "Received response #{correlation_id} from #{to_s}" return correlation_id, response rescue Errno::ETIMEDOUT @logger.error "Timed out while waiting for response #{@correlation_id}" raise end
ruby
def read_response(response_class, notification) @logger.debug "Waiting for response #{@correlation_id} from #{to_s}" data = @decoder.bytes notification[:response_size] = data.bytesize buffer = StringIO.new(data) response_decoder = Kafka::Protocol::Decoder.new(buffer) correlation_id = response_decoder.int32 response = response_class.decode(response_decoder) @logger.debug "Received response #{correlation_id} from #{to_s}" return correlation_id, response rescue Errno::ETIMEDOUT @logger.error "Timed out while waiting for response #{@correlation_id}" raise end
[ "def", "read_response", "(", "response_class", ",", "notification", ")", "@logger", ".", "debug", "\"Waiting for response #{@correlation_id} from #{to_s}\"", "data", "=", "@decoder", ".", "bytes", "notification", "[", ":response_size", "]", "=", "data", ".", "bytesize", "buffer", "=", "StringIO", ".", "new", "(", "data", ")", "response_decoder", "=", "Kafka", "::", "Protocol", "::", "Decoder", ".", "new", "(", "buffer", ")", "correlation_id", "=", "response_decoder", ".", "int32", "response", "=", "response_class", ".", "decode", "(", "response_decoder", ")", "@logger", ".", "debug", "\"Received response #{correlation_id} from #{to_s}\"", "return", "correlation_id", ",", "response", "rescue", "Errno", "::", "ETIMEDOUT", "@logger", ".", "error", "\"Timed out while waiting for response #{@correlation_id}\"", "raise", "end" ]
Reads a response from the connection. @param response_class [#decode] an object that can decode the response from a given Decoder. @return [nil]
[ "Reads", "a", "response", "from", "the", "connection", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/connection.rb#L182-L200
11,002
zendesk/ruby-kafka
lib/kafka/producer.rb
Kafka.Producer.deliver_messages
def deliver_messages # There's no need to do anything if the buffer is empty. return if buffer_size == 0 @instrumenter.instrument("deliver_messages.producer") do |notification| message_count = buffer_size notification[:message_count] = message_count notification[:attempts] = 0 begin deliver_messages_with_retries(notification) ensure notification[:delivered_message_count] = message_count - buffer_size end end end
ruby
def deliver_messages # There's no need to do anything if the buffer is empty. return if buffer_size == 0 @instrumenter.instrument("deliver_messages.producer") do |notification| message_count = buffer_size notification[:message_count] = message_count notification[:attempts] = 0 begin deliver_messages_with_retries(notification) ensure notification[:delivered_message_count] = message_count - buffer_size end end end
[ "def", "deliver_messages", "# There's no need to do anything if the buffer is empty.", "return", "if", "buffer_size", "==", "0", "@instrumenter", ".", "instrument", "(", "\"deliver_messages.producer\"", ")", "do", "|", "notification", "|", "message_count", "=", "buffer_size", "notification", "[", ":message_count", "]", "=", "message_count", "notification", "[", ":attempts", "]", "=", "0", "begin", "deliver_messages_with_retries", "(", "notification", ")", "ensure", "notification", "[", ":delivered_message_count", "]", "=", "message_count", "-", "buffer_size", "end", "end", "end" ]
Sends all buffered messages to the Kafka brokers. Depending on the value of `required_acks` used when initializing the producer, this call may block until the specified number of replicas have acknowledged the writes. The `ack_timeout` setting places an upper bound on the amount of time the call will block before failing. @raise [DeliveryFailed] if not all messages could be successfully sent. @return [nil]
[ "Sends", "all", "buffered", "messages", "to", "the", "Kafka", "brokers", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/producer.rb#L242-L258
11,003
zendesk/ruby-kafka
lib/kafka/producer.rb
Kafka.Producer.send_offsets_to_transaction
def send_offsets_to_transaction(batch:, group_id:) @transaction_manager.send_offsets_to_txn(offsets: { batch.topic => { batch.partition => { offset: batch.last_offset + 1, leader_epoch: batch.leader_epoch } } }, group_id: group_id) end
ruby
def send_offsets_to_transaction(batch:, group_id:) @transaction_manager.send_offsets_to_txn(offsets: { batch.topic => { batch.partition => { offset: batch.last_offset + 1, leader_epoch: batch.leader_epoch } } }, group_id: group_id) end
[ "def", "send_offsets_to_transaction", "(", "batch", ":", ",", "group_id", ":", ")", "@transaction_manager", ".", "send_offsets_to_txn", "(", "offsets", ":", "{", "batch", ".", "topic", "=>", "{", "batch", ".", "partition", "=>", "{", "offset", ":", "batch", ".", "last_offset", "+", "1", ",", "leader_epoch", ":", "batch", ".", "leader_epoch", "}", "}", "}", ",", "group_id", ":", "group_id", ")", "end" ]
Sends batch last offset to the consumer group coordinator, and also marks this offset as part of the current transaction. This offset will be considered committed only if the transaction is committed successfully. This method should be used when you need to batch consumed and produced messages together, typically in a consume-transform-produce pattern. Thus, the specified group_id should be the same as config parameter group_id of the used consumer. @return [nil]
[ "Sends", "batch", "last", "offset", "to", "the", "consumer", "group", "coordinator", "and", "also", "marks", "this", "offset", "as", "part", "of", "the", "current", "transaction", ".", "This", "offset", "will", "be", "considered", "committed", "only", "if", "the", "transaction", "is", "committed", "successfully", "." ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/producer.rb#L343-L345
11,004
zendesk/ruby-kafka
lib/kafka/producer.rb
Kafka.Producer.transaction
def transaction raise 'This method requires a block' unless block_given? begin_transaction yield commit_transaction rescue Kafka::Producer::AbortTransaction abort_transaction rescue abort_transaction raise end
ruby
def transaction raise 'This method requires a block' unless block_given? begin_transaction yield commit_transaction rescue Kafka::Producer::AbortTransaction abort_transaction rescue abort_transaction raise end
[ "def", "transaction", "raise", "'This method requires a block'", "unless", "block_given?", "begin_transaction", "yield", "commit_transaction", "rescue", "Kafka", "::", "Producer", "::", "AbortTransaction", "abort_transaction", "rescue", "abort_transaction", "raise", "end" ]
Syntactic sugar to enable easier transaction usage. Do the following steps - Start the transaction (with Producer#begin_transaction) - Yield the given block - Commit the transaction (with Producer#commit_transaction) If the block raises exception, the transaction is automatically aborted *before* bubble up the exception. If the block raises Kafka::Producer::AbortTransaction indicator exception, it aborts the transaction silently, without throwing up that exception. @return [nil]
[ "Syntactic", "sugar", "to", "enable", "easier", "transaction", "usage", ".", "Do", "the", "following", "steps" ]
2a73471b6a607a52dc85c79301ba522acb4566b5
https://github.com/zendesk/ruby-kafka/blob/2a73471b6a607a52dc85c79301ba522acb4566b5/lib/kafka/producer.rb#L360-L370
11,005
teamcapybara/capybara
lib/capybara/session.rb
Capybara.Session.open_new_window
def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end
ruby
def open_new_window(kind = :tab) window_opened_by do if driver.method(:open_new_window).arity.zero? driver.open_new_window else driver.open_new_window(kind) end end end
[ "def", "open_new_window", "(", "kind", "=", ":tab", ")", "window_opened_by", "do", "if", "driver", ".", "method", "(", ":open_new_window", ")", ".", "arity", ".", "zero?", "driver", ".", "open_new_window", "else", "driver", ".", "open_new_window", "(", "kind", ")", "end", "end", "end" ]
Open new window. Current window doesn't change as the result of this call. It should be switched to explicitly. @return [Capybara::Window] window that has been opened
[ "Open", "new", "window", ".", "Current", "window", "doesn", "t", "change", "as", "the", "result", "of", "this", "call", ".", "It", "should", "be", "switched", "to", "explicitly", "." ]
3819078c820c5cd3be6f0bc9e8b1b0cc1190bc41
https://github.com/teamcapybara/capybara/blob/3819078c820c5cd3be6f0bc9e8b1b0cc1190bc41/lib/capybara/session.rb#L461-L469
11,006
lostisland/faraday
lib/faraday/autoload.rb
Faraday.AutoloadHelper.autoload_all
def autoload_all(prefix, options) if prefix =~ %r{^faraday(/|$)}i prefix = File.join(Faraday.root_path, prefix) end options.each do |const_name, path| autoload const_name, File.join(prefix, path) end end
ruby
def autoload_all(prefix, options) if prefix =~ %r{^faraday(/|$)}i prefix = File.join(Faraday.root_path, prefix) end options.each do |const_name, path| autoload const_name, File.join(prefix, path) end end
[ "def", "autoload_all", "(", "prefix", ",", "options", ")", "if", "prefix", "=~", "%r{", "}i", "prefix", "=", "File", ".", "join", "(", "Faraday", ".", "root_path", ",", "prefix", ")", "end", "options", ".", "each", "do", "|", "const_name", ",", "path", "|", "autoload", "const_name", ",", "File", ".", "join", "(", "prefix", ",", "path", ")", "end", "end" ]
Registers the constants to be auto loaded. @param prefix [String] The require prefix. If the path is inside Faraday, then it will be prefixed with the root path of this loaded Faraday version. @param options [{ Symbol => String }] library names. @example Faraday.autoload_all 'faraday/foo', Bar: 'bar' # requires faraday/foo/bar to load Faraday::Bar. Faraday::Bar @return [void]
[ "Registers", "the", "constants", "to", "be", "auto", "loaded", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/autoload.rb#L25-L33
11,007
lostisland/faraday
lib/faraday/autoload.rb
Faraday.AutoloadHelper.all_loaded_constants
def all_loaded_constants constants .map { |c| const_get(c) } .select { |a| a.respond_to?(:loaded?) && a.loaded? } end
ruby
def all_loaded_constants constants .map { |c| const_get(c) } .select { |a| a.respond_to?(:loaded?) && a.loaded? } end
[ "def", "all_loaded_constants", "constants", ".", "map", "{", "|", "c", "|", "const_get", "(", "c", ")", "}", ".", "select", "{", "|", "a", "|", "a", ".", "respond_to?", "(", ":loaded?", ")", "&&", "a", ".", "loaded?", "}", "end" ]
Filters the module's contents with those that have been already autoloaded. @return [Array<Class, Module>]
[ "Filters", "the", "module", "s", "contents", "with", "those", "that", "have", "been", "already", "autoloaded", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/autoload.rb#L49-L53
11,008
lostisland/faraday
spec/support/helper_methods.rb
Faraday.HelperMethods.parse_multipart
def parse_multipart(boundary, body) reader = MultipartParser::Reader.new(boundary) result = { errors: [], parts: [] } def result.part(name) hash = self[:parts].detect { |h| h[:part].name == name } [hash[:part], hash[:body].join] end reader.on_part do |part| result[:parts] << thispart = { part: part, body: [] } part.on_data do |chunk| thispart[:body] << chunk end end reader.on_error do |msg| result[:errors] << msg end reader.write(body) result end
ruby
def parse_multipart(boundary, body) reader = MultipartParser::Reader.new(boundary) result = { errors: [], parts: [] } def result.part(name) hash = self[:parts].detect { |h| h[:part].name == name } [hash[:part], hash[:body].join] end reader.on_part do |part| result[:parts] << thispart = { part: part, body: [] } part.on_data do |chunk| thispart[:body] << chunk end end reader.on_error do |msg| result[:errors] << msg end reader.write(body) result end
[ "def", "parse_multipart", "(", "boundary", ",", "body", ")", "reader", "=", "MultipartParser", "::", "Reader", ".", "new", "(", "boundary", ")", "result", "=", "{", "errors", ":", "[", "]", ",", "parts", ":", "[", "]", "}", "def", "result", ".", "part", "(", "name", ")", "hash", "=", "self", "[", ":parts", "]", ".", "detect", "{", "|", "h", "|", "h", "[", ":part", "]", ".", "name", "==", "name", "}", "[", "hash", "[", ":part", "]", ",", "hash", "[", ":body", "]", ".", "join", "]", "end", "reader", ".", "on_part", "do", "|", "part", "|", "result", "[", ":parts", "]", "<<", "thispart", "=", "{", "part", ":", "part", ",", "body", ":", "[", "]", "}", "part", ".", "on_data", "do", "|", "chunk", "|", "thispart", "[", ":body", "]", "<<", "chunk", "end", "end", "reader", ".", "on_error", "do", "|", "msg", "|", "result", "[", ":errors", "]", "<<", "msg", "end", "reader", ".", "write", "(", "body", ")", "result", "end" ]
parse a multipart MIME message, returning a hash of any multipart errors
[ "parse", "a", "multipart", "MIME", "message", "returning", "a", "hash", "of", "any", "multipart", "errors" ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/spec/support/helper_methods.rb#L100-L122
11,009
lostisland/faraday
lib/faraday/dependency_loader.rb
Faraday.DependencyLoader.dependency
def dependency(lib = nil) lib ? require(lib) : yield rescue LoadError, NameError => e self.load_error = e end
ruby
def dependency(lib = nil) lib ? require(lib) : yield rescue LoadError, NameError => e self.load_error = e end
[ "def", "dependency", "(", "lib", "=", "nil", ")", "lib", "?", "require", "(", "lib", ")", ":", "yield", "rescue", "LoadError", ",", "NameError", "=>", "e", "self", ".", "load_error", "=", "e", "end" ]
Executes a block which should try to require and reference dependent libraries
[ "Executes", "a", "block", "which", "should", "try", "to", "require", "and", "reference", "dependent", "libraries" ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/dependency_loader.rb#L10-L14
11,010
lostisland/faraday
lib/faraday/connection.rb
Faraday.Connection.default_parallel_manager
def default_parallel_manager @default_parallel_manager ||= begin adapter = @builder.adapter.klass if @builder.adapter if support_parallel?(adapter) adapter.setup_parallel_manager elsif block_given? yield end end end
ruby
def default_parallel_manager @default_parallel_manager ||= begin adapter = @builder.adapter.klass if @builder.adapter if support_parallel?(adapter) adapter.setup_parallel_manager elsif block_given? yield end end end
[ "def", "default_parallel_manager", "@default_parallel_manager", "||=", "begin", "adapter", "=", "@builder", ".", "adapter", ".", "klass", "if", "@builder", ".", "adapter", "if", "support_parallel?", "(", "adapter", ")", "adapter", ".", "setup_parallel_manager", "elsif", "block_given?", "yield", "end", "end", "end" ]
Check if the adapter is parallel-capable. @yield if the adapter isn't parallel-capable, or if no adapter is set yet. @return [Object, nil] a parallel manager or nil if yielded @api private
[ "Check", "if", "the", "adapter", "is", "parallel", "-", "capable", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/connection.rb#L355-L365
11,011
lostisland/faraday
lib/faraday/connection.rb
Faraday.Connection.url_prefix=
def url_prefix=(url, encoder = nil) uri = @url_prefix = Utils.URI(url) self.path_prefix = uri.path params.merge_query(uri.query, encoder) uri.query = nil with_uri_credentials(uri) do |user, password| basic_auth user, password uri.user = uri.password = nil end end
ruby
def url_prefix=(url, encoder = nil) uri = @url_prefix = Utils.URI(url) self.path_prefix = uri.path params.merge_query(uri.query, encoder) uri.query = nil with_uri_credentials(uri) do |user, password| basic_auth user, password uri.user = uri.password = nil end end
[ "def", "url_prefix", "=", "(", "url", ",", "encoder", "=", "nil", ")", "uri", "=", "@url_prefix", "=", "Utils", ".", "URI", "(", "url", ")", "self", ".", "path_prefix", "=", "uri", ".", "path", "params", ".", "merge_query", "(", "uri", ".", "query", ",", "encoder", ")", "uri", ".", "query", "=", "nil", "with_uri_credentials", "(", "uri", ")", "do", "|", "user", ",", "password", "|", "basic_auth", "user", ",", "password", "uri", ".", "user", "=", "uri", ".", "password", "=", "nil", "end", "end" ]
Parses the given URL with URI and stores the individual components in this connection. These components serve as defaults for requests made by this connection. @param url [String, URI] @param encoder [Object] @example conn = Faraday::Connection.new { ... } conn.url_prefix = "https://sushi.com/api" conn.scheme # => https conn.path_prefix # => "/api" conn.get("nigiri?page=2") # accesses https://sushi.com/api/nigiri
[ "Parses", "the", "given", "URL", "with", "URI", "and", "stores", "the", "individual", "components", "in", "this", "connection", ".", "These", "components", "serve", "as", "defaults", "for", "requests", "made", "by", "this", "connection", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/connection.rb#L420-L431
11,012
lostisland/faraday
lib/faraday/connection.rb
Faraday.Connection.build_url
def build_url(url = nil, extra_params = nil) uri = build_exclusive_url(url) query_values = params.dup.merge_query(uri.query, options.params_encoder) query_values.update(extra_params) if extra_params uri.query = if query_values.empty? nil else query_values.to_query(options.params_encoder) end uri end
ruby
def build_url(url = nil, extra_params = nil) uri = build_exclusive_url(url) query_values = params.dup.merge_query(uri.query, options.params_encoder) query_values.update(extra_params) if extra_params uri.query = if query_values.empty? nil else query_values.to_query(options.params_encoder) end uri end
[ "def", "build_url", "(", "url", "=", "nil", ",", "extra_params", "=", "nil", ")", "uri", "=", "build_exclusive_url", "(", "url", ")", "query_values", "=", "params", ".", "dup", ".", "merge_query", "(", "uri", ".", "query", ",", "options", ".", "params_encoder", ")", "query_values", ".", "update", "(", "extra_params", ")", "if", "extra_params", "uri", ".", "query", "=", "if", "query_values", ".", "empty?", "nil", "else", "query_values", ".", "to_query", "(", "options", ".", "params_encoder", ")", "end", "uri", "end" ]
Takes a relative url for a request and combines it with the defaults set on the connection instance. @param url [String] @param extra_params [Hash] @example conn = Faraday::Connection.new { ... } conn.url_prefix = "https://sushi.com/api?token=abc" conn.scheme # => https conn.path_prefix # => "/api" conn.build_url("nigiri?page=2") # => https://sushi.com/api/nigiri?token=abc&page=2 conn.build_url("nigiri", page: 2) # => https://sushi.com/api/nigiri?token=abc&page=2
[ "Takes", "a", "relative", "url", "for", "a", "request", "and", "combines", "it", "with", "the", "defaults", "set", "on", "the", "connection", "instance", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/connection.rb#L464-L477
11,013
lostisland/faraday
lib/faraday/connection.rb
Faraday.Connection.build_request
def build_request(method) Request.create(method) do |req| req.params = params.dup req.headers = headers.dup req.options = options yield(req) if block_given? end end
ruby
def build_request(method) Request.create(method) do |req| req.params = params.dup req.headers = headers.dup req.options = options yield(req) if block_given? end end
[ "def", "build_request", "(", "method", ")", "Request", ".", "create", "(", "method", ")", "do", "|", "req", "|", "req", ".", "params", "=", "params", ".", "dup", "req", ".", "headers", "=", "headers", ".", "dup", "req", ".", "options", "=", "options", "yield", "(", "req", ")", "if", "block_given?", "end", "end" ]
Creates and configures the request object. @param method [Symbol] @yield [Faraday::Request] if block given @return [Faraday::Request]
[ "Creates", "and", "configures", "the", "request", "object", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/connection.rb#L513-L520
11,014
lostisland/faraday
lib/faraday/connection.rb
Faraday.Connection.build_exclusive_url
def build_exclusive_url(url = nil, params = nil, params_encoder = nil) url = nil if url.respond_to?(:empty?) && url.empty? base = url_prefix if url && base.path && base.path !~ %r{/$} base = base.dup base.path = base.path + '/' # ensure trailing slash end uri = url ? base + url : base if params uri.query = params.to_query(params_encoder || options.params_encoder) end # rubocop:disable Style/SafeNavigation uri.query = nil if uri.query && uri.query.empty? # rubocop:enable Style/SafeNavigation uri end
ruby
def build_exclusive_url(url = nil, params = nil, params_encoder = nil) url = nil if url.respond_to?(:empty?) && url.empty? base = url_prefix if url && base.path && base.path !~ %r{/$} base = base.dup base.path = base.path + '/' # ensure trailing slash end uri = url ? base + url : base if params uri.query = params.to_query(params_encoder || options.params_encoder) end # rubocop:disable Style/SafeNavigation uri.query = nil if uri.query && uri.query.empty? # rubocop:enable Style/SafeNavigation uri end
[ "def", "build_exclusive_url", "(", "url", "=", "nil", ",", "params", "=", "nil", ",", "params_encoder", "=", "nil", ")", "url", "=", "nil", "if", "url", ".", "respond_to?", "(", ":empty?", ")", "&&", "url", ".", "empty?", "base", "=", "url_prefix", "if", "url", "&&", "base", ".", "path", "&&", "base", ".", "path", "!~", "%r{", "}", "base", "=", "base", ".", "dup", "base", ".", "path", "=", "base", ".", "path", "+", "'/'", "# ensure trailing slash", "end", "uri", "=", "url", "?", "base", "+", "url", ":", "base", "if", "params", "uri", ".", "query", "=", "params", ".", "to_query", "(", "params_encoder", "||", "options", ".", "params_encoder", ")", "end", "# rubocop:disable Style/SafeNavigation", "uri", ".", "query", "=", "nil", "if", "uri", ".", "query", "&&", "uri", ".", "query", ".", "empty?", "# rubocop:enable Style/SafeNavigation", "uri", "end" ]
Build an absolute URL based on url_prefix. @param url [String, URI] @param params [Faraday::Utils::ParamsHash] A Faraday::Utils::ParamsHash to replace the query values of the resulting url (default: nil). @return [URI]
[ "Build", "an", "absolute", "URL", "based", "on", "url_prefix", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/connection.rb#L530-L545
11,015
lostisland/faraday
lib/faraday/utils.rb
Faraday.Utils.normalize_path
def normalize_path(url) url = URI(url) (url.path.start_with?('/') ? url.path : '/' + url.path) + (url.query ? "?#{sort_query_params(url.query)}" : '') end
ruby
def normalize_path(url) url = URI(url) (url.path.start_with?('/') ? url.path : '/' + url.path) + (url.query ? "?#{sort_query_params(url.query)}" : '') end
[ "def", "normalize_path", "(", "url", ")", "url", "=", "URI", "(", "url", ")", "(", "url", ".", "path", ".", "start_with?", "(", "'/'", ")", "?", "url", ".", "path", ":", "'/'", "+", "url", ".", "path", ")", "+", "(", "url", ".", "query", "?", "\"?#{sort_query_params(url.query)}\"", ":", "''", ")", "end" ]
Receives a String or URI and returns just the path with the query string sorted.
[ "Receives", "a", "String", "or", "URI", "and", "returns", "just", "the", "path", "with", "the", "query", "string", "sorted", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/utils.rb#L82-L86
11,016
lostisland/faraday
lib/faraday/utils.rb
Faraday.Utils.deep_merge!
def deep_merge!(target, hash) hash.each do |key, value| target[key] = if value.is_a?(Hash) && target[key].is_a?(Hash) deep_merge(target[key], value) else value end end target end
ruby
def deep_merge!(target, hash) hash.each do |key, value| target[key] = if value.is_a?(Hash) && target[key].is_a?(Hash) deep_merge(target[key], value) else value end end target end
[ "def", "deep_merge!", "(", "target", ",", "hash", ")", "hash", ".", "each", "do", "|", "key", ",", "value", "|", "target", "[", "key", "]", "=", "if", "value", ".", "is_a?", "(", "Hash", ")", "&&", "target", "[", "key", "]", ".", "is_a?", "(", "Hash", ")", "deep_merge", "(", "target", "[", "key", "]", ",", "value", ")", "else", "value", "end", "end", "target", "end" ]
Recursive hash update
[ "Recursive", "hash", "update" ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/utils.rb#L89-L98
11,017
lostisland/faraday
lib/faraday/request.rb
Faraday.Request.url
def url(path, params = nil) if path.respond_to? :query if (query = path.query) path = path.dup path.query = nil end else anchor_index = path.index('#') path = path.slice(0, anchor_index) unless anchor_index.nil? path, query = path.split('?', 2) end self.path = path self.params.merge_query query, options.params_encoder self.params.update(params) if params end
ruby
def url(path, params = nil) if path.respond_to? :query if (query = path.query) path = path.dup path.query = nil end else anchor_index = path.index('#') path = path.slice(0, anchor_index) unless anchor_index.nil? path, query = path.split('?', 2) end self.path = path self.params.merge_query query, options.params_encoder self.params.update(params) if params end
[ "def", "url", "(", "path", ",", "params", "=", "nil", ")", "if", "path", ".", "respond_to?", ":query", "if", "(", "query", "=", "path", ".", "query", ")", "path", "=", "path", ".", "dup", "path", ".", "query", "=", "nil", "end", "else", "anchor_index", "=", "path", ".", "index", "(", "'#'", ")", "path", "=", "path", ".", "slice", "(", "0", ",", "anchor_index", ")", "unless", "anchor_index", ".", "nil?", "path", ",", "query", "=", "path", ".", "split", "(", "'?'", ",", "2", ")", "end", "self", ".", "path", "=", "path", "self", ".", "params", ".", "merge_query", "query", ",", "options", ".", "params_encoder", "self", ".", "params", ".", "update", "(", "params", ")", "if", "params", "end" ]
Update path and params. @param path [URI, String] @param params [Hash, nil] @return [void]
[ "Update", "path", "and", "params", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/request.rb#L86-L100
11,018
lostisland/faraday
lib/faraday/request.rb
Faraday.Request.marshal_dump
def marshal_dump { method: method, body: body, headers: headers, path: path, params: params, options: options } end
ruby
def marshal_dump { method: method, body: body, headers: headers, path: path, params: params, options: options } end
[ "def", "marshal_dump", "{", "method", ":", "method", ",", "body", ":", "body", ",", "headers", ":", "headers", ",", "path", ":", "path", ",", "params", ":", "params", ",", "options", ":", "options", "}", "end" ]
Marshal serialization support. @return [Hash] the hash ready to be serialized in Marshal.
[ "Marshal", "serialization", "support", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/request.rb#L117-L126
11,019
lostisland/faraday
lib/faraday/request.rb
Faraday.Request.marshal_load
def marshal_load(serialised) self.method = serialised[:method] self.body = serialised[:body] self.headers = serialised[:headers] self.path = serialised[:path] self.params = serialised[:params] self.options = serialised[:options] end
ruby
def marshal_load(serialised) self.method = serialised[:method] self.body = serialised[:body] self.headers = serialised[:headers] self.path = serialised[:path] self.params = serialised[:params] self.options = serialised[:options] end
[ "def", "marshal_load", "(", "serialised", ")", "self", ".", "method", "=", "serialised", "[", ":method", "]", "self", ".", "body", "=", "serialised", "[", ":body", "]", "self", ".", "headers", "=", "serialised", "[", ":headers", "]", "self", ".", "path", "=", "serialised", "[", ":path", "]", "self", ".", "params", "=", "serialised", "[", ":params", "]", "self", ".", "options", "=", "serialised", "[", ":options", "]", "end" ]
Marshal serialization support. Restores the instance variables according to the +serialised+. @param serialised [Hash] the serialised object.
[ "Marshal", "serialization", "support", ".", "Restores", "the", "instance", "variables", "according", "to", "the", "+", "serialised", "+", "." ]
3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70
https://github.com/lostisland/faraday/blob/3abe9d1eea4bdf61cdf7b76ff9f1ae7e09482e70/lib/faraday/request.rb#L131-L138
11,020
aws/aws-sdk-ruby
gems/aws-sdk-s3/lib/aws-sdk-s3/client.rb
Aws::S3.Client.get_bucket_policy
def get_bucket_policy(params = {}, options = {}, &block) req = build_request(:get_bucket_policy, params) req.send_request(options, &block) end
ruby
def get_bucket_policy(params = {}, options = {}, &block) req = build_request(:get_bucket_policy, params) req.send_request(options, &block) end
[ "def", "get_bucket_policy", "(", "params", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "req", "=", "build_request", "(", ":get_bucket_policy", ",", "params", ")", "req", ".", "send_request", "(", "options", ",", "block", ")", "end" ]
Returns the policy of a specified bucket. @option params [required, String] :bucket @return [Types::GetBucketPolicyOutput] Returns a {Seahorse::Client::Response response} object which responds to the following methods: * {Types::GetBucketPolicyOutput#policy #policy} => IO @example Example: To get bucket policy # The following example returns bucket policy associated with a bucket. resp = client.get_bucket_policy({ bucket: "examplebucket", }) resp.to_h outputs the following: { policy: "{\"Version\":\"2008-10-17\",\"Id\":\"LogPolicy\",\"Statement\":[{\"Sid\":\"Enables the log delivery group to publish logs to your bucket \",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"111122223333\"},\"Action\":[\"s3:GetBucketAcl\",\"s3:GetObjectAcl\",\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::policytest1/*\",\"arn:aws:s3:::policytest1\"]}]}", } @example Request syntax with placeholder values resp = client.get_bucket_policy({ bucket: "BucketName", # required }) @example Response structure resp.policy #=> String @see http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetBucketPolicy AWS API Documentation @overload get_bucket_policy(params = {}) @param [Hash] params ({})
[ "Returns", "the", "policy", "of", "a", "specified", "bucket", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-s3/lib/aws-sdk-s3/client.rb#L2337-L2340
11,021
aws/aws-sdk-ruby
gems/aws-sdk-s3/lib/aws-sdk-s3/client.rb
Aws::S3.Client.get_object
def get_object(params = {}, options = {}, &block) req = build_request(:get_object, params) req.send_request(options, &block) end
ruby
def get_object(params = {}, options = {}, &block) req = build_request(:get_object, params) req.send_request(options, &block) end
[ "def", "get_object", "(", "params", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "req", "=", "build_request", "(", ":get_object", ",", "params", ")", "req", ".", "send_request", "(", "options", ",", "block", ")", "end" ]
Retrieves objects from Amazon S3. @option params [String, IO] :response_target Where to write response data, file path, or IO object. @option params [required, String] :bucket @option params [String] :if_match Return the object only if its entity tag (ETag) is the same as the one specified, otherwise return a 412 (precondition failed). @option params [Time,DateTime,Date,Integer,String] :if_modified_since Return the object only if it has been modified since the specified time, otherwise return a 304 (not modified). @option params [String] :if_none_match Return the object only if its entity tag (ETag) is different from the one specified, otherwise return a 304 (not modified). @option params [Time,DateTime,Date,Integer,String] :if_unmodified_since Return the object only if it has not been modified since the specified time, otherwise return a 412 (precondition failed). @option params [required, String] :key @option params [String] :range Downloads the specified range bytes of an object. For more information about the HTTP Range header, go to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35. @option params [String] :response_cache_control Sets the Cache-Control header of the response. @option params [String] :response_content_disposition Sets the Content-Disposition header of the response @option params [String] :response_content_encoding Sets the Content-Encoding header of the response. @option params [String] :response_content_language Sets the Content-Language header of the response. @option params [String] :response_content_type Sets the Content-Type header of the response. @option params [Time,DateTime,Date,Integer,String] :response_expires Sets the Expires header of the response. @option params [String] :version_id VersionId used to reference a specific version of the object. @option params [String] :sse_customer_algorithm Specifies the algorithm to use to when encrypting the object (e.g., AES256). @option params [String] :sse_customer_key Specifies the customer-provided encryption key for Amazon S3 to use in encrypting data. This value is used to store the object and then it is discarded; Amazon does not store the encryption key. The key must be appropriate for use with the algorithm specified in the x-amz-server-side​-encryption​-customer-algorithm header. @option params [String] :sse_customer_key_md5 Specifies the 128-bit MD5 digest of the encryption key according to RFC 1321. Amazon S3 uses this header for a message integrity check to ensure the encryption key was transmitted without error. @option params [String] :request_payer Confirms that the requester knows that she or he will be charged for the request. Bucket owners need not specify this parameter in their requests. Documentation on downloading objects from requester pays buckets can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html @option params [Integer] :part_number Part number of the object being read. This is a positive integer between 1 and 10,000. Effectively performs a 'ranged' GET request for the part specified. Useful for downloading just a part of an object. @return [Types::GetObjectOutput] Returns a {Seahorse::Client::Response response} object which responds to the following methods: * {Types::GetObjectOutput#body #body} => IO * {Types::GetObjectOutput#delete_marker #delete_marker} => Boolean * {Types::GetObjectOutput#accept_ranges #accept_ranges} => String * {Types::GetObjectOutput#expiration #expiration} => String * {Types::GetObjectOutput#restore #restore} => String * {Types::GetObjectOutput#last_modified #last_modified} => Time * {Types::GetObjectOutput#content_length #content_length} => Integer * {Types::GetObjectOutput#etag #etag} => String * {Types::GetObjectOutput#missing_meta #missing_meta} => Integer * {Types::GetObjectOutput#version_id #version_id} => String * {Types::GetObjectOutput#cache_control #cache_control} => String * {Types::GetObjectOutput#content_disposition #content_disposition} => String * {Types::GetObjectOutput#content_encoding #content_encoding} => String * {Types::GetObjectOutput#content_language #content_language} => String * {Types::GetObjectOutput#content_range #content_range} => String * {Types::GetObjectOutput#content_type #content_type} => String * {Types::GetObjectOutput#expires #expires} => Time * {Types::GetObjectOutput#expires_string #expires_string} => String * {Types::GetObjectOutput#website_redirect_location #website_redirect_location} => String * {Types::GetObjectOutput#server_side_encryption #server_side_encryption} => String * {Types::GetObjectOutput#metadata #metadata} => Hash&lt;String,String&gt; * {Types::GetObjectOutput#sse_customer_algorithm #sse_customer_algorithm} => String * {Types::GetObjectOutput#sse_customer_key_md5 #sse_customer_key_md5} => String * {Types::GetObjectOutput#ssekms_key_id #ssekms_key_id} => String * {Types::GetObjectOutput#storage_class #storage_class} => String * {Types::GetObjectOutput#request_charged #request_charged} => String * {Types::GetObjectOutput#replication_status #replication_status} => String * {Types::GetObjectOutput#parts_count #parts_count} => Integer * {Types::GetObjectOutput#tag_count #tag_count} => Integer * {Types::GetObjectOutput#object_lock_mode #object_lock_mode} => String * {Types::GetObjectOutput#object_lock_retain_until_date #object_lock_retain_until_date} => Time * {Types::GetObjectOutput#object_lock_legal_hold_status #object_lock_legal_hold_status} => String @example Example: To retrieve an object # The following example retrieves an object for an S3 bucket. resp = client.get_object({ bucket: "examplebucket", key: "HappyFace.jpg", }) resp.to_h outputs the following: { accept_ranges: "bytes", content_length: 3191, content_type: "image/jpeg", etag: "\"6805f2cfc46c0f04559748bb039d69ae\"", last_modified: Time.parse("Thu, 15 Dec 2016 01:19:41 GMT"), metadata: { }, tag_count: 2, version_id: "null", } @example Example: To retrieve a byte range of an object # The following example retrieves an object for an S3 bucket. The request specifies the range header to retrieve a # specific byte range. resp = client.get_object({ bucket: "examplebucket", key: "SampleFile.txt", range: "bytes=0-9", }) resp.to_h outputs the following: { accept_ranges: "bytes", content_length: 10, content_range: "bytes 0-9/43", content_type: "text/plain", etag: "\"0d94420ffd0bc68cd3d152506b97a9cc\"", last_modified: Time.parse("Thu, 09 Oct 2014 22:57:28 GMT"), metadata: { }, version_id: "null", } @example Download an object to disk # stream object directly to disk resp = s3.get_object( response_target: '/path/to/file', bucket: 'bucket-name', key: 'object-key') # you can still access other response data resp.metadata #=> { ... } resp.etag #=> "..." @example Download object into memory # omit :response_target to download to a StringIO in memory resp = s3.get_object(bucket: 'bucket-name', key: 'object-key') # call #read or #string on the response body resp.body.read #=> '...' @example Streaming data to a block # WARNING: yielding data to a block disables retries of networking errors File.open('/path/to/file', 'wb') do |file| s3.get_object(bucket: 'bucket-name', key: 'object-key') do |chunk| file.write(chunk) end end @example Request syntax with placeholder values resp = client.get_object({ bucket: "BucketName", # required if_match: "IfMatch", if_modified_since: Time.now, if_none_match: "IfNoneMatch", if_unmodified_since: Time.now, key: "ObjectKey", # required range: "Range", response_cache_control: "ResponseCacheControl", response_content_disposition: "ResponseContentDisposition", response_content_encoding: "ResponseContentEncoding", response_content_language: "ResponseContentLanguage", response_content_type: "ResponseContentType", response_expires: Time.now, version_id: "ObjectVersionId", sse_customer_algorithm: "SSECustomerAlgorithm", sse_customer_key: "SSECustomerKey", sse_customer_key_md5: "SSECustomerKeyMD5", request_payer: "requester", # accepts requester part_number: 1, }) @example Response structure resp.body #=> IO resp.delete_marker #=> Boolean resp.accept_ranges #=> String resp.expiration #=> String resp.restore #=> String resp.last_modified #=> Time resp.content_length #=> Integer resp.etag #=> String resp.missing_meta #=> Integer resp.version_id #=> String resp.cache_control #=> String resp.content_disposition #=> String resp.content_encoding #=> String resp.content_language #=> String resp.content_range #=> String resp.content_type #=> String resp.expires #=> Time resp.expires_string #=> String resp.website_redirect_location #=> String resp.server_side_encryption #=> String, one of "AES256", "aws:kms" resp.metadata #=> Hash resp.metadata["MetadataKey"] #=> String resp.sse_customer_algorithm #=> String resp.sse_customer_key_md5 #=> String resp.ssekms_key_id #=> String resp.storage_class #=> String, one of "STANDARD", "REDUCED_REDUNDANCY", "STANDARD_IA", "ONEZONE_IA", "INTELLIGENT_TIERING", "GLACIER", "DEEP_ARCHIVE" resp.request_charged #=> String, one of "requester" resp.replication_status #=> String, one of "COMPLETE", "PENDING", "FAILED", "REPLICA" resp.parts_count #=> Integer resp.tag_count #=> Integer resp.object_lock_mode #=> String, one of "GOVERNANCE", "COMPLIANCE" resp.object_lock_retain_until_date #=> Time resp.object_lock_legal_hold_status #=> String, one of "ON", "OFF" @see http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObject AWS API Documentation @overload get_object(params = {}) @param [Hash] params ({})
[ "Retrieves", "objects", "from", "Amazon", "S3", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-s3/lib/aws-sdk-s3/client.rb#L2900-L2903
11,022
aws/aws-sdk-ruby
gems/aws-sdk-s3/lib/aws-sdk-s3/client.rb
Aws::S3.Client.get_object_torrent
def get_object_torrent(params = {}, options = {}, &block) req = build_request(:get_object_torrent, params) req.send_request(options, &block) end
ruby
def get_object_torrent(params = {}, options = {}, &block) req = build_request(:get_object_torrent, params) req.send_request(options, &block) end
[ "def", "get_object_torrent", "(", "params", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "req", "=", "build_request", "(", ":get_object_torrent", ",", "params", ")", "req", ".", "send_request", "(", "options", ",", "block", ")", "end" ]
Return torrent files from a bucket. @option params [String, IO] :response_target Where to write response data, file path, or IO object. @option params [required, String] :bucket @option params [required, String] :key @option params [String] :request_payer Confirms that the requester knows that she or he will be charged for the request. Bucket owners need not specify this parameter in their requests. Documentation on downloading objects from requester pays buckets can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html @return [Types::GetObjectTorrentOutput] Returns a {Seahorse::Client::Response response} object which responds to the following methods: * {Types::GetObjectTorrentOutput#body #body} => IO * {Types::GetObjectTorrentOutput#request_charged #request_charged} => String @example Example: To retrieve torrent files for an object # The following example retrieves torrent files of an object. resp = client.get_object_torrent({ bucket: "examplebucket", key: "HappyFace.jpg", }) resp.to_h outputs the following: { } @example Request syntax with placeholder values resp = client.get_object_torrent({ bucket: "BucketName", # required key: "ObjectKey", # required request_payer: "requester", # accepts requester }) @example Response structure resp.body #=> IO resp.request_charged #=> String, one of "requester" @see http://docs.aws.amazon.com/goto/WebAPI/s3-2006-03-01/GetObjectTorrent AWS API Documentation @overload get_object_torrent(params = {}) @param [Hash] params ({})
[ "Return", "torrent", "files", "from", "a", "bucket", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-s3/lib/aws-sdk-s3/client.rb#L3273-L3276
11,023
aws/aws-sdk-ruby
gems/aws-sdk-s3/lib/aws-sdk-s3/client.rb
Aws::S3.Client.wait_until
def wait_until(waiter_name, params = {}, options = {}) w = waiter(waiter_name, options) yield(w.waiter) if block_given? # deprecated w.wait(params) end
ruby
def wait_until(waiter_name, params = {}, options = {}) w = waiter(waiter_name, options) yield(w.waiter) if block_given? # deprecated w.wait(params) end
[ "def", "wait_until", "(", "waiter_name", ",", "params", "=", "{", "}", ",", "options", "=", "{", "}", ")", "w", "=", "waiter", "(", "waiter_name", ",", "options", ")", "yield", "(", "w", ".", "waiter", ")", "if", "block_given?", "# deprecated", "w", ".", "wait", "(", "params", ")", "end" ]
Polls an API operation until a resource enters a desired state. ## Basic Usage A waiter will call an API operation until: * It is successful * It enters a terminal state * It makes the maximum number of attempts In between attempts, the waiter will sleep. # polls in a loop, sleeping between attempts client.wait_until(waiter_name, params) ## Configuration You can configure the maximum number of polling attempts, and the delay (in seconds) between each polling attempt. You can pass configuration as the final arguments hash. # poll for ~25 seconds client.wait_until(waiter_name, params, { max_attempts: 5, delay: 5, }) ## Callbacks You can be notified before each polling attempt and before each delay. If you throw `:success` or `:failure` from these callbacks, it will terminate the waiter. started_at = Time.now client.wait_until(waiter_name, params, { # disable max attempts max_attempts: nil, # poll for 1 hour, instead of a number of attempts before_wait: -> (attempts, response) do throw :failure if Time.now - started_at > 3600 end }) ## Handling Errors When a waiter is unsuccessful, it will raise an error. All of the failure errors extend from {Aws::Waiters::Errors::WaiterFailed}. begin client.wait_until(...) rescue Aws::Waiters::Errors::WaiterFailed # resource did not enter the desired state in time end ## Valid Waiters The following table lists the valid waiter names, the operations they call, and the default `:delay` and `:max_attempts` values. | waiter_name | params | :delay | :max_attempts | | ----------------- | -------------- | -------- | ------------- | | bucket_exists | {#head_bucket} | 5 | 20 | | bucket_not_exists | {#head_bucket} | 5 | 20 | | object_exists | {#head_object} | 5 | 20 | | object_not_exists | {#head_object} | 5 | 20 | @raise [Errors::FailureStateError] Raised when the waiter terminates because the waiter has entered a state that it will not transition out of, preventing success. @raise [Errors::TooManyAttemptsError] Raised when the configured maximum number of attempts have been made, and the waiter is not yet successful. @raise [Errors::UnexpectedError] Raised when an error is encounted while polling for a resource that is not expected. @raise [Errors::NoSuchWaiterError] Raised when you request to wait for an unknown state. @return [Boolean] Returns `true` if the waiter was successful. @param [Symbol] waiter_name @param [Hash] params ({}) @param [Hash] options ({}) @option options [Integer] :max_attempts @option options [Integer] :delay @option options [Proc] :before_attempt @option options [Proc] :before_wait
[ "Polls", "an", "API", "operation", "until", "a", "resource", "enters", "a", "desired", "state", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-s3/lib/aws-sdk-s3/client.rb#L7139-L7143
11,024
aws/aws-sdk-ruby
gems/aws-sdk-core/lib/aws-sdk-core/shared_config.rb
Aws.SharedConfig.fresh
def fresh(options = {}) @profile_name = nil @credentials_path = nil @config_path = nil @parsed_credentials = {} @parsed_config = nil @config_enabled = options[:config_enabled] ? true : false @profile_name = determine_profile(options) @credentials_path = options[:credentials_path] || determine_credentials_path load_credentials_file if loadable?(@credentials_path) if @config_enabled @config_path = options[:config_path] || determine_config_path load_config_file if loadable?(@config_path) end end
ruby
def fresh(options = {}) @profile_name = nil @credentials_path = nil @config_path = nil @parsed_credentials = {} @parsed_config = nil @config_enabled = options[:config_enabled] ? true : false @profile_name = determine_profile(options) @credentials_path = options[:credentials_path] || determine_credentials_path load_credentials_file if loadable?(@credentials_path) if @config_enabled @config_path = options[:config_path] || determine_config_path load_config_file if loadable?(@config_path) end end
[ "def", "fresh", "(", "options", "=", "{", "}", ")", "@profile_name", "=", "nil", "@credentials_path", "=", "nil", "@config_path", "=", "nil", "@parsed_credentials", "=", "{", "}", "@parsed_config", "=", "nil", "@config_enabled", "=", "options", "[", ":config_enabled", "]", "?", "true", ":", "false", "@profile_name", "=", "determine_profile", "(", "options", ")", "@credentials_path", "=", "options", "[", ":credentials_path", "]", "||", "determine_credentials_path", "load_credentials_file", "if", "loadable?", "(", "@credentials_path", ")", "if", "@config_enabled", "@config_path", "=", "options", "[", ":config_path", "]", "||", "determine_config_path", "load_config_file", "if", "loadable?", "(", "@config_path", ")", "end", "end" ]
Constructs a new SharedConfig provider object. This will load the shared credentials file, and optionally the shared configuration file, as ini files which support profiles. By default, the shared credential file (the default path for which is `~/.aws/credentials`) and the shared config file (the default path for which is `~/.aws/config`) are loaded. However, if you set the `ENV['AWS_SDK_CONFIG_OPT_OUT']` environment variable, only the shared credential file will be loaded. You can specify the shared credential file path with the `ENV['AWS_SHARED_CREDENTIALS_FILE']` environment variable or with the `:credentials_path` option. Similarly, you can specify the shared config file path with the `ENV['AWS_CONFIG_FILE']` environment variable or with the `:config_path` option. The default profile name is 'default'. You can specify the profile name with the `ENV['AWS_PROFILE']` environment variable or with the `:profile_name` option. @param [Hash] options @option options [String] :credentials_path Path to the shared credentials file. If not specified, will check `ENV['AWS_SHARED_CREDENTIALS_FILE']` before using the default value of "#{Dir.home}/.aws/credentials". @option options [String] :config_path Path to the shared config file. If not specified, will check `ENV['AWS_CONFIG_FILE']` before using the default value of "#{Dir.home}/.aws/config". @option options [String] :profile_name The credential/config profile name to use. If not specified, will check `ENV['AWS_PROFILE']` before using the fixed default value of 'default'. @option options [Boolean] :config_enabled If true, loads the shared config file and enables new config values outside of the old shared credential spec. @api private
[ "Constructs", "a", "new", "SharedConfig", "provider", "object", ".", "This", "will", "load", "the", "shared", "credentials", "file", "and", "optionally", "the", "shared", "configuration", "file", "as", "ini", "files", "which", "support", "profiles", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-core/lib/aws-sdk-core/shared_config.rb#L61-L76
11,025
aws/aws-sdk-ruby
gems/aws-sdk-core/lib/aws-sdk-core/shared_config.rb
Aws.SharedConfig.assume_role_credentials_from_config
def assume_role_credentials_from_config(opts = {}) p = opts.delete(:profile) || @profile_name chain_config = opts.delete(:chain_config) credentials = assume_role_from_profile(@parsed_credentials, p, opts, chain_config) if @parsed_config credentials ||= assume_role_from_profile(@parsed_config, p, opts, chain_config) end credentials end
ruby
def assume_role_credentials_from_config(opts = {}) p = opts.delete(:profile) || @profile_name chain_config = opts.delete(:chain_config) credentials = assume_role_from_profile(@parsed_credentials, p, opts, chain_config) if @parsed_config credentials ||= assume_role_from_profile(@parsed_config, p, opts, chain_config) end credentials end
[ "def", "assume_role_credentials_from_config", "(", "opts", "=", "{", "}", ")", "p", "=", "opts", ".", "delete", "(", ":profile", ")", "||", "@profile_name", "chain_config", "=", "opts", ".", "delete", "(", ":chain_config", ")", "credentials", "=", "assume_role_from_profile", "(", "@parsed_credentials", ",", "p", ",", "opts", ",", "chain_config", ")", "if", "@parsed_config", "credentials", "||=", "assume_role_from_profile", "(", "@parsed_config", ",", "p", ",", "opts", ",", "chain_config", ")", "end", "credentials", "end" ]
Attempts to assume a role from shared config or shared credentials file. Will always attempt first to assume a role from the shared credentials file, if present.
[ "Attempts", "to", "assume", "a", "role", "from", "shared", "config", "or", "shared", "credentials", "file", ".", "Will", "always", "attempt", "first", "to", "assume", "a", "role", "from", "the", "shared", "credentials", "file", "if", "present", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-core/lib/aws-sdk-core/shared_config.rb#L114-L122
11,026
aws/aws-sdk-ruby
gems/aws-sdk-core/lib/aws-sdk-core/structure.rb
Aws.Structure.to_h
def to_h(obj = self) case obj when Struct obj.members.each.with_object({}) do |member, hash| value = obj[member] hash[member] = to_hash(value) unless value.nil? end when Hash obj.each.with_object({}) do |(key, value), hash| hash[key] = to_hash(value) end when Array obj.collect { |value| to_hash(value) } else obj end end
ruby
def to_h(obj = self) case obj when Struct obj.members.each.with_object({}) do |member, hash| value = obj[member] hash[member] = to_hash(value) unless value.nil? end when Hash obj.each.with_object({}) do |(key, value), hash| hash[key] = to_hash(value) end when Array obj.collect { |value| to_hash(value) } else obj end end
[ "def", "to_h", "(", "obj", "=", "self", ")", "case", "obj", "when", "Struct", "obj", ".", "members", ".", "each", ".", "with_object", "(", "{", "}", ")", "do", "|", "member", ",", "hash", "|", "value", "=", "obj", "[", "member", "]", "hash", "[", "member", "]", "=", "to_hash", "(", "value", ")", "unless", "value", ".", "nil?", "end", "when", "Hash", "obj", ".", "each", ".", "with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "hash", "|", "hash", "[", "key", "]", "=", "to_hash", "(", "value", ")", "end", "when", "Array", "obj", ".", "collect", "{", "|", "value", "|", "to_hash", "(", "value", ")", "}", "else", "obj", "end", "end" ]
Deeply converts the Structure into a hash. Structure members that are `nil` are omitted from the resultant hash. You can call #orig_to_h to get vanilla #to_h behavior as defined in stdlib Struct. @return [Hash]
[ "Deeply", "converts", "the", "Structure", "into", "a", "hash", ".", "Structure", "members", "that", "are", "nil", "are", "omitted", "from", "the", "resultant", "hash", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-core/lib/aws-sdk-core/structure.rb#L29-L45
11,027
aws/aws-sdk-ruby
gems/aws-sdk-core/lib/aws-sdk-core/client_stubs.rb
Aws.ClientStubs.api_requests
def api_requests(options = {}) if config.stub_responses if options[:exclude_presign] @api_requests.reject {|req| req[:context][:presigned_url] } else @api_requests end else msg = 'This method is only implemented for stubbed clients, and is ' msg << 'available when you enable stubbing in the constructor with `stub_responses: true`' raise NotImplementedError.new(msg) end end
ruby
def api_requests(options = {}) if config.stub_responses if options[:exclude_presign] @api_requests.reject {|req| req[:context][:presigned_url] } else @api_requests end else msg = 'This method is only implemented for stubbed clients, and is ' msg << 'available when you enable stubbing in the constructor with `stub_responses: true`' raise NotImplementedError.new(msg) end end
[ "def", "api_requests", "(", "options", "=", "{", "}", ")", "if", "config", ".", "stub_responses", "if", "options", "[", ":exclude_presign", "]", "@api_requests", ".", "reject", "{", "|", "req", "|", "req", "[", ":context", "]", "[", ":presigned_url", "]", "}", "else", "@api_requests", "end", "else", "msg", "=", "'This method is only implemented for stubbed clients, and is '", "msg", "<<", "'available when you enable stubbing in the constructor with `stub_responses: true`'", "raise", "NotImplementedError", ".", "new", "(", "msg", ")", "end", "end" ]
Allows you to access all of the requests that the stubbed client has made @params [Boolean] exclude_presign Setting to true for filtering out not sent requests from generating presigned urls. Default to false. @return [Array] Returns an array of the api requests made, each request object contains the :operation_name, :params, and :context of the request. @raise [NotImplementedError] Raises `NotImplementedError` when the client is not stubbed
[ "Allows", "you", "to", "access", "all", "of", "the", "requests", "that", "the", "stubbed", "client", "has", "made" ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-core/lib/aws-sdk-core/client_stubs.rb#L192-L204
11,028
aws/aws-sdk-ruby
gems/aws-sdk-core/lib/aws-sdk-core/client_stubs.rb
Aws.ClientStubs.stub_data
def stub_data(operation_name, data = {}) Stubbing::StubData.new(config.api.operation(operation_name)).stub(data) end
ruby
def stub_data(operation_name, data = {}) Stubbing::StubData.new(config.api.operation(operation_name)).stub(data) end
[ "def", "stub_data", "(", "operation_name", ",", "data", "=", "{", "}", ")", "Stubbing", "::", "StubData", ".", "new", "(", "config", ".", "api", ".", "operation", "(", "operation_name", ")", ")", ".", "stub", "(", "data", ")", "end" ]
Generates and returns stubbed response data from the named operation. s3 = Aws::S3::Client.new s3.stub_data(:list_buckets) #=> #<struct Aws::S3::Types::ListBucketsOutput buckets=[], owner=#<struct Aws::S3::Types::Owner display_name="DisplayName", id="ID">> In addition to generating default stubs, you can provide data to apply to the response stub. s3.stub_data(:list_buckets, buckets:[{name:'aws-sdk'}]) #=> #<struct Aws::S3::Types::ListBucketsOutput buckets=[#<struct Aws::S3::Types::Bucket name="aws-sdk", creation_date=nil>], owner=#<struct Aws::S3::Types::Owner display_name="DisplayName", id="ID">> @param [Symbol] operation_name @param [Hash] data @return [Structure] Returns a stubbed response data structure. The actual class returned will depend on the given `operation_name`.
[ "Generates", "and", "returns", "stubbed", "response", "data", "from", "the", "named", "operation", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-core/lib/aws-sdk-core/client_stubs.rb#L224-L226
11,029
aws/aws-sdk-ruby
gems/aws-sdk-core/lib/aws-sdk-core/pageable_response.rb
Aws.PageableResponse.each
def each(&block) return enum_for(:each_page) unless block_given? response = self yield(response) until response.last_page? response = response.next_page yield(response) end end
ruby
def each(&block) return enum_for(:each_page) unless block_given? response = self yield(response) until response.last_page? response = response.next_page yield(response) end end
[ "def", "each", "(", "&", "block", ")", "return", "enum_for", "(", ":each_page", ")", "unless", "block_given?", "response", "=", "self", "yield", "(", "response", ")", "until", "response", ".", "last_page?", "response", "=", "response", ".", "next_page", "yield", "(", "response", ")", "end", "end" ]
Yields the current and each following response to the given block. @yieldparam [Response] response @return [Enumerable,nil] Returns a new Enumerable if no block is given.
[ "Yields", "the", "current", "and", "each", "following", "response", "to", "the", "given", "block", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-core/lib/aws-sdk-core/pageable_response.rb#L72-L80
11,030
aws/aws-sdk-ruby
gems/aws-sdk-glacier/lib/aws-sdk-glacier/client.rb
Aws::Glacier.Client.get_job_output
def get_job_output(params = {}, options = {}, &block) req = build_request(:get_job_output, params) req.send_request(options, &block) end
ruby
def get_job_output(params = {}, options = {}, &block) req = build_request(:get_job_output, params) req.send_request(options, &block) end
[ "def", "get_job_output", "(", "params", "=", "{", "}", ",", "options", "=", "{", "}", ",", "&", "block", ")", "req", "=", "build_request", "(", ":get_job_output", ",", "params", ")", "req", ".", "send_request", "(", "options", ",", "block", ")", "end" ]
This operation downloads the output of the job you initiated using InitiateJob. Depending on the job type you specified when you initiated the job, the output will be either the content of an archive or a vault inventory. You can download all the job output or download a portion of the output by specifying a byte range. In the case of an archive retrieval job, depending on the byte range you specify, Amazon Glacier returns the checksum for the portion of the data. You can compute the checksum on the client and verify that the values match to ensure the portion you downloaded is the correct data. A job ID will not expire for at least 24 hours after Amazon Glacier completes the job. That a byte range. For both archive and inventory retrieval jobs, you should verify the downloaded size against the size returned in the headers from the **Get Job Output** response. For archive retrieval jobs, you should also verify that the size is what you expected. If you download a portion of the output, the expected size is based on the range of bytes you specified. For example, if you specify a range of `bytes=0-1048575`, you should verify your download size is 1,048,576 bytes. If you download an entire archive, the expected size is the size of the archive when you uploaded it to Amazon Glacier The expected size is also returned in the headers from the **Get Job Output** response. In the case of an archive retrieval job, depending on the byte range you specify, Amazon Glacier returns the checksum for the portion of the data. To ensure the portion you downloaded is the correct data, compute the checksum on the client, verify that the values match, and verify that the size is what you expected. A job ID does not expire for at least 24 hours after Amazon Glacier completes the job. That is, you can download the job output within the 24 hours period after Amazon Glacier completes the job. An AWS account has full permission to perform all operations (actions). However, AWS Identity and Access Management (IAM) users don't have any permissions by default. You must grant them explicit permission to perform specific actions. For more information, see [Access Control Using AWS Identity and Access Management (IAM)][1]. For conceptual information and the underlying REST API, see [Downloading a Vault Inventory][2], [Downloading an Archive][3], and [Get Job Output ][4] [1]: http://docs.aws.amazon.com/amazonglacier/latest/dev/using-iam-with-amazon-glacier.html [2]: http://docs.aws.amazon.com/amazonglacier/latest/dev/vault-inventory.html [3]: http://docs.aws.amazon.com/amazonglacier/latest/dev/downloading-an-archive.html [4]: http://docs.aws.amazon.com/amazonglacier/latest/dev/api-job-output-get.html @option params [required, String] :account_id The `AccountId` value is the AWS account ID of the account that owns the vault. You can either specify an AWS account ID or optionally a single '`-`' (hyphen), in which case Amazon Glacier uses the AWS account ID associated with the credentials used to sign the request. If you use an account ID, do not include any hyphens ('-') in the ID. @option params [required, String] :vault_name The name of the vault. @option params [required, String] :job_id The job ID whose data is downloaded. @option params [String] :range The range of bytes to retrieve from the output. For example, if you want to download the first 1,048,576 bytes, specify the range as `bytes=0-1048575`. By default, this operation downloads the entire output. If the job output is large, then you can use a range to retrieve a portion of the output. This allows you to download the entire output in smaller chunks of bytes. For example, suppose you have 1 GB of job output you want to download and you decide to download 128 MB chunks of data at a time, which is a total of eight Get Job Output requests. You use the following process to download the job output: 1. Download a 128 MB chunk of output by specifying the appropriate byte range. Verify that all 128 MB of data was received. 2. Along with the data, the response includes a SHA256 tree hash of the payload. You compute the checksum of the payload on the client and compare it with the checksum you received in the response to ensure you received all the expected data. 3. Repeat steps 1 and 2 for all the eight 128 MB chunks of output data, each time specifying the appropriate byte range. 4. After downloading all the parts of the job output, you have a list of eight checksum values. Compute the tree hash of these values to find the checksum of the entire output. Using the DescribeJob API, obtain job information of the job that provided you the output. The response includes the checksum of the entire archive stored in Amazon Glacier. You compare this value with the checksum you computed to ensure you have downloaded the entire archive content with no errors. @return [Types::GetJobOutputOutput] Returns a {Seahorse::Client::Response response} object which responds to the following methods: * {Types::GetJobOutputOutput#body #body} => IO * {Types::GetJobOutputOutput#checksum #checksum} => String * {Types::GetJobOutputOutput#status #status} => Integer * {Types::GetJobOutputOutput#content_range #content_range} => String * {Types::GetJobOutputOutput#accept_ranges #accept_ranges} => String * {Types::GetJobOutputOutput#content_type #content_type} => String * {Types::GetJobOutputOutput#archive_description #archive_description} => String @example Example: To get the output of a previously initiated job # The example downloads the output of a previously initiated inventory retrieval job that is identified by the job ID. resp = client.get_job_output({ account_id: "-", job_id: "zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW", range: "", vault_name: "my-vaul", }) resp.to_h outputs the following: { accept_ranges: "bytes", body: "inventory-data", content_type: "application/json", status: 200, } @example Request syntax with placeholder values resp = client.get_job_output({ account_id: "string", # required vault_name: "string", # required job_id: "string", # required range: "string", }) @example Response structure resp.body #=> IO resp.checksum #=> String resp.status #=> Integer resp.content_range #=> String resp.accept_ranges #=> String resp.content_type #=> String resp.archive_description #=> String @overload get_job_output(params = {}) @param [Hash] params ({})
[ "This", "operation", "downloads", "the", "output", "of", "the", "job", "you", "initiated", "using", "InitiateJob", ".", "Depending", "on", "the", "job", "type", "you", "specified", "when", "you", "initiated", "the", "job", "the", "output", "will", "be", "either", "the", "content", "of", "an", "archive", "or", "a", "vault", "inventory", "." ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-glacier/lib/aws-sdk-glacier/client.rb#L1448-L1451
11,031
aws/aws-sdk-ruby
gems/aws-sdk-core/lib/aws-sdk-core/endpoint_cache.rb
Aws.EndpointCache.key?
def key?(key) if @entries.key?(key) && (@entries[key].nil? || @entries[key].expired?) self.delete(key) end @entries.key?(key) end
ruby
def key?(key) if @entries.key?(key) && (@entries[key].nil? || @entries[key].expired?) self.delete(key) end @entries.key?(key) end
[ "def", "key?", "(", "key", ")", "if", "@entries", ".", "key?", "(", "key", ")", "&&", "(", "@entries", "[", "key", "]", ".", "nil?", "||", "@entries", "[", "key", "]", ".", "expired?", ")", "self", ".", "delete", "(", "key", ")", "end", "@entries", ".", "key?", "(", "key", ")", "end" ]
checking whether an unexpired endpoint key exists in cache @param [String] key @return [Boolean]
[ "checking", "whether", "an", "unexpired", "endpoint", "key", "exists", "in", "cache" ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-core/lib/aws-sdk-core/endpoint_cache.rb#L62-L67
11,032
aws/aws-sdk-ruby
gems/aws-sdk-core/lib/aws-sdk-core/endpoint_cache.rb
Aws.EndpointCache.extract_key
def extract_key(ctx) parts = [] # fetching from cred provider directly gives warnings parts << ctx.config.credentials.credentials.access_key_id if _endpoint_operation_identifier(ctx) parts << ctx.operation_name ctx.operation.input.shape.members.inject(parts) do |p, (name, ref)| p << ctx.params[name] if ref["endpointdiscoveryid"] p end end parts.join('_') end
ruby
def extract_key(ctx) parts = [] # fetching from cred provider directly gives warnings parts << ctx.config.credentials.credentials.access_key_id if _endpoint_operation_identifier(ctx) parts << ctx.operation_name ctx.operation.input.shape.members.inject(parts) do |p, (name, ref)| p << ctx.params[name] if ref["endpointdiscoveryid"] p end end parts.join('_') end
[ "def", "extract_key", "(", "ctx", ")", "parts", "=", "[", "]", "# fetching from cred provider directly gives warnings", "parts", "<<", "ctx", ".", "config", ".", "credentials", ".", "credentials", ".", "access_key_id", "if", "_endpoint_operation_identifier", "(", "ctx", ")", "parts", "<<", "ctx", ".", "operation_name", "ctx", ".", "operation", ".", "input", ".", "shape", ".", "members", ".", "inject", "(", "parts", ")", "do", "|", "p", ",", "(", "name", ",", "ref", ")", "|", "p", "<<", "ctx", ".", "params", "[", "name", "]", "if", "ref", "[", "\"endpointdiscoveryid\"", "]", "p", "end", "end", "parts", ".", "join", "(", "'_'", ")", "end" ]
extract the key to be used in the cache from request context @param [RequestContext] ctx @return [String]
[ "extract", "the", "key", "to", "be", "used", "in", "the", "cache", "from", "request", "context" ]
e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d
https://github.com/aws/aws-sdk-ruby/blob/e28b8d320ddf7b6ee0161bdd9d00fb786d99b63d/gems/aws-sdk-core/lib/aws-sdk-core/endpoint_cache.rb#L105-L117
11,033
primer/octicons
lib/octicons_jekyll/lib/jekyll-octicons.rb
Jekyll.Octicons.string_to_hash
def string_to_hash(markup) options = {} if match = markup.match(Syntax) markup.scan(TagAttributes) do |key, value| options[key.to_sym] = value.gsub(/\A"|"\z/, "") end end options end
ruby
def string_to_hash(markup) options = {} if match = markup.match(Syntax) markup.scan(TagAttributes) do |key, value| options[key.to_sym] = value.gsub(/\A"|"\z/, "") end end options end
[ "def", "string_to_hash", "(", "markup", ")", "options", "=", "{", "}", "if", "match", "=", "markup", ".", "match", "(", "Syntax", ")", "markup", ".", "scan", "(", "TagAttributes", ")", "do", "|", "key", ",", "value", "|", "options", "[", "key", ".", "to_sym", "]", "=", "value", ".", "gsub", "(", "/", "\\A", "\\z", "/", ",", "\"\"", ")", "end", "end", "options", "end" ]
Create a ruby hash from a string passed by the jekyll tag
[ "Create", "a", "ruby", "hash", "from", "a", "string", "passed", "by", "the", "jekyll", "tag" ]
6fe5475945d5633818b49ce55619ec039789b1c8
https://github.com/primer/octicons/blob/6fe5475945d5633818b49ce55619ec039789b1c8/lib/octicons_jekyll/lib/jekyll-octicons.rb#L58-L68
11,034
resque/resque
lib/resque/plugin.rb
Resque.Plugin.lint
def lint(plugin) hooks = before_hooks(plugin) + around_hooks(plugin) + after_hooks(plugin) hooks.each do |hook| if hook.to_s.end_with?("perform") raise LintError, "#{plugin}.#{hook} is not namespaced" end end failure_hooks(plugin).each do |hook| if hook.to_s.end_with?("failure") raise LintError, "#{plugin}.#{hook} is not namespaced" end end end
ruby
def lint(plugin) hooks = before_hooks(plugin) + around_hooks(plugin) + after_hooks(plugin) hooks.each do |hook| if hook.to_s.end_with?("perform") raise LintError, "#{plugin}.#{hook} is not namespaced" end end failure_hooks(plugin).each do |hook| if hook.to_s.end_with?("failure") raise LintError, "#{plugin}.#{hook} is not namespaced" end end end
[ "def", "lint", "(", "plugin", ")", "hooks", "=", "before_hooks", "(", "plugin", ")", "+", "around_hooks", "(", "plugin", ")", "+", "after_hooks", "(", "plugin", ")", "hooks", ".", "each", "do", "|", "hook", "|", "if", "hook", ".", "to_s", ".", "end_with?", "(", "\"perform\"", ")", "raise", "LintError", ",", "\"#{plugin}.#{hook} is not namespaced\"", "end", "end", "failure_hooks", "(", "plugin", ")", ".", "each", "do", "|", "hook", "|", "if", "hook", ".", "to_s", ".", "end_with?", "(", "\"failure\"", ")", "raise", "LintError", ",", "\"#{plugin}.#{hook} is not namespaced\"", "end", "end", "end" ]
Ensure that your plugin conforms to good hook naming conventions. Resque::Plugin.lint(MyResquePlugin)
[ "Ensure", "that", "your", "plugin", "conforms", "to", "good", "hook", "naming", "conventions", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/plugin.rb#L10-L24
11,035
resque/resque
lib/resque/worker.rb
Resque.Worker.process
def process(job = nil, &block) return unless job ||= reserve job.worker = self working_on job perform(job, &block) ensure done_working end
ruby
def process(job = nil, &block) return unless job ||= reserve job.worker = self working_on job perform(job, &block) ensure done_working end
[ "def", "process", "(", "job", "=", "nil", ",", "&", "block", ")", "return", "unless", "job", "||=", "reserve", "job", ".", "worker", "=", "self", "working_on", "job", "perform", "(", "job", ",", "block", ")", "ensure", "done_working", "end" ]
DEPRECATED. Processes a single job. If none is given, it will try to produce one. Usually run in the child.
[ "DEPRECATED", ".", "Processes", "a", "single", "job", ".", "If", "none", "is", "given", "it", "will", "try", "to", "produce", "one", ".", "Usually", "run", "in", "the", "child", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L275-L283
11,036
resque/resque
lib/resque/worker.rb
Resque.Worker.report_failed_job
def report_failed_job(job,exception) log_with_severity :error, "#{job.inspect} failed: #{exception.inspect}" begin job.fail(exception) rescue Object => exception log_with_severity :error, "Received exception when reporting failure: #{exception.inspect}" end begin failed! rescue Object => exception log_with_severity :error, "Received exception when increasing failed jobs counter (redis issue) : #{exception.inspect}" end end
ruby
def report_failed_job(job,exception) log_with_severity :error, "#{job.inspect} failed: #{exception.inspect}" begin job.fail(exception) rescue Object => exception log_with_severity :error, "Received exception when reporting failure: #{exception.inspect}" end begin failed! rescue Object => exception log_with_severity :error, "Received exception when increasing failed jobs counter (redis issue) : #{exception.inspect}" end end
[ "def", "report_failed_job", "(", "job", ",", "exception", ")", "log_with_severity", ":error", ",", "\"#{job.inspect} failed: #{exception.inspect}\"", "begin", "job", ".", "fail", "(", "exception", ")", "rescue", "Object", "=>", "exception", "log_with_severity", ":error", ",", "\"Received exception when reporting failure: #{exception.inspect}\"", "end", "begin", "failed!", "rescue", "Object", "=>", "exception", "log_with_severity", ":error", ",", "\"Received exception when increasing failed jobs counter (redis issue) : #{exception.inspect}\"", "end", "end" ]
Reports the exception and marks the job as failed
[ "Reports", "the", "exception", "and", "marks", "the", "job", "as", "failed" ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L286-L298
11,037
resque/resque
lib/resque/worker.rb
Resque.Worker.perform
def perform(job) begin if fork_per_job? reconnect run_hook :after_fork, job end job.perform rescue Object => e report_failed_job(job,e) else log_with_severity :info, "done: #{job.inspect}" ensure yield job if block_given? end end
ruby
def perform(job) begin if fork_per_job? reconnect run_hook :after_fork, job end job.perform rescue Object => e report_failed_job(job,e) else log_with_severity :info, "done: #{job.inspect}" ensure yield job if block_given? end end
[ "def", "perform", "(", "job", ")", "begin", "if", "fork_per_job?", "reconnect", "run_hook", ":after_fork", ",", "job", "end", "job", ".", "perform", "rescue", "Object", "=>", "e", "report_failed_job", "(", "job", ",", "e", ")", "else", "log_with_severity", ":info", ",", "\"done: #{job.inspect}\"", "ensure", "yield", "job", "if", "block_given?", "end", "end" ]
Processes a given job in the child.
[ "Processes", "a", "given", "job", "in", "the", "child", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L302-L316
11,038
resque/resque
lib/resque/worker.rb
Resque.Worker.reserve
def reserve queues.each do |queue| log_with_severity :debug, "Checking #{queue}" if job = Resque.reserve(queue) log_with_severity :debug, "Found job on #{queue}" return job end end nil rescue Exception => e log_with_severity :error, "Error reserving job: #{e.inspect}" log_with_severity :error, e.backtrace.join("\n") raise e end
ruby
def reserve queues.each do |queue| log_with_severity :debug, "Checking #{queue}" if job = Resque.reserve(queue) log_with_severity :debug, "Found job on #{queue}" return job end end nil rescue Exception => e log_with_severity :error, "Error reserving job: #{e.inspect}" log_with_severity :error, e.backtrace.join("\n") raise e end
[ "def", "reserve", "queues", ".", "each", "do", "|", "queue", "|", "log_with_severity", ":debug", ",", "\"Checking #{queue}\"", "if", "job", "=", "Resque", ".", "reserve", "(", "queue", ")", "log_with_severity", ":debug", ",", "\"Found job on #{queue}\"", "return", "job", "end", "end", "nil", "rescue", "Exception", "=>", "e", "log_with_severity", ":error", ",", "\"Error reserving job: #{e.inspect}\"", "log_with_severity", ":error", ",", "e", ".", "backtrace", ".", "join", "(", "\"\\n\"", ")", "raise", "e", "end" ]
Attempts to grab a job off one of the provided queues. Returns nil if no job can be found.
[ "Attempts", "to", "grab", "a", "job", "off", "one", "of", "the", "provided", "queues", ".", "Returns", "nil", "if", "no", "job", "can", "be", "found", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L320-L334
11,039
resque/resque
lib/resque/worker.rb
Resque.Worker.reconnect
def reconnect tries = 0 begin data_store.reconnect rescue Redis::BaseConnectionError if (tries += 1) <= 3 log_with_severity :error, "Error reconnecting to Redis; retrying" sleep(tries) retry else log_with_severity :error, "Error reconnecting to Redis; quitting" raise end end end
ruby
def reconnect tries = 0 begin data_store.reconnect rescue Redis::BaseConnectionError if (tries += 1) <= 3 log_with_severity :error, "Error reconnecting to Redis; retrying" sleep(tries) retry else log_with_severity :error, "Error reconnecting to Redis; quitting" raise end end end
[ "def", "reconnect", "tries", "=", "0", "begin", "data_store", ".", "reconnect", "rescue", "Redis", "::", "BaseConnectionError", "if", "(", "tries", "+=", "1", ")", "<=", "3", "log_with_severity", ":error", ",", "\"Error reconnecting to Redis; retrying\"", "sleep", "(", "tries", ")", "retry", "else", "log_with_severity", ":error", ",", "\"Error reconnecting to Redis; quitting\"", "raise", "end", "end", "end" ]
Reconnect to Redis to avoid sharing a connection with the parent, retry up to 3 times with increasing delay before giving up.
[ "Reconnect", "to", "Redis", "to", "avoid", "sharing", "a", "connection", "with", "the", "parent", "retry", "up", "to", "3", "times", "with", "increasing", "delay", "before", "giving", "up", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L338-L352
11,040
resque/resque
lib/resque/worker.rb
Resque.Worker.shutdown!
def shutdown! shutdown if term_child if fork_per_job? new_kill_child else # Raise TermException in the same process trap('TERM') do # ignore subsequent terms end raise TermException.new("SIGTERM") end else kill_child end end
ruby
def shutdown! shutdown if term_child if fork_per_job? new_kill_child else # Raise TermException in the same process trap('TERM') do # ignore subsequent terms end raise TermException.new("SIGTERM") end else kill_child end end
[ "def", "shutdown!", "shutdown", "if", "term_child", "if", "fork_per_job?", "new_kill_child", "else", "# Raise TermException in the same process", "trap", "(", "'TERM'", ")", "do", "# ignore subsequent terms", "end", "raise", "TermException", ".", "new", "(", "\"SIGTERM\"", ")", "end", "else", "kill_child", "end", "end" ]
Kill the child and shutdown immediately. If not forking, abort this process.
[ "Kill", "the", "child", "and", "shutdown", "immediately", ".", "If", "not", "forking", "abort", "this", "process", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L434-L449
11,041
resque/resque
lib/resque/worker.rb
Resque.Worker.run_hook
def run_hook(name, *args) hooks = Resque.send(name) return if hooks.empty? return if name == :before_first_fork && @before_first_fork_hook_ran msg = "Running #{name} hooks" msg << " with #{args.inspect}" if args.any? log_with_severity :info, msg hooks.each do |hook| args.any? ? hook.call(*args) : hook.call @before_first_fork_hook_ran = true if name == :before_first_fork end end
ruby
def run_hook(name, *args) hooks = Resque.send(name) return if hooks.empty? return if name == :before_first_fork && @before_first_fork_hook_ran msg = "Running #{name} hooks" msg << " with #{args.inspect}" if args.any? log_with_severity :info, msg hooks.each do |hook| args.any? ? hook.call(*args) : hook.call @before_first_fork_hook_ran = true if name == :before_first_fork end end
[ "def", "run_hook", "(", "name", ",", "*", "args", ")", "hooks", "=", "Resque", ".", "send", "(", "name", ")", "return", "if", "hooks", ".", "empty?", "return", "if", "name", "==", ":before_first_fork", "&&", "@before_first_fork_hook_ran", "msg", "=", "\"Running #{name} hooks\"", "msg", "<<", "\" with #{args.inspect}\"", "if", "args", ".", "any?", "log_with_severity", ":info", ",", "msg", "hooks", ".", "each", "do", "|", "hook", "|", "args", ".", "any?", "?", "hook", ".", "call", "(", "args", ")", ":", "hook", ".", "call", "@before_first_fork_hook_ran", "=", "true", "if", "name", "==", ":before_first_fork", "end", "end" ]
Runs a named hook, passing along any arguments.
[ "Runs", "a", "named", "hook", "passing", "along", "any", "arguments", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L645-L657
11,042
resque/resque
lib/resque/worker.rb
Resque.Worker.unregister_worker
def unregister_worker(exception = nil) # If we're still processing a job, make sure it gets logged as a # failure. if (hash = processing) && !hash.empty? job = Job.new(hash['queue'], hash['payload']) # Ensure the proper worker is attached to this job, even if # it's not the precise instance that died. job.worker = self begin job.fail(exception || DirtyExit.new("Job still being processed")) rescue RuntimeError => e log_with_severity :error, e.message end end kill_background_threads data_store.unregister_worker(self) do Stat.clear("processed:#{self}") Stat.clear("failed:#{self}") end rescue Exception => exception_while_unregistering message = exception_while_unregistering.message if exception message += "\nOriginal Exception (#{exception.class}): #{exception.message}" message += "\n #{exception.backtrace.join(" \n")}" if exception.backtrace end fail(exception_while_unregistering.class, message, exception_while_unregistering.backtrace) end
ruby
def unregister_worker(exception = nil) # If we're still processing a job, make sure it gets logged as a # failure. if (hash = processing) && !hash.empty? job = Job.new(hash['queue'], hash['payload']) # Ensure the proper worker is attached to this job, even if # it's not the precise instance that died. job.worker = self begin job.fail(exception || DirtyExit.new("Job still being processed")) rescue RuntimeError => e log_with_severity :error, e.message end end kill_background_threads data_store.unregister_worker(self) do Stat.clear("processed:#{self}") Stat.clear("failed:#{self}") end rescue Exception => exception_while_unregistering message = exception_while_unregistering.message if exception message += "\nOriginal Exception (#{exception.class}): #{exception.message}" message += "\n #{exception.backtrace.join(" \n")}" if exception.backtrace end fail(exception_while_unregistering.class, message, exception_while_unregistering.backtrace) end
[ "def", "unregister_worker", "(", "exception", "=", "nil", ")", "# If we're still processing a job, make sure it gets logged as a", "# failure.", "if", "(", "hash", "=", "processing", ")", "&&", "!", "hash", ".", "empty?", "job", "=", "Job", ".", "new", "(", "hash", "[", "'queue'", "]", ",", "hash", "[", "'payload'", "]", ")", "# Ensure the proper worker is attached to this job, even if", "# it's not the precise instance that died.", "job", ".", "worker", "=", "self", "begin", "job", ".", "fail", "(", "exception", "||", "DirtyExit", ".", "new", "(", "\"Job still being processed\"", ")", ")", "rescue", "RuntimeError", "=>", "e", "log_with_severity", ":error", ",", "e", ".", "message", "end", "end", "kill_background_threads", "data_store", ".", "unregister_worker", "(", "self", ")", "do", "Stat", ".", "clear", "(", "\"processed:#{self}\"", ")", "Stat", ".", "clear", "(", "\"failed:#{self}\"", ")", "end", "rescue", "Exception", "=>", "exception_while_unregistering", "message", "=", "exception_while_unregistering", ".", "message", "if", "exception", "message", "+=", "\"\\nOriginal Exception (#{exception.class}): #{exception.message}\"", "message", "+=", "\"\\n #{exception.backtrace.join(\" \\n\")}\"", "if", "exception", ".", "backtrace", "end", "fail", "(", "exception_while_unregistering", ".", "class", ",", "message", ",", "exception_while_unregistering", ".", "backtrace", ")", "end" ]
Unregisters ourself as a worker. Useful when shutting down.
[ "Unregisters", "ourself", "as", "a", "worker", ".", "Useful", "when", "shutting", "down", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L667-L697
11,043
resque/resque
lib/resque/worker.rb
Resque.Worker.working_on
def working_on(job) data = encode \ :queue => job.queue, :run_at => Time.now.utc.iso8601, :payload => job.payload data_store.set_worker_payload(self,data) end
ruby
def working_on(job) data = encode \ :queue => job.queue, :run_at => Time.now.utc.iso8601, :payload => job.payload data_store.set_worker_payload(self,data) end
[ "def", "working_on", "(", "job", ")", "data", "=", "encode", ":queue", "=>", "job", ".", "queue", ",", ":run_at", "=>", "Time", ".", "now", ".", "utc", ".", "iso8601", ",", ":payload", "=>", "job", ".", "payload", "data_store", ".", "set_worker_payload", "(", "self", ",", "data", ")", "end" ]
Given a job, tells Redis we're working on it. Useful for seeing what workers are doing and when.
[ "Given", "a", "job", "tells", "Redis", "we", "re", "working", "on", "it", ".", "Useful", "for", "seeing", "what", "workers", "are", "doing", "and", "when", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L701-L707
11,044
resque/resque
lib/resque/worker.rb
Resque.Worker.windows_worker_pids
def windows_worker_pids tasklist_output = `tasklist /FI "IMAGENAME eq ruby.exe" /FO list`.encode("UTF-8", Encoding.locale_charmap) tasklist_output.split($/).select { |line| line =~ /^PID:/ }.collect { |line| line.gsub(/PID:\s+/, '') } end
ruby
def windows_worker_pids tasklist_output = `tasklist /FI "IMAGENAME eq ruby.exe" /FO list`.encode("UTF-8", Encoding.locale_charmap) tasklist_output.split($/).select { |line| line =~ /^PID:/ }.collect { |line| line.gsub(/PID:\s+/, '') } end
[ "def", "windows_worker_pids", "tasklist_output", "=", "`", "`", ".", "encode", "(", "\"UTF-8\"", ",", "Encoding", ".", "locale_charmap", ")", "tasklist_output", ".", "split", "(", "$/", ")", ".", "select", "{", "|", "line", "|", "line", "=~", "/", "/", "}", ".", "collect", "{", "|", "line", "|", "line", ".", "gsub", "(", "/", "\\s", "/", ",", "''", ")", "}", "end" ]
Returns an Array of string pids of all the other workers on this machine. Useful when pruning dead workers on startup.
[ "Returns", "an", "Array", "of", "string", "pids", "of", "all", "the", "other", "workers", "on", "this", "machine", ".", "Useful", "when", "pruning", "dead", "workers", "on", "startup", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/worker.rb#L818-L821
11,045
resque/resque
lib/resque/job.rb
Resque.Job.fail
def fail(exception) begin run_failure_hooks(exception) rescue Exception => e raise e ensure Failure.create \ :payload => payload, :exception => exception, :worker => worker, :queue => queue end end
ruby
def fail(exception) begin run_failure_hooks(exception) rescue Exception => e raise e ensure Failure.create \ :payload => payload, :exception => exception, :worker => worker, :queue => queue end end
[ "def", "fail", "(", "exception", ")", "begin", "run_failure_hooks", "(", "exception", ")", "rescue", "Exception", "=>", "e", "raise", "e", "ensure", "Failure", ".", "create", ":payload", "=>", "payload", ",", ":exception", "=>", "exception", ",", ":worker", "=>", "worker", ",", ":queue", "=>", "queue", "end", "end" ]
Given an exception object, hands off the needed parameters to the Failure module.
[ "Given", "an", "exception", "object", "hands", "off", "the", "needed", "parameters", "to", "the", "Failure", "module", "." ]
adb633a0f6b98b1eb5a5a85bb36ebac9309978fd
https://github.com/resque/resque/blob/adb633a0f6b98b1eb5a5a85bb36ebac9309978fd/lib/resque/job.rb#L232-L244
11,046
ruby-grape/grape
lib/grape/endpoint.rb
Grape.Endpoint.inherit_settings
def inherit_settings(namespace_stackable) inheritable_setting.route[:saved_validations] += namespace_stackable[:validations] parent_declared_params = namespace_stackable[:declared_params] if parent_declared_params inheritable_setting.route[:declared_params] ||= [] inheritable_setting.route[:declared_params].concat(parent_declared_params.flatten) end endpoints && endpoints.each { |e| e.inherit_settings(namespace_stackable) } end
ruby
def inherit_settings(namespace_stackable) inheritable_setting.route[:saved_validations] += namespace_stackable[:validations] parent_declared_params = namespace_stackable[:declared_params] if parent_declared_params inheritable_setting.route[:declared_params] ||= [] inheritable_setting.route[:declared_params].concat(parent_declared_params.flatten) end endpoints && endpoints.each { |e| e.inherit_settings(namespace_stackable) } end
[ "def", "inherit_settings", "(", "namespace_stackable", ")", "inheritable_setting", ".", "route", "[", ":saved_validations", "]", "+=", "namespace_stackable", "[", ":validations", "]", "parent_declared_params", "=", "namespace_stackable", "[", ":declared_params", "]", "if", "parent_declared_params", "inheritable_setting", ".", "route", "[", ":declared_params", "]", "||=", "[", "]", "inheritable_setting", ".", "route", "[", ":declared_params", "]", ".", "concat", "(", "parent_declared_params", ".", "flatten", ")", "end", "endpoints", "&&", "endpoints", ".", "each", "{", "|", "e", "|", "e", ".", "inherit_settings", "(", "namespace_stackable", ")", "}", "end" ]
Create a new endpoint. @param new_settings [InheritableSetting] settings to determine the params, validations, and other properties from. @param options [Hash] attributes of this endpoint @option options path [String or Array] the path to this endpoint, within the current scope. @option options method [String or Array] which HTTP method(s) can be used to reach this endpoint. @option options route_options [Hash] @note This happens at the time of API definition, so in this context the endpoint does not know if it will be mounted under a different endpoint. @yield a block defining what your API should do when this endpoint is hit Update our settings from a given set of stackable parameters. Used when the endpoint's API is mounted under another one.
[ "Create", "a", "new", "endpoint", "." ]
e26ae618b86920b19b1a98945ba7d6e953a9b989
https://github.com/ruby-grape/grape/blob/e26ae618b86920b19b1a98945ba7d6e953a9b989/lib/grape/endpoint.rb#L112-L122
11,047
ankane/blazer
app/helpers/blazer/base_helper.rb
Blazer.BaseHelper.blazer_json_escape
def blazer_json_escape(s) if Rails::VERSION::STRING < "4.1" result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE) s.html_safe? ? result.html_safe : result else json_escape(s) end end
ruby
def blazer_json_escape(s) if Rails::VERSION::STRING < "4.1" result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE) s.html_safe? ? result.html_safe : result else json_escape(s) end end
[ "def", "blazer_json_escape", "(", "s", ")", "if", "Rails", "::", "VERSION", "::", "STRING", "<", "\"4.1\"", "result", "=", "s", ".", "to_s", ".", "gsub", "(", "JSON_ESCAPE_REGEXP", ",", "JSON_ESCAPE", ")", "s", ".", "html_safe?", "?", "result", ".", "html_safe", ":", "result", "else", "json_escape", "(", "s", ")", "end", "end" ]
Prior to version 4.1 of rails double quotes were inadventently removed in json_escape. This adds the correct json_escape functionality to rails versions < 4.1
[ "Prior", "to", "version", "4", ".", "1", "of", "rails", "double", "quotes", "were", "inadventently", "removed", "in", "json_escape", ".", "This", "adds", "the", "correct", "json_escape", "functionality", "to", "rails", "versions", "<", "4", ".", "1" ]
c6c56314d47194b4b24aded4246835d036705bb3
https://github.com/ankane/blazer/blob/c6c56314d47194b4b24aded4246835d036705bb3/app/helpers/blazer/base_helper.rb#L44-L51
11,048
activeadmin/activeadmin
lib/active_admin/namespace.rb
ActiveAdmin.Namespace.register
def register(resource_class, options = {}, &block) config = find_or_build_resource(resource_class, options) # Register the resource register_resource_controller(config) parse_registration_block(config, &block) if block_given? reset_menu! # Dispatch a registration event ActiveSupport::Notifications.publish ActiveAdmin::Resource::RegisterEvent, config # Return the config config end
ruby
def register(resource_class, options = {}, &block) config = find_or_build_resource(resource_class, options) # Register the resource register_resource_controller(config) parse_registration_block(config, &block) if block_given? reset_menu! # Dispatch a registration event ActiveSupport::Notifications.publish ActiveAdmin::Resource::RegisterEvent, config # Return the config config end
[ "def", "register", "(", "resource_class", ",", "options", "=", "{", "}", ",", "&", "block", ")", "config", "=", "find_or_build_resource", "(", "resource_class", ",", "options", ")", "# Register the resource", "register_resource_controller", "(", "config", ")", "parse_registration_block", "(", "config", ",", "block", ")", "if", "block_given?", "reset_menu!", "# Dispatch a registration event", "ActiveSupport", "::", "Notifications", ".", "publish", "ActiveAdmin", "::", "Resource", "::", "RegisterEvent", ",", "config", "# Return the config", "config", "end" ]
Register a resource into this namespace. The preffered method to access this is to use the global registration ActiveAdmin.register which delegates to the proper namespace instance.
[ "Register", "a", "resource", "into", "this", "namespace", ".", "The", "preffered", "method", "to", "access", "this", "is", "to", "use", "the", "global", "registration", "ActiveAdmin", ".", "register", "which", "delegates", "to", "the", "proper", "namespace", "instance", "." ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/namespace.rb#L65-L78
11,049
activeadmin/activeadmin
lib/active_admin/namespace.rb
ActiveAdmin.Namespace.build_menu
def build_menu(name = DEFAULT_MENU) @menus.before_build do |menus| menus.menu name do |menu| yield menu end end end
ruby
def build_menu(name = DEFAULT_MENU) @menus.before_build do |menus| menus.menu name do |menu| yield menu end end end
[ "def", "build_menu", "(", "name", "=", "DEFAULT_MENU", ")", "@menus", ".", "before_build", "do", "|", "menus", "|", "menus", ".", "menu", "name", "do", "|", "menu", "|", "yield", "menu", "end", "end", "end" ]
Add a callback to be ran when we build the menu @param [Symbol] name The name of the menu. Default: :default @yield [ActiveAdmin::Menu] The block to be ran when the menu is built @return [void]
[ "Add", "a", "callback", "to", "be", "ran", "when", "we", "build", "the", "menu" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/namespace.rb#L135-L141
11,050
activeadmin/activeadmin
lib/active_admin/namespace.rb
ActiveAdmin.Namespace.add_logout_button_to_menu
def add_logout_button_to_menu(menu, priority = 20, html_options = {}) if logout_link_path html_options = html_options.reverse_merge(method: logout_link_method || :get) menu.add id: 'logout', priority: priority, html_options: html_options, label: -> { I18n.t 'active_admin.logout' }, url: -> { render_or_call_method_or_proc_on self, active_admin_namespace.logout_link_path }, if: :current_active_admin_user? end end
ruby
def add_logout_button_to_menu(menu, priority = 20, html_options = {}) if logout_link_path html_options = html_options.reverse_merge(method: logout_link_method || :get) menu.add id: 'logout', priority: priority, html_options: html_options, label: -> { I18n.t 'active_admin.logout' }, url: -> { render_or_call_method_or_proc_on self, active_admin_namespace.logout_link_path }, if: :current_active_admin_user? end end
[ "def", "add_logout_button_to_menu", "(", "menu", ",", "priority", "=", "20", ",", "html_options", "=", "{", "}", ")", "if", "logout_link_path", "html_options", "=", "html_options", ".", "reverse_merge", "(", "method", ":", "logout_link_method", "||", ":get", ")", "menu", ".", "add", "id", ":", "'logout'", ",", "priority", ":", "priority", ",", "html_options", ":", "html_options", ",", "label", ":", "->", "{", "I18n", ".", "t", "'active_admin.logout'", "}", ",", "url", ":", "->", "{", "render_or_call_method_or_proc_on", "self", ",", "active_admin_namespace", ".", "logout_link_path", "}", ",", "if", ":", ":current_active_admin_user?", "end", "end" ]
The default logout menu item @param [ActiveAdmin::MenuItem] menu The menu to add the logout link to @param [Fixnum] priority The numeric priority for the order in which it appears @param [Hash] html_options An options hash to pass along to link_to
[ "The", "default", "logout", "menu", "item" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/namespace.rb#L149-L157
11,051
activeadmin/activeadmin
lib/active_admin/namespace.rb
ActiveAdmin.Namespace.add_current_user_to_menu
def add_current_user_to_menu(menu, priority = 10, html_options = {}) if current_user_method menu.add id: 'current_user', priority: priority, html_options: html_options, label: -> { display_name current_active_admin_user }, url: -> { auto_url_for(current_active_admin_user) }, if: :current_active_admin_user? end end
ruby
def add_current_user_to_menu(menu, priority = 10, html_options = {}) if current_user_method menu.add id: 'current_user', priority: priority, html_options: html_options, label: -> { display_name current_active_admin_user }, url: -> { auto_url_for(current_active_admin_user) }, if: :current_active_admin_user? end end
[ "def", "add_current_user_to_menu", "(", "menu", ",", "priority", "=", "10", ",", "html_options", "=", "{", "}", ")", "if", "current_user_method", "menu", ".", "add", "id", ":", "'current_user'", ",", "priority", ":", "priority", ",", "html_options", ":", "html_options", ",", "label", ":", "->", "{", "display_name", "current_active_admin_user", "}", ",", "url", ":", "->", "{", "auto_url_for", "(", "current_active_admin_user", ")", "}", ",", "if", ":", ":current_active_admin_user?", "end", "end" ]
The default user session menu item @param [ActiveAdmin::MenuItem] menu The menu to add the logout link to @param [Fixnum] priority The numeric priority for the order in which it appears @param [Hash] html_options An options hash to pass along to link_to
[ "The", "default", "user", "session", "menu", "item" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/namespace.rb#L165-L172
11,052
activeadmin/activeadmin
lib/active_admin/page_dsl.rb
ActiveAdmin.PageDSL.content
def content(options = {}, &block) config.set_page_presenter :index, ActiveAdmin::PagePresenter.new(options, &block) end
ruby
def content(options = {}, &block) config.set_page_presenter :index, ActiveAdmin::PagePresenter.new(options, &block) end
[ "def", "content", "(", "options", "=", "{", "}", ",", "&", "block", ")", "config", ".", "set_page_presenter", ":index", ",", "ActiveAdmin", "::", "PagePresenter", ".", "new", "(", "options", ",", "block", ")", "end" ]
Page content. The block should define the view using Arbre. Example: ActiveAdmin.register "My Page" do content do para "Sweet!" end end
[ "Page", "content", "." ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/page_dsl.rb#L17-L19
11,053
activeadmin/activeadmin
lib/active_admin/resource_collection.rb
ActiveAdmin.ResourceCollection.find_resource
def find_resource(obj) resources.detect do |r| r.resource_name.to_s == obj.to_s end || resources.detect do |r| r.resource_class.to_s == obj.to_s end || if obj.respond_to? :base_class resources.detect { |r| r.resource_class.to_s == obj.base_class.to_s } end end
ruby
def find_resource(obj) resources.detect do |r| r.resource_name.to_s == obj.to_s end || resources.detect do |r| r.resource_class.to_s == obj.to_s end || if obj.respond_to? :base_class resources.detect { |r| r.resource_class.to_s == obj.base_class.to_s } end end
[ "def", "find_resource", "(", "obj", ")", "resources", ".", "detect", "do", "|", "r", "|", "r", ".", "resource_name", ".", "to_s", "==", "obj", ".", "to_s", "end", "||", "resources", ".", "detect", "do", "|", "r", "|", "r", ".", "resource_class", ".", "to_s", "==", "obj", ".", "to_s", "end", "||", "if", "obj", ".", "respond_to?", ":base_class", "resources", ".", "detect", "{", "|", "r", "|", "r", ".", "resource_class", ".", "to_s", "==", "obj", ".", "base_class", ".", "to_s", "}", "end", "end" ]
Finds a resource based on the resource name, resource class, or base class.
[ "Finds", "a", "resource", "based", "on", "the", "resource", "name", "resource", "class", "or", "base", "class", "." ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/resource_collection.rb#L34-L43
11,054
activeadmin/activeadmin
lib/active_admin/application.rb
ActiveAdmin.Application.register
def register(resource, options = {}, &block) ns = options.fetch(:namespace) { default_namespace } namespace(ns).register resource, options, &block end
ruby
def register(resource, options = {}, &block) ns = options.fetch(:namespace) { default_namespace } namespace(ns).register resource, options, &block end
[ "def", "register", "(", "resource", ",", "options", "=", "{", "}", ",", "&", "block", ")", "ns", "=", "options", ".", "fetch", "(", ":namespace", ")", "{", "default_namespace", "}", "namespace", "(", "ns", ")", ".", "register", "resource", ",", "options", ",", "block", "end" ]
Registers a brand new configuration for the given resource.
[ "Registers", "a", "brand", "new", "configuration", "for", "the", "given", "resource", "." ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/application.rb#L63-L66
11,055
activeadmin/activeadmin
lib/active_admin/application.rb
ActiveAdmin.Application.namespace
def namespace(name) name ||= :root namespace = namespaces[name] ||= begin namespace = Namespace.new(self, name) ActiveSupport::Notifications.publish ActiveAdmin::Namespace::RegisterEvent, namespace namespace end yield(namespace) if block_given? namespace end
ruby
def namespace(name) name ||= :root namespace = namespaces[name] ||= begin namespace = Namespace.new(self, name) ActiveSupport::Notifications.publish ActiveAdmin::Namespace::RegisterEvent, namespace namespace end yield(namespace) if block_given? namespace end
[ "def", "namespace", "(", "name", ")", "name", "||=", ":root", "namespace", "=", "namespaces", "[", "name", "]", "||=", "begin", "namespace", "=", "Namespace", ".", "new", "(", "self", ",", "name", ")", "ActiveSupport", "::", "Notifications", ".", "publish", "ActiveAdmin", "::", "Namespace", "::", "RegisterEvent", ",", "namespace", "namespace", "end", "yield", "(", "namespace", ")", "if", "block_given?", "namespace", "end" ]
Creates a namespace for the given name Yields the namespace if a block is given @return [Namespace] the new or existing namespace
[ "Creates", "a", "namespace", "for", "the", "given", "name" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/application.rb#L73-L85
11,056
activeadmin/activeadmin
lib/active_admin/application.rb
ActiveAdmin.Application.register_page
def register_page(name, options = {}, &block) ns = options.fetch(:namespace) { default_namespace } namespace(ns).register_page name, options, &block end
ruby
def register_page(name, options = {}, &block) ns = options.fetch(:namespace) { default_namespace } namespace(ns).register_page name, options, &block end
[ "def", "register_page", "(", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "ns", "=", "options", ".", "fetch", "(", ":namespace", ")", "{", "default_namespace", "}", "namespace", "(", "ns", ")", ".", "register_page", "name", ",", "options", ",", "block", "end" ]
Register a page @param name [String] The page name @option [Hash] Accepts option :namespace. @&block The registration block.
[ "Register", "a", "page" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/application.rb#L93-L96
11,057
activeadmin/activeadmin
lib/active_admin/application.rb
ActiveAdmin.Application.load!
def load! unless loaded? ActiveSupport::Notifications.publish BeforeLoadEvent, self # before_load hook files.each { |file| load file } # load files namespace(default_namespace) # init AA resources ActiveSupport::Notifications.publish AfterLoadEvent, self # after_load hook @@loaded = true end end
ruby
def load! unless loaded? ActiveSupport::Notifications.publish BeforeLoadEvent, self # before_load hook files.each { |file| load file } # load files namespace(default_namespace) # init AA resources ActiveSupport::Notifications.publish AfterLoadEvent, self # after_load hook @@loaded = true end end
[ "def", "load!", "unless", "loaded?", "ActiveSupport", "::", "Notifications", ".", "publish", "BeforeLoadEvent", ",", "self", "# before_load hook", "files", ".", "each", "{", "|", "file", "|", "load", "file", "}", "# load files", "namespace", "(", "default_namespace", ")", "# init AA resources", "ActiveSupport", "::", "Notifications", ".", "publish", "AfterLoadEvent", ",", "self", "# after_load hook", "@@loaded", "=", "true", "end", "end" ]
Loads all ruby files that are within the load_paths setting. To reload everything simply call `ActiveAdmin.unload!`
[ "Loads", "all", "ruby", "files", "that", "are", "within", "the", "load_paths", "setting", ".", "To", "reload", "everything", "simply", "call", "ActiveAdmin", ".", "unload!" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/application.rb#L112-L120
11,058
activeadmin/activeadmin
lib/active_admin/application.rb
ActiveAdmin.Application.routes
def routes(rails_router) load! Router.new(router: rails_router, namespaces: namespaces).apply end
ruby
def routes(rails_router) load! Router.new(router: rails_router, namespaces: namespaces).apply end
[ "def", "routes", "(", "rails_router", ")", "load!", "Router", ".", "new", "(", "router", ":", "rails_router", ",", "namespaces", ":", "namespaces", ")", ".", "apply", "end" ]
Creates all the necessary routes for the ActiveAdmin configurations Use this within the routes.rb file: Application.routes.draw do |map| ActiveAdmin.routes(self) end @param rails_router [ActionDispatch::Routing::Mapper]
[ "Creates", "all", "the", "necessary", "routes", "for", "the", "ActiveAdmin", "configurations" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/application.rb#L140-L143
11,059
activeadmin/activeadmin
lib/active_admin/application.rb
ActiveAdmin.Application.attach_reloader
def attach_reloader Rails.application.config.after_initialize do |app| ActiveSupport::Reloader.after_class_unload do ActiveAdmin.application.unload! end admin_dirs = {} load_paths.each do |path| admin_dirs[path] = [:rb] end routes_reloader = app.config.file_watcher.new([], admin_dirs) do app.reload_routes! end app.reloaders << routes_reloader ActiveSupport::Reloader.to_prepare do # Rails might have reloaded the routes for other reasons (e.g. # routes.rb has changed), in which case Active Admin would have been # loaded via the `ActiveAdmin.routes` call in `routes.rb`. # # Otherwise, we should check if any of the admin files are changed # and force the routes to reload if necessary. This would again causes # Active Admin to load via `ActiveAdmin.routes`. # # Finally, if Active Admin is still not loaded at this point, then we # would need to load it manually. unless ActiveAdmin.application.loaded? routes_reloader.execute_if_updated ActiveAdmin.application.load! end end end end
ruby
def attach_reloader Rails.application.config.after_initialize do |app| ActiveSupport::Reloader.after_class_unload do ActiveAdmin.application.unload! end admin_dirs = {} load_paths.each do |path| admin_dirs[path] = [:rb] end routes_reloader = app.config.file_watcher.new([], admin_dirs) do app.reload_routes! end app.reloaders << routes_reloader ActiveSupport::Reloader.to_prepare do # Rails might have reloaded the routes for other reasons (e.g. # routes.rb has changed), in which case Active Admin would have been # loaded via the `ActiveAdmin.routes` call in `routes.rb`. # # Otherwise, we should check if any of the admin files are changed # and force the routes to reload if necessary. This would again causes # Active Admin to load via `ActiveAdmin.routes`. # # Finally, if Active Admin is still not loaded at this point, then we # would need to load it manually. unless ActiveAdmin.application.loaded? routes_reloader.execute_if_updated ActiveAdmin.application.load! end end end end
[ "def", "attach_reloader", "Rails", ".", "application", ".", "config", ".", "after_initialize", "do", "|", "app", "|", "ActiveSupport", "::", "Reloader", ".", "after_class_unload", "do", "ActiveAdmin", ".", "application", ".", "unload!", "end", "admin_dirs", "=", "{", "}", "load_paths", ".", "each", "do", "|", "path", "|", "admin_dirs", "[", "path", "]", "=", "[", ":rb", "]", "end", "routes_reloader", "=", "app", ".", "config", ".", "file_watcher", ".", "new", "(", "[", "]", ",", "admin_dirs", ")", "do", "app", ".", "reload_routes!", "end", "app", ".", "reloaders", "<<", "routes_reloader", "ActiveSupport", "::", "Reloader", ".", "to_prepare", "do", "# Rails might have reloaded the routes for other reasons (e.g.", "# routes.rb has changed), in which case Active Admin would have been", "# loaded via the `ActiveAdmin.routes` call in `routes.rb`.", "#", "# Otherwise, we should check if any of the admin files are changed", "# and force the routes to reload if necessary. This would again causes", "# Active Admin to load via `ActiveAdmin.routes`.", "#", "# Finally, if Active Admin is still not loaded at this point, then we", "# would need to load it manually.", "unless", "ActiveAdmin", ".", "application", ".", "loaded?", "routes_reloader", ".", "execute_if_updated", "ActiveAdmin", ".", "application", ".", "load!", "end", "end", "end", "end" ]
Hook into the Rails code reloading mechanism so that things are reloaded properly in development mode. If any of the app files (e.g. models) has changed, we need to reload all the admin files. If the admin files themselves has changed, we need to regenerate the routes as well.
[ "Hook", "into", "the", "Rails", "code", "reloading", "mechanism", "so", "that", "things", "are", "reloaded", "properly", "in", "development", "mode", "." ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/application.rb#L188-L223
11,060
activeadmin/activeadmin
lib/active_admin/form_builder.rb
ActiveAdmin.HasManyBuilder.extract_custom_settings!
def extract_custom_settings!(options) @heading = options.key?(:heading) ? options.delete(:heading) : default_heading @sortable_column = options.delete(:sortable) @sortable_start = options.delete(:sortable_start) || 0 @new_record = options.key?(:new_record) ? options.delete(:new_record) : true @destroy_option = options.delete(:allow_destroy) options end
ruby
def extract_custom_settings!(options) @heading = options.key?(:heading) ? options.delete(:heading) : default_heading @sortable_column = options.delete(:sortable) @sortable_start = options.delete(:sortable_start) || 0 @new_record = options.key?(:new_record) ? options.delete(:new_record) : true @destroy_option = options.delete(:allow_destroy) options end
[ "def", "extract_custom_settings!", "(", "options", ")", "@heading", "=", "options", ".", "key?", "(", ":heading", ")", "?", "options", ".", "delete", "(", ":heading", ")", ":", "default_heading", "@sortable_column", "=", "options", ".", "delete", "(", ":sortable", ")", "@sortable_start", "=", "options", ".", "delete", "(", ":sortable_start", ")", "||", "0", "@new_record", "=", "options", ".", "key?", "(", ":new_record", ")", "?", "options", ".", "delete", "(", ":new_record", ")", ":", "true", "@destroy_option", "=", "options", ".", "delete", "(", ":allow_destroy", ")", "options", "end" ]
remove options that should not render as attributes
[ "remove", "options", "that", "should", "not", "render", "as", "attributes" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/form_builder.rb#L69-L76
11,061
activeadmin/activeadmin
lib/active_admin/form_builder.rb
ActiveAdmin.HasManyBuilder.render_has_many_form
def render_has_many_form(form_builder, parent, &block) index = parent && form_builder.send(:parent_child_index, parent) template.concat template.capture { yield(form_builder, index) } template.concat has_many_actions(form_builder, "".html_safe) end
ruby
def render_has_many_form(form_builder, parent, &block) index = parent && form_builder.send(:parent_child_index, parent) template.concat template.capture { yield(form_builder, index) } template.concat has_many_actions(form_builder, "".html_safe) end
[ "def", "render_has_many_form", "(", "form_builder", ",", "parent", ",", "&", "block", ")", "index", "=", "parent", "&&", "form_builder", ".", "send", "(", ":parent_child_index", ",", "parent", ")", "template", ".", "concat", "template", ".", "capture", "{", "yield", "(", "form_builder", ",", "index", ")", "}", "template", ".", "concat", "has_many_actions", "(", "form_builder", ",", "\"\"", ".", "html_safe", ")", "end" ]
Renders the Formtastic inputs then appends ActiveAdmin delete and sort actions.
[ "Renders", "the", "Formtastic", "inputs", "then", "appends", "ActiveAdmin", "delete", "and", "sort", "actions", "." ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/form_builder.rb#L101-L105
11,062
activeadmin/activeadmin
lib/active_admin/form_builder.rb
ActiveAdmin.HasManyBuilder.js_for_has_many
def js_for_has_many(class_string, &form_block) assoc_name = assoc_klass.model_name placeholder = "NEW_#{assoc_name.to_s.underscore.upcase.gsub(/\//, '_')}_RECORD" opts = { for: [assoc, assoc_klass.new], class: class_string, for_options: { child_index: placeholder } } html = template.capture { __getobj__.send(:inputs_for_nested_attributes, opts, &form_block) } text = new_record.is_a?(String) ? new_record : I18n.t('active_admin.has_many_new', model: assoc_name.human) template.link_to text, '#', class: "button has_many_add", data: { html: CGI.escapeHTML(html).html_safe, placeholder: placeholder } end
ruby
def js_for_has_many(class_string, &form_block) assoc_name = assoc_klass.model_name placeholder = "NEW_#{assoc_name.to_s.underscore.upcase.gsub(/\//, '_')}_RECORD" opts = { for: [assoc, assoc_klass.new], class: class_string, for_options: { child_index: placeholder } } html = template.capture { __getobj__.send(:inputs_for_nested_attributes, opts, &form_block) } text = new_record.is_a?(String) ? new_record : I18n.t('active_admin.has_many_new', model: assoc_name.human) template.link_to text, '#', class: "button has_many_add", data: { html: CGI.escapeHTML(html).html_safe, placeholder: placeholder } end
[ "def", "js_for_has_many", "(", "class_string", ",", "&", "form_block", ")", "assoc_name", "=", "assoc_klass", ".", "model_name", "placeholder", "=", "\"NEW_#{assoc_name.to_s.underscore.upcase.gsub(/\\//, '_')}_RECORD\"", "opts", "=", "{", "for", ":", "[", "assoc", ",", "assoc_klass", ".", "new", "]", ",", "class", ":", "class_string", ",", "for_options", ":", "{", "child_index", ":", "placeholder", "}", "}", "html", "=", "template", ".", "capture", "{", "__getobj__", ".", "send", "(", ":inputs_for_nested_attributes", ",", "opts", ",", "form_block", ")", "}", "text", "=", "new_record", ".", "is_a?", "(", "String", ")", "?", "new_record", ":", "I18n", ".", "t", "(", "'active_admin.has_many_new'", ",", "model", ":", "assoc_name", ".", "human", ")", "template", ".", "link_to", "text", ",", "'#'", ",", "class", ":", "\"button has_many_add\"", ",", "data", ":", "{", "html", ":", "CGI", ".", "escapeHTML", "(", "html", ")", ".", "html_safe", ",", "placeholder", ":", "placeholder", "}", "end" ]
Capture the ADD JS
[ "Capture", "the", "ADD", "JS" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/form_builder.rb#L158-L172
11,063
activeadmin/activeadmin
lib/active_admin/router.rb
ActiveAdmin.Router.define_resources_routes
def define_resources_routes resources = namespaces.flat_map { |n| n.resources.values } resources.each do |config| define_resource_routes(config) end end
ruby
def define_resources_routes resources = namespaces.flat_map { |n| n.resources.values } resources.each do |config| define_resource_routes(config) end end
[ "def", "define_resources_routes", "resources", "=", "namespaces", ".", "flat_map", "{", "|", "n", "|", "n", ".", "resources", ".", "values", "}", "resources", ".", "each", "do", "|", "config", "|", "define_resource_routes", "(", "config", ")", "end", "end" ]
Defines the routes for each resource
[ "Defines", "the", "routes", "for", "each", "resource" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/router.rb#L30-L35
11,064
activeadmin/activeadmin
lib/active_admin/router.rb
ActiveAdmin.Router.define_actions
def define_actions(config) router.member do config.member_actions.each { |action| build_action(action) } end router.collection do config.collection_actions.each { |action| build_action(action) } router.post :batch_action if config.batch_actions_enabled? end end
ruby
def define_actions(config) router.member do config.member_actions.each { |action| build_action(action) } end router.collection do config.collection_actions.each { |action| build_action(action) } router.post :batch_action if config.batch_actions_enabled? end end
[ "def", "define_actions", "(", "config", ")", "router", ".", "member", "do", "config", ".", "member_actions", ".", "each", "{", "|", "action", "|", "build_action", "(", "action", ")", "}", "end", "router", ".", "collection", "do", "config", ".", "collection_actions", ".", "each", "{", "|", "action", "|", "build_action", "(", "action", ")", "}", "router", ".", "post", ":batch_action", "if", "config", ".", "batch_actions_enabled?", "end", "end" ]
Defines member and collection actions
[ "Defines", "member", "and", "collection", "actions" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/router.rb#L75-L84
11,065
activeadmin/activeadmin
lib/active_admin/callbacks.rb
ActiveAdmin.Callbacks.run_callback
def run_callback(method, *args) case method when Symbol send(method, *args) when Proc instance_exec(*args, &method) else raise "Please register with callbacks using a symbol or a block/proc." end end
ruby
def run_callback(method, *args) case method when Symbol send(method, *args) when Proc instance_exec(*args, &method) else raise "Please register with callbacks using a symbol or a block/proc." end end
[ "def", "run_callback", "(", "method", ",", "*", "args", ")", "case", "method", "when", "Symbol", "send", "(", "method", ",", "args", ")", "when", "Proc", "instance_exec", "(", "args", ",", "method", ")", "else", "raise", "\"Please register with callbacks using a symbol or a block/proc.\"", "end", "end" ]
Simple callback system. Implements before and after callbacks for use within the controllers. We didn't use the ActiveSupport callbacks because they do not support passing in any arbitrary object into the callback method (which we need to do)
[ "Simple", "callback", "system", ".", "Implements", "before", "and", "after", "callbacks", "for", "use", "within", "the", "controllers", "." ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/callbacks.rb#L14-L23
11,066
activeadmin/activeadmin
lib/active_admin/resource_dsl.rb
ActiveAdmin.ResourceDSL.permit_params
def permit_params(*args, &block) param_key = config.param_key.to_sym belongs_to_param = config.belongs_to_param create_another_param = :create_another if config.create_another controller do define_method :permitted_params do permitted_params = active_admin_namespace.permitted_params + Array.wrap(belongs_to_param) + Array.wrap(create_another_param) params.permit(*permitted_params, param_key => block ? instance_exec(&block) : args) end private :permitted_params end end
ruby
def permit_params(*args, &block) param_key = config.param_key.to_sym belongs_to_param = config.belongs_to_param create_another_param = :create_another if config.create_another controller do define_method :permitted_params do permitted_params = active_admin_namespace.permitted_params + Array.wrap(belongs_to_param) + Array.wrap(create_another_param) params.permit(*permitted_params, param_key => block ? instance_exec(&block) : args) end private :permitted_params end end
[ "def", "permit_params", "(", "*", "args", ",", "&", "block", ")", "param_key", "=", "config", ".", "param_key", ".", "to_sym", "belongs_to_param", "=", "config", ".", "belongs_to_param", "create_another_param", "=", ":create_another", "if", "config", ".", "create_another", "controller", "do", "define_method", ":permitted_params", "do", "permitted_params", "=", "active_admin_namespace", ".", "permitted_params", "+", "Array", ".", "wrap", "(", "belongs_to_param", ")", "+", "Array", ".", "wrap", "(", "create_another_param", ")", "params", ".", "permit", "(", "permitted_params", ",", "param_key", "=>", "block", "?", "instance_exec", "(", "block", ")", ":", "args", ")", "end", "private", ":permitted_params", "end", "end" ]
Keys included in the `permitted_params` setting are automatically whitelisted. Either permit_params :title, :author, :body, tags: [] Or permit_params do defaults = [:title, :body] if current_user.admin? defaults + [:author] else defaults end end
[ "Keys", "included", "in", "the", "permitted_params", "setting", "are", "automatically", "whitelisted", "." ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/resource_dsl.rb#L63-L80
11,067
activeadmin/activeadmin
lib/active_admin/resource_dsl.rb
ActiveAdmin.ResourceDSL.index
def index(options = {}, &block) options[:as] ||= :table config.set_page_presenter :index, ActiveAdmin::PagePresenter.new(options, &block) end
ruby
def index(options = {}, &block) options[:as] ||= :table config.set_page_presenter :index, ActiveAdmin::PagePresenter.new(options, &block) end
[ "def", "index", "(", "options", "=", "{", "}", ",", "&", "block", ")", "options", "[", ":as", "]", "||=", ":table", "config", ".", "set_page_presenter", ":index", ",", "ActiveAdmin", "::", "PagePresenter", ".", "new", "(", "options", ",", "block", ")", "end" ]
Configure the index page for the resource
[ "Configure", "the", "index", "page", "for", "the", "resource" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/resource_dsl.rb#L83-L86
11,068
activeadmin/activeadmin
lib/active_admin/resource_dsl.rb
ActiveAdmin.ResourceDSL.show
def show(options = {}, &block) config.set_page_presenter :show, ActiveAdmin::PagePresenter.new(options, &block) end
ruby
def show(options = {}, &block) config.set_page_presenter :show, ActiveAdmin::PagePresenter.new(options, &block) end
[ "def", "show", "(", "options", "=", "{", "}", ",", "&", "block", ")", "config", ".", "set_page_presenter", ":show", ",", "ActiveAdmin", "::", "PagePresenter", ".", "new", "(", "options", ",", "block", ")", "end" ]
Configure the show page for the resource
[ "Configure", "the", "show", "page", "for", "the", "resource" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/resource_dsl.rb#L89-L91
11,069
activeadmin/activeadmin
lib/active_admin/resource_dsl.rb
ActiveAdmin.ResourceDSL.csv
def csv(options = {}, &block) options[:resource] = config config.csv_builder = CSVBuilder.new(options, &block) end
ruby
def csv(options = {}, &block) options[:resource] = config config.csv_builder = CSVBuilder.new(options, &block) end
[ "def", "csv", "(", "options", "=", "{", "}", ",", "&", "block", ")", "options", "[", ":resource", "]", "=", "config", "config", ".", "csv_builder", "=", "CSVBuilder", ".", "new", "(", "options", ",", "block", ")", "end" ]
Configure the CSV format For example: csv do column :name column("Author") { |post| post.author.full_name } end csv col_sep: ";", force_quotes: true do column :name end
[ "Configure", "the", "CSV", "format" ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/resource_dsl.rb#L110-L114
11,070
activeadmin/activeadmin
lib/active_admin/resource_dsl.rb
ActiveAdmin.ResourceDSL.action
def action(set, name, options = {}, &block) warn "Warning: method `#{name}` already defined" if controller.method_defined?(name) set << ControllerAction.new(name, options) title = options.delete(:title) controller do before_action(only: [name]) { @page_title = title } if title define_method(name, &block || Proc.new {}) end end
ruby
def action(set, name, options = {}, &block) warn "Warning: method `#{name}` already defined" if controller.method_defined?(name) set << ControllerAction.new(name, options) title = options.delete(:title) controller do before_action(only: [name]) { @page_title = title } if title define_method(name, &block || Proc.new {}) end end
[ "def", "action", "(", "set", ",", "name", ",", "options", "=", "{", "}", ",", "&", "block", ")", "warn", "\"Warning: method `#{name}` already defined\"", "if", "controller", ".", "method_defined?", "(", "name", ")", "set", "<<", "ControllerAction", ".", "new", "(", "name", ",", "options", ")", "title", "=", "options", ".", "delete", "(", ":title", ")", "controller", "do", "before_action", "(", "only", ":", "[", "name", "]", ")", "{", "@page_title", "=", "title", "}", "if", "title", "define_method", "(", "name", ",", "block", "||", "Proc", ".", "new", "{", "}", ")", "end", "end" ]
Member Actions give you the functionality of defining both the action and the route directly from your ActiveAdmin registration block. For example: ActiveAdmin.register Post do member_action :comments do @post = Post.find(params[:id]) @comments = @post.comments end end Will create a new controller action comments and will hook it up to the named route (comments_admin_post_path) /admin/posts/:id/comments You can treat everything within the block as a standard Rails controller action.
[ "Member", "Actions", "give", "you", "the", "functionality", "of", "defining", "both", "the", "action", "and", "the", "route", "directly", "from", "your", "ActiveAdmin", "registration", "block", "." ]
0759c8dcf97865748c9344459162ac3c7e65a6cd
https://github.com/activeadmin/activeadmin/blob/0759c8dcf97865748c9344459162ac3c7e65a6cd/lib/active_admin/resource_dsl.rb#L135-L145
11,071
Shopify/shopify_api
lib/shopify_api/resources/product.rb
ShopifyAPI.Product.price_range
def price_range prices = variants.collect(&:price).collect(&:to_f) format = "%0.2f" if prices.min != prices.max "#{format % prices.min} - #{format % prices.max}" else format % prices.min end end
ruby
def price_range prices = variants.collect(&:price).collect(&:to_f) format = "%0.2f" if prices.min != prices.max "#{format % prices.min} - #{format % prices.max}" else format % prices.min end end
[ "def", "price_range", "prices", "=", "variants", ".", "collect", "(", ":price", ")", ".", "collect", "(", ":to_f", ")", "format", "=", "\"%0.2f\"", "if", "prices", ".", "min", "!=", "prices", ".", "max", "\"#{format % prices.min} - #{format % prices.max}\"", "else", "format", "%", "prices", ".", "min", "end", "end" ]
compute the price range
[ "compute", "the", "price", "range" ]
2e069578fcaa93188c4f5a919a76df7b3e2e26ef
https://github.com/Shopify/shopify_api/blob/2e069578fcaa93188c4f5a919a76df7b3e2e26ef/lib/shopify_api/resources/product.rb#L7-L15
11,072
sds/overcommit
lib/overcommit/configuration_loader.rb
Overcommit.ConfigurationLoader.load_file
def load_file(file) config = self.class.load_from_file(file, default: false, logger: @log) config = self.class.default_configuration.merge(config) if @options.fetch(:verify) { config.verify_signatures? } verify_signatures(config) end config rescue Overcommit::Exceptions::ConfigurationSignatureChanged raise rescue StandardError => error raise Overcommit::Exceptions::ConfigurationError, "Unable to load configuration from '#{file}': #{error}", error.backtrace end
ruby
def load_file(file) config = self.class.load_from_file(file, default: false, logger: @log) config = self.class.default_configuration.merge(config) if @options.fetch(:verify) { config.verify_signatures? } verify_signatures(config) end config rescue Overcommit::Exceptions::ConfigurationSignatureChanged raise rescue StandardError => error raise Overcommit::Exceptions::ConfigurationError, "Unable to load configuration from '#{file}': #{error}", error.backtrace end
[ "def", "load_file", "(", "file", ")", "config", "=", "self", ".", "class", ".", "load_from_file", "(", "file", ",", "default", ":", "false", ",", "logger", ":", "@log", ")", "config", "=", "self", ".", "class", ".", "default_configuration", ".", "merge", "(", "config", ")", "if", "@options", ".", "fetch", "(", ":verify", ")", "{", "config", ".", "verify_signatures?", "}", "verify_signatures", "(", "config", ")", "end", "config", "rescue", "Overcommit", "::", "Exceptions", "::", "ConfigurationSignatureChanged", "raise", "rescue", "StandardError", "=>", "error", "raise", "Overcommit", "::", "Exceptions", "::", "ConfigurationError", ",", "\"Unable to load configuration from '#{file}': #{error}\"", ",", "error", ".", "backtrace", "end" ]
Loads a configuration, ensuring it extends the default configuration.
[ "Loads", "a", "configuration", "ensuring", "it", "extends", "the", "default", "configuration", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration_loader.rb#L64-L79
11,073
sds/overcommit
lib/overcommit/hook_context/base.rb
Overcommit::HookContext.Base.filter_directories
def filter_directories(modified_files) modified_files.reject do |file| File.directory?(file) && !Overcommit::Utils::FileUtils.symlink?(file) end end
ruby
def filter_directories(modified_files) modified_files.reject do |file| File.directory?(file) && !Overcommit::Utils::FileUtils.symlink?(file) end end
[ "def", "filter_directories", "(", "modified_files", ")", "modified_files", ".", "reject", "do", "|", "file", "|", "File", ".", "directory?", "(", "file", ")", "&&", "!", "Overcommit", "::", "Utils", "::", "FileUtils", ".", "symlink?", "(", "file", ")", "end", "end" ]
Filter out directories. This could happen when changing a symlink to a directory as part of an amendment, since the symlink will still appear as a file, but the actual working tree will have a directory.
[ "Filter", "out", "directories", ".", "This", "could", "happen", "when", "changing", "a", "symlink", "to", "a", "directory", "as", "part", "of", "an", "amendment", "since", "the", "symlink", "will", "still", "appear", "as", "a", "file", "but", "the", "actual", "working", "tree", "will", "have", "a", "directory", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/base.rb#L133-L137
11,074
sds/overcommit
lib/overcommit/hook/pre_commit/yard_coverage.rb
Overcommit::Hook::PreCommit.YardCoverage.check_yard_coverage
def check_yard_coverage(stat_lines) if config['min_coverage_percentage'] match = stat_lines.last.match(/^\s*([\d.]+)%\s+documented\s*$/) unless match return :warn end yard_coverage = match.captures[0].to_f if yard_coverage >= config['min_coverage_percentage'].to_f return :pass end yard_coverage end end
ruby
def check_yard_coverage(stat_lines) if config['min_coverage_percentage'] match = stat_lines.last.match(/^\s*([\d.]+)%\s+documented\s*$/) unless match return :warn end yard_coverage = match.captures[0].to_f if yard_coverage >= config['min_coverage_percentage'].to_f return :pass end yard_coverage end end
[ "def", "check_yard_coverage", "(", "stat_lines", ")", "if", "config", "[", "'min_coverage_percentage'", "]", "match", "=", "stat_lines", ".", "last", ".", "match", "(", "/", "\\s", "\\d", "\\s", "\\s", "/", ")", "unless", "match", "return", ":warn", "end", "yard_coverage", "=", "match", ".", "captures", "[", "0", "]", ".", "to_f", "if", "yard_coverage", ">=", "config", "[", "'min_coverage_percentage'", "]", ".", "to_f", "return", ":pass", "end", "yard_coverage", "end", "end" ]
Check the yard coverage Return a :pass if the coverage is enough, :warn if it couldn't be read, otherwise, it has been read successfully.
[ "Check", "the", "yard", "coverage" ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook/pre_commit/yard_coverage.rb#L49-L63
11,075
sds/overcommit
lib/overcommit/hook/pre_commit/yard_coverage.rb
Overcommit::Hook::PreCommit.YardCoverage.error_messages
def error_messages(yard_coverage, error_text) first_message = "You have a #{yard_coverage}% yard documentation coverage. "\ "#{config['min_coverage_percentage']}% is the minimum required." # Add the undocumented objects text as error messages messages = [Overcommit::Hook::Message.new(:error, nil, nil, first_message)] errors = error_text.strip.split("\n") errors.each do |undocumented_object| undocumented_object_message, file_info = undocumented_object.split(/:?\s+/) file_info_match = file_info.match(/^\(([^:]+):(\d+)\)/) # In case any compacted error does not follow the format, ignore it if file_info_match file = file_info_match.captures[0] line = file_info_match.captures[1] messages << Overcommit::Hook::Message.new( :error, file, line, "#{file}:#{line}: #{undocumented_object_message}" ) end end messages end
ruby
def error_messages(yard_coverage, error_text) first_message = "You have a #{yard_coverage}% yard documentation coverage. "\ "#{config['min_coverage_percentage']}% is the minimum required." # Add the undocumented objects text as error messages messages = [Overcommit::Hook::Message.new(:error, nil, nil, first_message)] errors = error_text.strip.split("\n") errors.each do |undocumented_object| undocumented_object_message, file_info = undocumented_object.split(/:?\s+/) file_info_match = file_info.match(/^\(([^:]+):(\d+)\)/) # In case any compacted error does not follow the format, ignore it if file_info_match file = file_info_match.captures[0] line = file_info_match.captures[1] messages << Overcommit::Hook::Message.new( :error, file, line, "#{file}:#{line}: #{undocumented_object_message}" ) end end messages end
[ "def", "error_messages", "(", "yard_coverage", ",", "error_text", ")", "first_message", "=", "\"You have a #{yard_coverage}% yard documentation coverage. \"", "\"#{config['min_coverage_percentage']}% is the minimum required.\"", "# Add the undocumented objects text as error messages", "messages", "=", "[", "Overcommit", "::", "Hook", "::", "Message", ".", "new", "(", ":error", ",", "nil", ",", "nil", ",", "first_message", ")", "]", "errors", "=", "error_text", ".", "strip", ".", "split", "(", "\"\\n\"", ")", "errors", ".", "each", "do", "|", "undocumented_object", "|", "undocumented_object_message", ",", "file_info", "=", "undocumented_object", ".", "split", "(", "/", "\\s", "/", ")", "file_info_match", "=", "file_info", ".", "match", "(", "/", "\\(", "\\d", "\\)", "/", ")", "# In case any compacted error does not follow the format, ignore it", "if", "file_info_match", "file", "=", "file_info_match", ".", "captures", "[", "0", "]", "line", "=", "file_info_match", ".", "captures", "[", "1", "]", "messages", "<<", "Overcommit", "::", "Hook", "::", "Message", ".", "new", "(", ":error", ",", "file", ",", "line", ",", "\"#{file}:#{line}: #{undocumented_object_message}\"", ")", "end", "end", "messages", "end" ]
Create the error messages
[ "Create", "the", "error", "messages" ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook/pre_commit/yard_coverage.rb#L66-L88
11,076
sds/overcommit
lib/overcommit/hook_context/post_merge.rb
Overcommit::HookContext.PostMerge.modified_files
def modified_files staged = squash? refs = 'HEAD^ HEAD' if merge_commit? @modified_files ||= Overcommit::GitRepo.modified_files(staged: staged, refs: refs) end
ruby
def modified_files staged = squash? refs = 'HEAD^ HEAD' if merge_commit? @modified_files ||= Overcommit::GitRepo.modified_files(staged: staged, refs: refs) end
[ "def", "modified_files", "staged", "=", "squash?", "refs", "=", "'HEAD^ HEAD'", "if", "merge_commit?", "@modified_files", "||=", "Overcommit", "::", "GitRepo", ".", "modified_files", "(", "staged", ":", "staged", ",", "refs", ":", "refs", ")", "end" ]
Get a list of files that were added, copied, or modified in the merge commit. Renames and deletions are ignored, since there should be nothing to check.
[ "Get", "a", "list", "of", "files", "that", "were", "added", "copied", "or", "modified", "in", "the", "merge", "commit", ".", "Renames", "and", "deletions", "are", "ignored", "since", "there", "should", "be", "nothing", "to", "check", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/post_merge.rb#L11-L15
11,077
sds/overcommit
lib/overcommit/hook_context/post_rewrite.rb
Overcommit::HookContext.PostRewrite.modified_files
def modified_files @modified_files ||= begin @modified_files = [] rewritten_commits.each do |rewritten_commit| refs = "#{rewritten_commit.old_hash} #{rewritten_commit.new_hash}" @modified_files |= Overcommit::GitRepo.modified_files(refs: refs) end filter_modified_files(@modified_files) end end
ruby
def modified_files @modified_files ||= begin @modified_files = [] rewritten_commits.each do |rewritten_commit| refs = "#{rewritten_commit.old_hash} #{rewritten_commit.new_hash}" @modified_files |= Overcommit::GitRepo.modified_files(refs: refs) end filter_modified_files(@modified_files) end end
[ "def", "modified_files", "@modified_files", "||=", "begin", "@modified_files", "=", "[", "]", "rewritten_commits", ".", "each", "do", "|", "rewritten_commit", "|", "refs", "=", "\"#{rewritten_commit.old_hash} #{rewritten_commit.new_hash}\"", "@modified_files", "|=", "Overcommit", "::", "GitRepo", ".", "modified_files", "(", "refs", ":", "refs", ")", "end", "filter_modified_files", "(", "@modified_files", ")", "end", "end" ]
Get a list of files that have been added or modified as part of a rewritten commit. Renames and deletions are ignored, since there should be nothing to check.
[ "Get", "a", "list", "of", "files", "that", "have", "been", "added", "or", "modified", "as", "part", "of", "a", "rewritten", "commit", ".", "Renames", "and", "deletions", "are", "ignored", "since", "there", "should", "be", "nothing", "to", "check", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/post_rewrite.rb#L33-L44
11,078
sds/overcommit
lib/overcommit/message_processor.rb
Overcommit.MessageProcessor.basic_status_and_output
def basic_status_and_output(messages) status = if messages.any? { |message| message.type == :error } :fail elsif messages.any? { |message| message.type == :warning } :warn else :pass end output = '' if messages.any? output += messages.join("\n") + "\n" end [status, output] end
ruby
def basic_status_and_output(messages) status = if messages.any? { |message| message.type == :error } :fail elsif messages.any? { |message| message.type == :warning } :warn else :pass end output = '' if messages.any? output += messages.join("\n") + "\n" end [status, output] end
[ "def", "basic_status_and_output", "(", "messages", ")", "status", "=", "if", "messages", ".", "any?", "{", "|", "message", "|", "message", ".", "type", "==", ":error", "}", ":fail", "elsif", "messages", ".", "any?", "{", "|", "message", "|", "message", ".", "type", "==", ":warning", "}", ":warn", "else", ":pass", "end", "output", "=", "''", "if", "messages", ".", "any?", "output", "+=", "messages", ".", "join", "(", "\"\\n\"", ")", "+", "\"\\n\"", "end", "[", "status", ",", "output", "]", "end" ]
Returns status and output for messages assuming no special treatment of messages occurring on unmodified lines.
[ "Returns", "status", "and", "output", "for", "messages", "assuming", "no", "special", "treatment", "of", "messages", "occurring", "on", "unmodified", "lines", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/message_processor.rb#L101-L117
11,079
sds/overcommit
lib/overcommit/hook/base.rb
Overcommit::Hook.Base.run_and_transform
def run_and_transform if output = check_for_requirements status = :fail else result = Overcommit::Utils.with_environment(@config.fetch('env') { {} }) { run } status, output = process_hook_return_value(result) end [transform_status(status), output] end
ruby
def run_and_transform if output = check_for_requirements status = :fail else result = Overcommit::Utils.with_environment(@config.fetch('env') { {} }) { run } status, output = process_hook_return_value(result) end [transform_status(status), output] end
[ "def", "run_and_transform", "if", "output", "=", "check_for_requirements", "status", "=", ":fail", "else", "result", "=", "Overcommit", "::", "Utils", ".", "with_environment", "(", "@config", ".", "fetch", "(", "'env'", ")", "{", "{", "}", "}", ")", "{", "run", "}", "status", ",", "output", "=", "process_hook_return_value", "(", "result", ")", "end", "[", "transform_status", "(", "status", ")", ",", "output", "]", "end" ]
Runs the hook and transforms the status returned based on the hook's configuration. Poorly named because we already have a bunch of hooks in the wild that implement `#run`, and we needed a wrapper step to transform the status based on any custom configuration.
[ "Runs", "the", "hook", "and", "transforms", "the", "status", "returned", "based", "on", "the", "hook", "s", "configuration", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook/base.rb#L43-L52
11,080
sds/overcommit
lib/overcommit/hook/base.rb
Overcommit::Hook.Base.check_for_libraries
def check_for_libraries output = [] required_libraries.each do |library| begin require library rescue LoadError install_command = @config['install_command'] install_command = " -- install via #{install_command}" if install_command output << "Unable to load '#{library}'#{install_command}" end end return if output.empty? output.join("\n") end
ruby
def check_for_libraries output = [] required_libraries.each do |library| begin require library rescue LoadError install_command = @config['install_command'] install_command = " -- install via #{install_command}" if install_command output << "Unable to load '#{library}'#{install_command}" end end return if output.empty? output.join("\n") end
[ "def", "check_for_libraries", "output", "=", "[", "]", "required_libraries", ".", "each", "do", "|", "library", "|", "begin", "require", "library", "rescue", "LoadError", "install_command", "=", "@config", "[", "'install_command'", "]", "install_command", "=", "\" -- install via #{install_command}\"", "if", "install_command", "output", "<<", "\"Unable to load '#{library}'#{install_command}\"", "end", "end", "return", "if", "output", ".", "empty?", "output", ".", "join", "(", "\"\\n\"", ")", "end" ]
If the hook defines required library paths that it wants to load, attempt to load them.
[ "If", "the", "hook", "defines", "required", "library", "paths", "that", "it", "wants", "to", "load", "attempt", "to", "load", "them", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook/base.rb#L221-L238
11,081
sds/overcommit
lib/overcommit/hook_context/pre_commit.rb
Overcommit::HookContext.PreCommit.setup_environment
def setup_environment store_modified_times Overcommit::GitRepo.store_merge_state Overcommit::GitRepo.store_cherry_pick_state if !initial_commit? && any_changes? @stash_attempted = true stash_message = "Overcommit: Stash of repo state before hook run at #{Time.now}" result = Overcommit::Utils.execute( %w[git -c commit.gpgsign=false stash save --keep-index --quiet] + [stash_message] ) unless result.success? # Failure to stash in this case is likely due to a configuration # issue (e.g. author/email not set or GPG signing key incorrect) raise Overcommit::Exceptions::HookSetupFailed, "Unable to setup environment for #{hook_script_name} hook run:" \ "\nSTDOUT:#{result.stdout}\nSTDERR:#{result.stderr}" end @changes_stashed = `git stash list -1`.include?(stash_message) end # While running the hooks make it appear as if nothing changed restore_modified_times end
ruby
def setup_environment store_modified_times Overcommit::GitRepo.store_merge_state Overcommit::GitRepo.store_cherry_pick_state if !initial_commit? && any_changes? @stash_attempted = true stash_message = "Overcommit: Stash of repo state before hook run at #{Time.now}" result = Overcommit::Utils.execute( %w[git -c commit.gpgsign=false stash save --keep-index --quiet] + [stash_message] ) unless result.success? # Failure to stash in this case is likely due to a configuration # issue (e.g. author/email not set or GPG signing key incorrect) raise Overcommit::Exceptions::HookSetupFailed, "Unable to setup environment for #{hook_script_name} hook run:" \ "\nSTDOUT:#{result.stdout}\nSTDERR:#{result.stderr}" end @changes_stashed = `git stash list -1`.include?(stash_message) end # While running the hooks make it appear as if nothing changed restore_modified_times end
[ "def", "setup_environment", "store_modified_times", "Overcommit", "::", "GitRepo", ".", "store_merge_state", "Overcommit", "::", "GitRepo", ".", "store_cherry_pick_state", "if", "!", "initial_commit?", "&&", "any_changes?", "@stash_attempted", "=", "true", "stash_message", "=", "\"Overcommit: Stash of repo state before hook run at #{Time.now}\"", "result", "=", "Overcommit", "::", "Utils", ".", "execute", "(", "%w[", "git", "-c", "commit.gpgsign=false", "stash", "save", "--keep-index", "--quiet", "]", "+", "[", "stash_message", "]", ")", "unless", "result", ".", "success?", "# Failure to stash in this case is likely due to a configuration", "# issue (e.g. author/email not set or GPG signing key incorrect)", "raise", "Overcommit", "::", "Exceptions", "::", "HookSetupFailed", ",", "\"Unable to setup environment for #{hook_script_name} hook run:\"", "\"\\nSTDOUT:#{result.stdout}\\nSTDERR:#{result.stderr}\"", "end", "@changes_stashed", "=", "`", "`", ".", "include?", "(", "stash_message", ")", "end", "# While running the hooks make it appear as if nothing changed", "restore_modified_times", "end" ]
Stash unstaged contents of files so hooks don't see changes that aren't about to be committed.
[ "Stash", "unstaged", "contents", "of", "files", "so", "hooks", "don", "t", "see", "changes", "that", "aren", "t", "about", "to", "be", "committed", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/pre_commit.rb#L46-L72
11,082
sds/overcommit
lib/overcommit/hook_context/pre_commit.rb
Overcommit::HookContext.PreCommit.cleanup_environment
def cleanup_environment unless initial_commit? || (@stash_attempted && !@changes_stashed) clear_working_tree # Ensure working tree is clean before restoring it restore_modified_times end if @changes_stashed restore_working_tree restore_modified_times end Overcommit::GitRepo.restore_merge_state Overcommit::GitRepo.restore_cherry_pick_state restore_modified_times end
ruby
def cleanup_environment unless initial_commit? || (@stash_attempted && !@changes_stashed) clear_working_tree # Ensure working tree is clean before restoring it restore_modified_times end if @changes_stashed restore_working_tree restore_modified_times end Overcommit::GitRepo.restore_merge_state Overcommit::GitRepo.restore_cherry_pick_state restore_modified_times end
[ "def", "cleanup_environment", "unless", "initial_commit?", "||", "(", "@stash_attempted", "&&", "!", "@changes_stashed", ")", "clear_working_tree", "# Ensure working tree is clean before restoring it", "restore_modified_times", "end", "if", "@changes_stashed", "restore_working_tree", "restore_modified_times", "end", "Overcommit", "::", "GitRepo", ".", "restore_merge_state", "Overcommit", "::", "GitRepo", ".", "restore_cherry_pick_state", "restore_modified_times", "end" ]
Restore unstaged changes and reset file modification times so it appears as if nothing ever changed. We want to restore the modification times for each of the files after every step to ensure as little time as possible has passed while the modification time on the file was newer. This helps us play more nicely with file watchers.
[ "Restore", "unstaged", "changes", "and", "reset", "file", "modification", "times", "so", "it", "appears", "as", "if", "nothing", "ever", "changed", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/pre_commit.rb#L81-L95
11,083
sds/overcommit
lib/overcommit/hook_context/pre_commit.rb
Overcommit::HookContext.PreCommit.modified_files
def modified_files unless @modified_files currently_staged = Overcommit::GitRepo.modified_files(staged: true) @modified_files = currently_staged # Include files modified in last commit if amending if amendment? subcmd = 'show --format=%n' previously_modified = Overcommit::GitRepo.modified_files(subcmd: subcmd) @modified_files |= filter_modified_files(previously_modified) end end @modified_files end
ruby
def modified_files unless @modified_files currently_staged = Overcommit::GitRepo.modified_files(staged: true) @modified_files = currently_staged # Include files modified in last commit if amending if amendment? subcmd = 'show --format=%n' previously_modified = Overcommit::GitRepo.modified_files(subcmd: subcmd) @modified_files |= filter_modified_files(previously_modified) end end @modified_files end
[ "def", "modified_files", "unless", "@modified_files", "currently_staged", "=", "Overcommit", "::", "GitRepo", ".", "modified_files", "(", "staged", ":", "true", ")", "@modified_files", "=", "currently_staged", "# Include files modified in last commit if amending", "if", "amendment?", "subcmd", "=", "'show --format=%n'", "previously_modified", "=", "Overcommit", "::", "GitRepo", ".", "modified_files", "(", "subcmd", ":", "subcmd", ")", "@modified_files", "|=", "filter_modified_files", "(", "previously_modified", ")", "end", "end", "@modified_files", "end" ]
Get a list of added, copied, or modified files that have been staged. Renames and deletions are ignored, since there should be nothing to check.
[ "Get", "a", "list", "of", "added", "copied", "or", "modified", "files", "that", "have", "been", "staged", ".", "Renames", "and", "deletions", "are", "ignored", "since", "there", "should", "be", "nothing", "to", "check", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/pre_commit.rb#L99-L112
11,084
sds/overcommit
lib/overcommit/hook_context/pre_commit.rb
Overcommit::HookContext.PreCommit.clear_working_tree
def clear_working_tree removed_submodules = Overcommit::GitRepo.staged_submodule_removals result = Overcommit::Utils.execute(%w[git reset --hard]) unless result.success? raise Overcommit::Exceptions::HookCleanupFailed, "Unable to cleanup working tree after #{hook_script_name} hooks run:" \ "\nSTDOUT:#{result.stdout}\nSTDERR:#{result.stderr}" end # Hard-resetting a staged submodule removal results in the index being # reset but the submodule being restored as an empty directory. This empty # directory prevents us from stashing on a subsequent run if a hook fails. # # Work around this by removing these empty submodule directories as there # doesn't appear any reason to keep them around. removed_submodules.each do |submodule| FileUtils.rmdir(submodule.path) end end
ruby
def clear_working_tree removed_submodules = Overcommit::GitRepo.staged_submodule_removals result = Overcommit::Utils.execute(%w[git reset --hard]) unless result.success? raise Overcommit::Exceptions::HookCleanupFailed, "Unable to cleanup working tree after #{hook_script_name} hooks run:" \ "\nSTDOUT:#{result.stdout}\nSTDERR:#{result.stderr}" end # Hard-resetting a staged submodule removal results in the index being # reset but the submodule being restored as an empty directory. This empty # directory prevents us from stashing on a subsequent run if a hook fails. # # Work around this by removing these empty submodule directories as there # doesn't appear any reason to keep them around. removed_submodules.each do |submodule| FileUtils.rmdir(submodule.path) end end
[ "def", "clear_working_tree", "removed_submodules", "=", "Overcommit", "::", "GitRepo", ".", "staged_submodule_removals", "result", "=", "Overcommit", "::", "Utils", ".", "execute", "(", "%w[", "git", "reset", "--hard", "]", ")", "unless", "result", ".", "success?", "raise", "Overcommit", "::", "Exceptions", "::", "HookCleanupFailed", ",", "\"Unable to cleanup working tree after #{hook_script_name} hooks run:\"", "\"\\nSTDOUT:#{result.stdout}\\nSTDERR:#{result.stderr}\"", "end", "# Hard-resetting a staged submodule removal results in the index being", "# reset but the submodule being restored as an empty directory. This empty", "# directory prevents us from stashing on a subsequent run if a hook fails.", "#", "# Work around this by removing these empty submodule directories as there", "# doesn't appear any reason to keep them around.", "removed_submodules", ".", "each", "do", "|", "submodule", "|", "FileUtils", ".", "rmdir", "(", "submodule", ".", "path", ")", "end", "end" ]
Clears the working tree so that the stash can be applied.
[ "Clears", "the", "working", "tree", "so", "that", "the", "stash", "can", "be", "applied", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/pre_commit.rb#L141-L160
11,085
sds/overcommit
lib/overcommit/hook_context/pre_commit.rb
Overcommit::HookContext.PreCommit.restore_working_tree
def restore_working_tree result = Overcommit::Utils.execute(%w[git stash pop --index --quiet]) unless result.success? raise Overcommit::Exceptions::HookCleanupFailed, "Unable to restore working tree after #{hook_script_name} hooks run:" \ "\nSTDOUT:#{result.stdout}\nSTDERR:#{result.stderr}" end end
ruby
def restore_working_tree result = Overcommit::Utils.execute(%w[git stash pop --index --quiet]) unless result.success? raise Overcommit::Exceptions::HookCleanupFailed, "Unable to restore working tree after #{hook_script_name} hooks run:" \ "\nSTDOUT:#{result.stdout}\nSTDERR:#{result.stderr}" end end
[ "def", "restore_working_tree", "result", "=", "Overcommit", "::", "Utils", ".", "execute", "(", "%w[", "git", "stash", "pop", "--index", "--quiet", "]", ")", "unless", "result", ".", "success?", "raise", "Overcommit", "::", "Exceptions", "::", "HookCleanupFailed", ",", "\"Unable to restore working tree after #{hook_script_name} hooks run:\"", "\"\\nSTDOUT:#{result.stdout}\\nSTDERR:#{result.stderr}\"", "end", "end" ]
Applies the stash to the working tree to restore the user's state.
[ "Applies", "the", "stash", "to", "the", "working", "tree", "to", "restore", "the", "user", "s", "state", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/pre_commit.rb#L163-L170
11,086
sds/overcommit
lib/overcommit/hook_context/pre_commit.rb
Overcommit::HookContext.PreCommit.store_modified_times
def store_modified_times @modified_times = {} staged_files = modified_files unstaged_files = Overcommit::GitRepo.modified_files(staged: false) (staged_files + unstaged_files).each do |file| next if Overcommit::Utils.broken_symlink?(file) next unless File.exist?(file) # Ignore renamed files (old file no longer exists) @modified_times[file] = File.mtime(file) end end
ruby
def store_modified_times @modified_times = {} staged_files = modified_files unstaged_files = Overcommit::GitRepo.modified_files(staged: false) (staged_files + unstaged_files).each do |file| next if Overcommit::Utils.broken_symlink?(file) next unless File.exist?(file) # Ignore renamed files (old file no longer exists) @modified_times[file] = File.mtime(file) end end
[ "def", "store_modified_times", "@modified_times", "=", "{", "}", "staged_files", "=", "modified_files", "unstaged_files", "=", "Overcommit", "::", "GitRepo", ".", "modified_files", "(", "staged", ":", "false", ")", "(", "staged_files", "+", "unstaged_files", ")", ".", "each", "do", "|", "file", "|", "next", "if", "Overcommit", "::", "Utils", ".", "broken_symlink?", "(", "file", ")", "next", "unless", "File", ".", "exist?", "(", "file", ")", "# Ignore renamed files (old file no longer exists)", "@modified_times", "[", "file", "]", "=", "File", ".", "mtime", "(", "file", ")", "end", "end" ]
Stores the modification times for all modified files to make it appear like they never changed. This prevents (some) editors from complaining about files changing when we stash changes before running the hooks.
[ "Stores", "the", "modification", "times", "for", "all", "modified", "files", "to", "make", "it", "appear", "like", "they", "never", "changed", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/pre_commit.rb#L187-L198
11,087
sds/overcommit
lib/overcommit/hook_context/pre_commit.rb
Overcommit::HookContext.PreCommit.restore_modified_times
def restore_modified_times @modified_times.each do |file, time| next if Overcommit::Utils.broken_symlink?(file) next unless File.exist?(file) File.utime(time, time, file) end end
ruby
def restore_modified_times @modified_times.each do |file, time| next if Overcommit::Utils.broken_symlink?(file) next unless File.exist?(file) File.utime(time, time, file) end end
[ "def", "restore_modified_times", "@modified_times", ".", "each", "do", "|", "file", ",", "time", "|", "next", "if", "Overcommit", "::", "Utils", ".", "broken_symlink?", "(", "file", ")", "next", "unless", "File", ".", "exist?", "(", "file", ")", "File", ".", "utime", "(", "time", ",", "time", ",", "file", ")", "end", "end" ]
Restores the file modification times for all modified files to make it appear like they never changed.
[ "Restores", "the", "file", "modification", "times", "for", "all", "modified", "files", "to", "make", "it", "appear", "like", "they", "never", "changed", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/hook_context/pre_commit.rb#L202-L208
11,088
sds/overcommit
lib/overcommit/configuration_validator.rb
Overcommit.ConfigurationValidator.validate
def validate(config, hash, options) @options = options.dup @log = options[:logger] hash = convert_nils_to_empty_hashes(hash) ensure_hook_type_sections_exist(hash) check_hook_name_format(hash) check_hook_env(hash) check_for_missing_enabled_option(hash) unless @options[:default] check_for_too_many_processors(config, hash) check_for_verify_plugin_signatures_option(hash) hash end
ruby
def validate(config, hash, options) @options = options.dup @log = options[:logger] hash = convert_nils_to_empty_hashes(hash) ensure_hook_type_sections_exist(hash) check_hook_name_format(hash) check_hook_env(hash) check_for_missing_enabled_option(hash) unless @options[:default] check_for_too_many_processors(config, hash) check_for_verify_plugin_signatures_option(hash) hash end
[ "def", "validate", "(", "config", ",", "hash", ",", "options", ")", "@options", "=", "options", ".", "dup", "@log", "=", "options", "[", ":logger", "]", "hash", "=", "convert_nils_to_empty_hashes", "(", "hash", ")", "ensure_hook_type_sections_exist", "(", "hash", ")", "check_hook_name_format", "(", "hash", ")", "check_hook_env", "(", "hash", ")", "check_for_missing_enabled_option", "(", "hash", ")", "unless", "@options", "[", ":default", "]", "check_for_too_many_processors", "(", "config", ",", "hash", ")", "check_for_verify_plugin_signatures_option", "(", "hash", ")", "hash", "end" ]
Validates hash for any invalid options, normalizing where possible. @param config [Overcommit::Configuration] @param hash [Hash] hash representation of YAML config @param options[Hash] @option default [Boolean] whether hash represents the default built-in config @option logger [Overcommit::Logger] logger to output warnings to @return [Hash] validated hash (potentially modified)
[ "Validates", "hash", "for", "any", "invalid", "options", "normalizing", "where", "possible", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration_validator.rb#L15-L28
11,089
sds/overcommit
lib/overcommit/configuration_validator.rb
Overcommit.ConfigurationValidator.convert_nils_to_empty_hashes
def convert_nils_to_empty_hashes(hash) hash.each_with_object({}) do |(key, value), h| h[key] = case value when nil then {} when Hash then convert_nils_to_empty_hashes(value) else value end end end
ruby
def convert_nils_to_empty_hashes(hash) hash.each_with_object({}) do |(key, value), h| h[key] = case value when nil then {} when Hash then convert_nils_to_empty_hashes(value) else value end end end
[ "def", "convert_nils_to_empty_hashes", "(", "hash", ")", "hash", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "(", "key", ",", "value", ")", ",", "h", "|", "h", "[", "key", "]", "=", "case", "value", "when", "nil", "then", "{", "}", "when", "Hash", "then", "convert_nils_to_empty_hashes", "(", "value", ")", "else", "value", "end", "end", "end" ]
Normalizes `nil` values to empty hashes. This is useful for when we want to merge two configuration hashes together, since it's easier to merge two hashes than to have to check if one of the values is nil.
[ "Normalizes", "nil", "values", "to", "empty", "hashes", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration_validator.rb#L46-L56
11,090
sds/overcommit
lib/overcommit/configuration_validator.rb
Overcommit.ConfigurationValidator.check_hook_name_format
def check_hook_name_format(hash) errors = [] Overcommit::Utils.supported_hook_type_classes.each do |hook_type| hash.fetch(hook_type) { {} }.each_key do |hook_name| next if hook_name == 'ALL' unless hook_name.match?(/\A[A-Za-z0-9]+\z/) errors << "#{hook_type}::#{hook_name} has an invalid name " \ "#{hook_name}. It must contain only alphanumeric " \ 'characters (no underscores or dashes, etc.)' end end end if errors.any? if @log @log.error errors.join("\n") @log.newline end raise Overcommit::Exceptions::ConfigurationError, 'One or more hooks had invalid names' end end
ruby
def check_hook_name_format(hash) errors = [] Overcommit::Utils.supported_hook_type_classes.each do |hook_type| hash.fetch(hook_type) { {} }.each_key do |hook_name| next if hook_name == 'ALL' unless hook_name.match?(/\A[A-Za-z0-9]+\z/) errors << "#{hook_type}::#{hook_name} has an invalid name " \ "#{hook_name}. It must contain only alphanumeric " \ 'characters (no underscores or dashes, etc.)' end end end if errors.any? if @log @log.error errors.join("\n") @log.newline end raise Overcommit::Exceptions::ConfigurationError, 'One or more hooks had invalid names' end end
[ "def", "check_hook_name_format", "(", "hash", ")", "errors", "=", "[", "]", "Overcommit", "::", "Utils", ".", "supported_hook_type_classes", ".", "each", "do", "|", "hook_type", "|", "hash", ".", "fetch", "(", "hook_type", ")", "{", "{", "}", "}", ".", "each_key", "do", "|", "hook_name", "|", "next", "if", "hook_name", "==", "'ALL'", "unless", "hook_name", ".", "match?", "(", "/", "\\A", "\\z", "/", ")", "errors", "<<", "\"#{hook_type}::#{hook_name} has an invalid name \"", "\"#{hook_name}. It must contain only alphanumeric \"", "'characters (no underscores or dashes, etc.)'", "end", "end", "end", "if", "errors", ".", "any?", "if", "@log", "@log", ".", "error", "errors", ".", "join", "(", "\"\\n\"", ")", "@log", ".", "newline", "end", "raise", "Overcommit", "::", "Exceptions", "::", "ConfigurationError", ",", "'One or more hooks had invalid names'", "end", "end" ]
Prints an error message and raises an exception if a hook has an invalid name, since this can result in strange errors elsewhere.
[ "Prints", "an", "error", "message", "and", "raises", "an", "exception", "if", "a", "hook", "has", "an", "invalid", "name", "since", "this", "can", "result", "in", "strange", "errors", "elsewhere", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration_validator.rb#L98-L121
11,091
sds/overcommit
lib/overcommit/configuration_validator.rb
Overcommit.ConfigurationValidator.check_for_missing_enabled_option
def check_for_missing_enabled_option(hash) return unless @log any_warnings = false Overcommit::Utils.supported_hook_type_classes.each do |hook_type| hash.fetch(hook_type) { {} }.each do |hook_name, hook_config| next if hook_name == 'ALL' if hook_config['enabled'].nil? @log.warning "#{hook_type}::#{hook_name} hook does not explicitly " \ 'set `enabled` option in .overcommit.yml' any_warnings = true end end end @log.newline if any_warnings end
ruby
def check_for_missing_enabled_option(hash) return unless @log any_warnings = false Overcommit::Utils.supported_hook_type_classes.each do |hook_type| hash.fetch(hook_type) { {} }.each do |hook_name, hook_config| next if hook_name == 'ALL' if hook_config['enabled'].nil? @log.warning "#{hook_type}::#{hook_name} hook does not explicitly " \ 'set `enabled` option in .overcommit.yml' any_warnings = true end end end @log.newline if any_warnings end
[ "def", "check_for_missing_enabled_option", "(", "hash", ")", "return", "unless", "@log", "any_warnings", "=", "false", "Overcommit", "::", "Utils", ".", "supported_hook_type_classes", ".", "each", "do", "|", "hook_type", "|", "hash", ".", "fetch", "(", "hook_type", ")", "{", "{", "}", "}", ".", "each", "do", "|", "hook_name", ",", "hook_config", "|", "next", "if", "hook_name", "==", "'ALL'", "if", "hook_config", "[", "'enabled'", "]", ".", "nil?", "@log", ".", "warning", "\"#{hook_type}::#{hook_name} hook does not explicitly \"", "'set `enabled` option in .overcommit.yml'", "any_warnings", "=", "true", "end", "end", "end", "@log", ".", "newline", "if", "any_warnings", "end" ]
Prints a warning if there are any hooks listed in the configuration without `enabled` explicitly set.
[ "Prints", "a", "warning", "if", "there", "are", "any", "hooks", "listed", "in", "the", "configuration", "without", "enabled", "explicitly", "set", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration_validator.rb#L125-L143
11,092
sds/overcommit
lib/overcommit/configuration_validator.rb
Overcommit.ConfigurationValidator.check_for_too_many_processors
def check_for_too_many_processors(config, hash) concurrency = config.concurrency errors = [] Overcommit::Utils.supported_hook_type_classes.each do |hook_type| hash.fetch(hook_type) { {} }.each do |hook_name, hook_config| processors = hook_config.fetch('processors') { 1 } if processors > concurrency errors << "#{hook_type}::#{hook_name} `processors` value " \ "(#{processors}) is larger than the global `concurrency` " \ "option (#{concurrency})" end end end if errors.any? if @log @log.error errors.join("\n") @log.newline end raise Overcommit::Exceptions::ConfigurationError, 'One or more hooks had invalid `processor` value configured' end end
ruby
def check_for_too_many_processors(config, hash) concurrency = config.concurrency errors = [] Overcommit::Utils.supported_hook_type_classes.each do |hook_type| hash.fetch(hook_type) { {} }.each do |hook_name, hook_config| processors = hook_config.fetch('processors') { 1 } if processors > concurrency errors << "#{hook_type}::#{hook_name} `processors` value " \ "(#{processors}) is larger than the global `concurrency` " \ "option (#{concurrency})" end end end if errors.any? if @log @log.error errors.join("\n") @log.newline end raise Overcommit::Exceptions::ConfigurationError, 'One or more hooks had invalid `processor` value configured' end end
[ "def", "check_for_too_many_processors", "(", "config", ",", "hash", ")", "concurrency", "=", "config", ".", "concurrency", "errors", "=", "[", "]", "Overcommit", "::", "Utils", ".", "supported_hook_type_classes", ".", "each", "do", "|", "hook_type", "|", "hash", ".", "fetch", "(", "hook_type", ")", "{", "{", "}", "}", ".", "each", "do", "|", "hook_name", ",", "hook_config", "|", "processors", "=", "hook_config", ".", "fetch", "(", "'processors'", ")", "{", "1", "}", "if", "processors", ">", "concurrency", "errors", "<<", "\"#{hook_type}::#{hook_name} `processors` value \"", "\"(#{processors}) is larger than the global `concurrency` \"", "\"option (#{concurrency})\"", "end", "end", "end", "if", "errors", ".", "any?", "if", "@log", "@log", ".", "error", "errors", ".", "join", "(", "\"\\n\"", ")", "@log", ".", "newline", "end", "raise", "Overcommit", "::", "Exceptions", "::", "ConfigurationError", ",", "'One or more hooks had invalid `processor` value configured'", "end", "end" ]
Prints a warning if any hook has a number of processors larger than the global `concurrency` setting.
[ "Prints", "a", "warning", "if", "any", "hook", "has", "a", "number", "of", "processors", "larger", "than", "the", "global", "concurrency", "setting", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration_validator.rb#L147-L170
11,093
sds/overcommit
lib/overcommit/configuration.rb
Overcommit.Configuration.all_builtin_hook_configs
def all_builtin_hook_configs hook_configs = {} Overcommit::Utils.supported_hook_type_classes.each do |hook_type| hook_names = @hash[hook_type].keys.reject { |name| name == 'ALL' } hook_configs[hook_type] = Hash[ hook_names.map do |hook_name| [hook_name, for_hook(hook_name, hook_type)] end ] end hook_configs end
ruby
def all_builtin_hook_configs hook_configs = {} Overcommit::Utils.supported_hook_type_classes.each do |hook_type| hook_names = @hash[hook_type].keys.reject { |name| name == 'ALL' } hook_configs[hook_type] = Hash[ hook_names.map do |hook_name| [hook_name, for_hook(hook_name, hook_type)] end ] end hook_configs end
[ "def", "all_builtin_hook_configs", "hook_configs", "=", "{", "}", "Overcommit", "::", "Utils", ".", "supported_hook_type_classes", ".", "each", "do", "|", "hook_type", "|", "hook_names", "=", "@hash", "[", "hook_type", "]", ".", "keys", ".", "reject", "{", "|", "name", "|", "name", "==", "'ALL'", "}", "hook_configs", "[", "hook_type", "]", "=", "Hash", "[", "hook_names", ".", "map", "do", "|", "hook_name", "|", "[", "hook_name", ",", "for_hook", "(", "hook_name", ",", "hook_type", ")", "]", "end", "]", "end", "hook_configs", "end" ]
Returns configuration for all built-in hooks in each hook type. @return [Hash]
[ "Returns", "configuration", "for", "all", "built", "-", "in", "hooks", "in", "each", "hook", "type", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration.rb#L72-L86
11,094
sds/overcommit
lib/overcommit/configuration.rb
Overcommit.Configuration.all_plugin_hook_configs
def all_plugin_hook_configs hook_configs = {} Overcommit::Utils.supported_hook_types.each do |hook_type| hook_type_class_name = Overcommit::Utils.camel_case(hook_type) directory = File.join(plugin_directory, hook_type.tr('-', '_')) plugin_paths = Dir[File.join(directory, '*.rb')].sort hook_names = plugin_paths.map do |path| Overcommit::Utils.camel_case(File.basename(path, '.rb')) end hook_configs[hook_type_class_name] = Hash[ hook_names.map do |hook_name| [hook_name, for_hook(hook_name, Overcommit::Utils.camel_case(hook_type))] end ] end hook_configs end
ruby
def all_plugin_hook_configs hook_configs = {} Overcommit::Utils.supported_hook_types.each do |hook_type| hook_type_class_name = Overcommit::Utils.camel_case(hook_type) directory = File.join(plugin_directory, hook_type.tr('-', '_')) plugin_paths = Dir[File.join(directory, '*.rb')].sort hook_names = plugin_paths.map do |path| Overcommit::Utils.camel_case(File.basename(path, '.rb')) end hook_configs[hook_type_class_name] = Hash[ hook_names.map do |hook_name| [hook_name, for_hook(hook_name, Overcommit::Utils.camel_case(hook_type))] end ] end hook_configs end
[ "def", "all_plugin_hook_configs", "hook_configs", "=", "{", "}", "Overcommit", "::", "Utils", ".", "supported_hook_types", ".", "each", "do", "|", "hook_type", "|", "hook_type_class_name", "=", "Overcommit", "::", "Utils", ".", "camel_case", "(", "hook_type", ")", "directory", "=", "File", ".", "join", "(", "plugin_directory", ",", "hook_type", ".", "tr", "(", "'-'", ",", "'_'", ")", ")", "plugin_paths", "=", "Dir", "[", "File", ".", "join", "(", "directory", ",", "'*.rb'", ")", "]", ".", "sort", "hook_names", "=", "plugin_paths", ".", "map", "do", "|", "path", "|", "Overcommit", "::", "Utils", ".", "camel_case", "(", "File", ".", "basename", "(", "path", ",", "'.rb'", ")", ")", "end", "hook_configs", "[", "hook_type_class_name", "]", "=", "Hash", "[", "hook_names", ".", "map", "do", "|", "hook_name", "|", "[", "hook_name", ",", "for_hook", "(", "hook_name", ",", "Overcommit", "::", "Utils", ".", "camel_case", "(", "hook_type", ")", ")", "]", "end", "]", "end", "hook_configs", "end" ]
Returns configuration for all plugin hooks in each hook type. @return [Hash]
[ "Returns", "configuration", "for", "all", "plugin", "hooks", "in", "each", "hook", "type", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration.rb#L91-L112
11,095
sds/overcommit
lib/overcommit/configuration.rb
Overcommit.Configuration.enabled_builtin_hooks
def enabled_builtin_hooks(hook_context) @hash[hook_context.hook_class_name].keys. reject { |hook_name| hook_name == 'ALL' }. select { |hook_name| built_in_hook?(hook_context, hook_name) }. select { |hook_name| hook_enabled?(hook_context, hook_name) } end
ruby
def enabled_builtin_hooks(hook_context) @hash[hook_context.hook_class_name].keys. reject { |hook_name| hook_name == 'ALL' }. select { |hook_name| built_in_hook?(hook_context, hook_name) }. select { |hook_name| hook_enabled?(hook_context, hook_name) } end
[ "def", "enabled_builtin_hooks", "(", "hook_context", ")", "@hash", "[", "hook_context", ".", "hook_class_name", "]", ".", "keys", ".", "reject", "{", "|", "hook_name", "|", "hook_name", "==", "'ALL'", "}", ".", "select", "{", "|", "hook_name", "|", "built_in_hook?", "(", "hook_context", ",", "hook_name", ")", "}", ".", "select", "{", "|", "hook_name", "|", "hook_enabled?", "(", "hook_context", ",", "hook_name", ")", "}", "end" ]
Returns the built-in hooks that have been enabled for a hook type.
[ "Returns", "the", "built", "-", "in", "hooks", "that", "have", "been", "enabled", "for", "a", "hook", "type", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration.rb#L115-L120
11,096
sds/overcommit
lib/overcommit/configuration.rb
Overcommit.Configuration.enabled_ad_hoc_hooks
def enabled_ad_hoc_hooks(hook_context) @hash[hook_context.hook_class_name].keys. reject { |hook_name| hook_name == 'ALL' }. select { |hook_name| ad_hoc_hook?(hook_context, hook_name) }. select { |hook_name| hook_enabled?(hook_context, hook_name) } end
ruby
def enabled_ad_hoc_hooks(hook_context) @hash[hook_context.hook_class_name].keys. reject { |hook_name| hook_name == 'ALL' }. select { |hook_name| ad_hoc_hook?(hook_context, hook_name) }. select { |hook_name| hook_enabled?(hook_context, hook_name) } end
[ "def", "enabled_ad_hoc_hooks", "(", "hook_context", ")", "@hash", "[", "hook_context", ".", "hook_class_name", "]", ".", "keys", ".", "reject", "{", "|", "hook_name", "|", "hook_name", "==", "'ALL'", "}", ".", "select", "{", "|", "hook_name", "|", "ad_hoc_hook?", "(", "hook_context", ",", "hook_name", ")", "}", ".", "select", "{", "|", "hook_name", "|", "hook_enabled?", "(", "hook_context", ",", "hook_name", ")", "}", "end" ]
Returns the ad hoc hooks that have been enabled for a hook type.
[ "Returns", "the", "ad", "hoc", "hooks", "that", "have", "been", "enabled", "for", "a", "hook", "type", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration.rb#L123-L128
11,097
sds/overcommit
lib/overcommit/configuration.rb
Overcommit.Configuration.for_hook
def for_hook(hook, hook_type = nil) unless hook_type components = hook.class.name.split('::') hook = components.last hook_type = components[-2] end # Merge hook configuration with special 'ALL' config hook_config = smart_merge(@hash[hook_type]['ALL'], @hash[hook_type][hook] || {}) # Need to specially handle `enabled` option since not setting it does not # necessarily mean the hook is disabled hook_config['enabled'] = hook_enabled?(hook_type, hook) hook_config.freeze end
ruby
def for_hook(hook, hook_type = nil) unless hook_type components = hook.class.name.split('::') hook = components.last hook_type = components[-2] end # Merge hook configuration with special 'ALL' config hook_config = smart_merge(@hash[hook_type]['ALL'], @hash[hook_type][hook] || {}) # Need to specially handle `enabled` option since not setting it does not # necessarily mean the hook is disabled hook_config['enabled'] = hook_enabled?(hook_type, hook) hook_config.freeze end
[ "def", "for_hook", "(", "hook", ",", "hook_type", "=", "nil", ")", "unless", "hook_type", "components", "=", "hook", ".", "class", ".", "name", ".", "split", "(", "'::'", ")", "hook", "=", "components", ".", "last", "hook_type", "=", "components", "[", "-", "2", "]", "end", "# Merge hook configuration with special 'ALL' config", "hook_config", "=", "smart_merge", "(", "@hash", "[", "hook_type", "]", "[", "'ALL'", "]", ",", "@hash", "[", "hook_type", "]", "[", "hook", "]", "||", "{", "}", ")", "# Need to specially handle `enabled` option since not setting it does not", "# necessarily mean the hook is disabled", "hook_config", "[", "'enabled'", "]", "=", "hook_enabled?", "(", "hook_type", ",", "hook", ")", "hook_config", ".", "freeze", "end" ]
Returns a non-modifiable configuration for a hook.
[ "Returns", "a", "non", "-", "modifiable", "configuration", "for", "a", "hook", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration.rb#L131-L146
11,098
sds/overcommit
lib/overcommit/configuration.rb
Overcommit.Configuration.apply_environment!
def apply_environment!(hook_context, env) skipped_hooks = "#{env['SKIP']} #{env['SKIP_CHECKS']} #{env['SKIP_HOOKS']}".split(/[:, ]/) only_hooks = env.fetch('ONLY') { '' }.split(/[:, ]/) hook_type = hook_context.hook_class_name if only_hooks.any? || skipped_hooks.include?('all') || skipped_hooks.include?('ALL') @hash[hook_type]['ALL']['skip'] = true end only_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }. map { |hook_name| Overcommit::Utils.camel_case(hook_name) }. each do |hook_name| @hash[hook_type][hook_name] ||= {} @hash[hook_type][hook_name]['skip'] = false end skipped_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }. map { |hook_name| Overcommit::Utils.camel_case(hook_name) }. each do |hook_name| @hash[hook_type][hook_name] ||= {} @hash[hook_type][hook_name]['skip'] = true end end
ruby
def apply_environment!(hook_context, env) skipped_hooks = "#{env['SKIP']} #{env['SKIP_CHECKS']} #{env['SKIP_HOOKS']}".split(/[:, ]/) only_hooks = env.fetch('ONLY') { '' }.split(/[:, ]/) hook_type = hook_context.hook_class_name if only_hooks.any? || skipped_hooks.include?('all') || skipped_hooks.include?('ALL') @hash[hook_type]['ALL']['skip'] = true end only_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }. map { |hook_name| Overcommit::Utils.camel_case(hook_name) }. each do |hook_name| @hash[hook_type][hook_name] ||= {} @hash[hook_type][hook_name]['skip'] = false end skipped_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }. map { |hook_name| Overcommit::Utils.camel_case(hook_name) }. each do |hook_name| @hash[hook_type][hook_name] ||= {} @hash[hook_type][hook_name]['skip'] = true end end
[ "def", "apply_environment!", "(", "hook_context", ",", "env", ")", "skipped_hooks", "=", "\"#{env['SKIP']} #{env['SKIP_CHECKS']} #{env['SKIP_HOOKS']}\"", ".", "split", "(", "/", "/", ")", "only_hooks", "=", "env", ".", "fetch", "(", "'ONLY'", ")", "{", "''", "}", ".", "split", "(", "/", "/", ")", "hook_type", "=", "hook_context", ".", "hook_class_name", "if", "only_hooks", ".", "any?", "||", "skipped_hooks", ".", "include?", "(", "'all'", ")", "||", "skipped_hooks", ".", "include?", "(", "'ALL'", ")", "@hash", "[", "hook_type", "]", "[", "'ALL'", "]", "[", "'skip'", "]", "=", "true", "end", "only_hooks", ".", "select", "{", "|", "hook_name", "|", "hook_exists?", "(", "hook_context", ",", "hook_name", ")", "}", ".", "map", "{", "|", "hook_name", "|", "Overcommit", "::", "Utils", ".", "camel_case", "(", "hook_name", ")", "}", ".", "each", "do", "|", "hook_name", "|", "@hash", "[", "hook_type", "]", "[", "hook_name", "]", "||=", "{", "}", "@hash", "[", "hook_type", "]", "[", "hook_name", "]", "[", "'skip'", "]", "=", "false", "end", "skipped_hooks", ".", "select", "{", "|", "hook_name", "|", "hook_exists?", "(", "hook_context", ",", "hook_name", ")", "}", ".", "map", "{", "|", "hook_name", "|", "Overcommit", "::", "Utils", ".", "camel_case", "(", "hook_name", ")", "}", ".", "each", "do", "|", "hook_name", "|", "@hash", "[", "hook_type", "]", "[", "hook_name", "]", "||=", "{", "}", "@hash", "[", "hook_type", "]", "[", "hook_name", "]", "[", "'skip'", "]", "=", "true", "end", "end" ]
Applies additional configuration settings based on the provided environment variables.
[ "Applies", "additional", "configuration", "settings", "based", "on", "the", "provided", "environment", "variables", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration.rb#L157-L179
11,099
sds/overcommit
lib/overcommit/configuration.rb
Overcommit.Configuration.stored_signature
def stored_signature result = Overcommit::Utils.execute( %w[git config --local --get] + [signature_config_key] ) if result.status == 1 # Key doesn't exist return '' elsif result.status != 0 raise Overcommit::Exceptions::GitConfigError, "Unable to read from local repo git config: #{result.stderr}" end result.stdout.chomp end
ruby
def stored_signature result = Overcommit::Utils.execute( %w[git config --local --get] + [signature_config_key] ) if result.status == 1 # Key doesn't exist return '' elsif result.status != 0 raise Overcommit::Exceptions::GitConfigError, "Unable to read from local repo git config: #{result.stderr}" end result.stdout.chomp end
[ "def", "stored_signature", "result", "=", "Overcommit", "::", "Utils", ".", "execute", "(", "%w[", "git", "config", "--local", "--get", "]", "+", "[", "signature_config_key", "]", ")", "if", "result", ".", "status", "==", "1", "# Key doesn't exist", "return", "''", "elsif", "result", ".", "status", "!=", "0", "raise", "Overcommit", "::", "Exceptions", "::", "GitConfigError", ",", "\"Unable to read from local repo git config: #{result.stderr}\"", "end", "result", ".", "stdout", ".", "chomp", "end" ]
Returns the stored signature of this repo's Overcommit configuration. This is intended to be compared against the current signature of this configuration object. @return [String]
[ "Returns", "the", "stored", "signature", "of", "this", "repo", "s", "Overcommit", "configuration", "." ]
35d60adb41da942178b789560968e3ad030b0ac7
https://github.com/sds/overcommit/blob/35d60adb41da942178b789560968e3ad030b0ac7/lib/overcommit/configuration.rb#L327-L340