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
10,400
rails/rails
activestorage/lib/active_storage/attached/many.rb
ActiveStorage.Attached::Many.attach
def attach(*attachables) if record.persisted? && !record.changed? record.update(name => blobs + attachables.flatten) else record.public_send("#{name}=", blobs + attachables.flatten) end end
ruby
def attach(*attachables) if record.persisted? && !record.changed? record.update(name => blobs + attachables.flatten) else record.public_send("#{name}=", blobs + attachables.flatten) end end
[ "def", "attach", "(", "*", "attachables", ")", "if", "record", ".", "persisted?", "&&", "!", "record", ".", "changed?", "record", ".", "update", "(", "name", "=>", "blobs", "+", "attachables", ".", "flatten", ")", "else", "record", ".", "public_send", "(", "\"#{name}=\"", ",", "blobs", "+", "attachables", ".", "flatten", ")", "end", "end" ]
Attaches one or more +attachables+ to the record. If the record is persisted and unchanged, the attachments are saved to the database immediately. Otherwise, they'll be saved to the DB when the record is next saved. document.images.attach(params[:images]) # Array of ActionDispatch::Http::UploadedFile objects document.images.attach(params[:signed_blob_id]) # Signed reference to blob from direct upload document.images.attach(io: File.open("/path/to/racecar.jpg"), filename: "racecar.jpg", content_type: "image/jpg") document.images.attach([ first_blob, second_blob ])
[ "Attaches", "one", "or", "more", "+", "attachables", "+", "to", "the", "record", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activestorage/lib/active_storage/attached/many.rb#L30-L36
10,401
rails/rails
actionpack/lib/action_dispatch/http/response.rb
ActionDispatch.Response.charset=
def charset=(charset) content_type = parsed_content_type_header.mime_type if false == charset set_content_type content_type, nil else set_content_type content_type, charset || self.class.default_charset end end
ruby
def charset=(charset) content_type = parsed_content_type_header.mime_type if false == charset set_content_type content_type, nil else set_content_type content_type, charset || self.class.default_charset end end
[ "def", "charset", "=", "(", "charset", ")", "content_type", "=", "parsed_content_type_header", ".", "mime_type", "if", "false", "==", "charset", "set_content_type", "content_type", ",", "nil", "else", "set_content_type", "content_type", ",", "charset", "||", "self", ".", "class", ".", "default_charset", "end", "end" ]
Sets the HTTP character set. In case of +nil+ parameter it sets the charset to +default_charset+. response.charset = 'utf-16' # => 'utf-16' response.charset = nil # => 'utf-8'
[ "Sets", "the", "HTTP", "character", "set", ".", "In", "case", "of", "+", "nil", "+", "parameter", "it", "sets", "the", "charset", "to", "+", "default_charset", "+", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_dispatch/http/response.rb#L262-L269
10,402
rails/rails
activesupport/lib/active_support/core_ext/date_and_time/calculations.rb
DateAndTime.Calculations.days_to_week_start
def days_to_week_start(start_day = Date.beginning_of_week) start_day_number = DAYS_INTO_WEEK.fetch(start_day) (wday - start_day_number) % 7 end
ruby
def days_to_week_start(start_day = Date.beginning_of_week) start_day_number = DAYS_INTO_WEEK.fetch(start_day) (wday - start_day_number) % 7 end
[ "def", "days_to_week_start", "(", "start_day", "=", "Date", ".", "beginning_of_week", ")", "start_day_number", "=", "DAYS_INTO_WEEK", ".", "fetch", "(", "start_day", ")", "(", "wday", "-", "start_day_number", ")", "%", "7", "end" ]
Returns the number of days to the start of the week on the given day. Week is assumed to start on +start_day+, default is +Date.beginning_of_week+ or +config.beginning_of_week+ when set.
[ "Returns", "the", "number", "of", "days", "to", "the", "start", "of", "the", "week", "on", "the", "given", "day", ".", "Week", "is", "assumed", "to", "start", "on", "+", "start_day", "+", "default", "is", "+", "Date", ".", "beginning_of_week", "+", "or", "+", "config", ".", "beginning_of_week", "+", "when", "set", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb#L265-L268
10,403
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.remote_send
def remote_send(req, marshalled = false) send_initial_metadata GRPC.logger.debug("sending #{req}, marshalled? #{marshalled}") payload = marshalled ? req : @marshal.call(req) @call.run_batch(SEND_MESSAGE => payload) end
ruby
def remote_send(req, marshalled = false) send_initial_metadata GRPC.logger.debug("sending #{req}, marshalled? #{marshalled}") payload = marshalled ? req : @marshal.call(req) @call.run_batch(SEND_MESSAGE => payload) end
[ "def", "remote_send", "(", "req", ",", "marshalled", "=", "false", ")", "send_initial_metadata", "GRPC", ".", "logger", ".", "debug", "(", "\"sending #{req}, marshalled? #{marshalled}\"", ")", "payload", "=", "marshalled", "?", "req", ":", "@marshal", ".", "call", "(", "req", ")", "@call", ".", "run_batch", "(", "SEND_MESSAGE", "=>", "payload", ")", "end" ]
remote_send sends a request to the remote endpoint. It blocks until the remote endpoint accepts the message. @param req [Object, String] the object to send or it's marshal form. @param marshalled [false, true] indicates if the object is already marshalled.
[ "remote_send", "sends", "a", "request", "to", "the", "remote", "endpoint", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L191-L196
10,404
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.send_status
def send_status(code = OK, details = '', assert_finished = false, metadata: {}) send_initial_metadata ops = { SEND_STATUS_FROM_SERVER => Struct::Status.new(code, details, metadata) } ops[RECV_CLOSE_ON_SERVER] = nil if assert_finished @call.run_batch(ops) set_output_stream_done nil end
ruby
def send_status(code = OK, details = '', assert_finished = false, metadata: {}) send_initial_metadata ops = { SEND_STATUS_FROM_SERVER => Struct::Status.new(code, details, metadata) } ops[RECV_CLOSE_ON_SERVER] = nil if assert_finished @call.run_batch(ops) set_output_stream_done nil end
[ "def", "send_status", "(", "code", "=", "OK", ",", "details", "=", "''", ",", "assert_finished", "=", "false", ",", "metadata", ":", "{", "}", ")", "send_initial_metadata", "ops", "=", "{", "SEND_STATUS_FROM_SERVER", "=>", "Struct", "::", "Status", ".", "new", "(", "code", ",", "details", ",", "metadata", ")", "}", "ops", "[", "RECV_CLOSE_ON_SERVER", "]", "=", "nil", "if", "assert_finished", "@call", ".", "run_batch", "(", "ops", ")", "set_output_stream_done", "nil", "end" ]
send_status sends a status to the remote endpoint. @param code [int] the status code to send @param details [String] details @param assert_finished [true, false] when true(default), waits for FINISHED. @param metadata [Hash] metadata to send to the server. If a value is a list, mulitple metadata for its key are sent
[ "send_status", "sends", "a", "status", "to", "the", "remote", "endpoint", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L206-L217
10,405
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.remote_read
def remote_read ops = { RECV_MESSAGE => nil } ops[RECV_INITIAL_METADATA] = nil unless @metadata_received batch_result = @call.run_batch(ops) unless @metadata_received @call.metadata = batch_result.metadata @metadata_received = true end get_message_from_batch_result(batch_result) end
ruby
def remote_read ops = { RECV_MESSAGE => nil } ops[RECV_INITIAL_METADATA] = nil unless @metadata_received batch_result = @call.run_batch(ops) unless @metadata_received @call.metadata = batch_result.metadata @metadata_received = true end get_message_from_batch_result(batch_result) end
[ "def", "remote_read", "ops", "=", "{", "RECV_MESSAGE", "=>", "nil", "}", "ops", "[", "RECV_INITIAL_METADATA", "]", "=", "nil", "unless", "@metadata_received", "batch_result", "=", "@call", ".", "run_batch", "(", "ops", ")", "unless", "@metadata_received", "@call", ".", "metadata", "=", "batch_result", ".", "metadata", "@metadata_received", "=", "true", "end", "get_message_from_batch_result", "(", "batch_result", ")", "end" ]
remote_read reads a response from the remote endpoint. It blocks until the remote endpoint replies with a message or status. On receiving a message, it returns the response after unmarshalling it. On receiving a status, it returns nil if the status is OK, otherwise raising BadStatus
[ "remote_read", "reads", "a", "response", "from", "the", "remote", "endpoint", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L251-L260
10,406
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.each_remote_read
def each_remote_read return enum_for(:each_remote_read) unless block_given? begin loop do resp = remote_read break if resp.nil? # the last response was received yield resp end ensure set_input_stream_done end end
ruby
def each_remote_read return enum_for(:each_remote_read) unless block_given? begin loop do resp = remote_read break if resp.nil? # the last response was received yield resp end ensure set_input_stream_done end end
[ "def", "each_remote_read", "return", "enum_for", "(", ":each_remote_read", ")", "unless", "block_given?", "begin", "loop", "do", "resp", "=", "remote_read", "break", "if", "resp", ".", "nil?", "# the last response was received", "yield", "resp", "end", "ensure", "set_input_stream_done", "end", "end" ]
each_remote_read passes each response to the given block or returns an enumerator the responses if no block is given. Used to generate the request enumerable for server-side client-streaming RPC's. == Enumerator == * #next blocks until the remote endpoint sends a READ or FINISHED * for each read, enumerator#next yields the response * on status * if it's is OK, enumerator#next raises StopException * if is not OK, enumerator#next raises RuntimeException == Block == * if provided it is executed for each response * the call blocks until no more responses are provided @return [Enumerator] if no block was given
[ "each_remote_read", "passes", "each", "response", "to", "the", "given", "block", "or", "returns", "an", "enumerator", "the", "responses", "if", "no", "block", "is", "given", ".", "Used", "to", "generate", "the", "request", "enumerable", "for", "server", "-", "side", "client", "-", "streaming", "RPC", "s", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L290-L301
10,407
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.each_remote_read_then_finish
def each_remote_read_then_finish return enum_for(:each_remote_read_then_finish) unless block_given? loop do resp = begin remote_read rescue GRPC::Core::CallError => e GRPC.logger.warn("In each_remote_read_then_finish: #{e}") nil end break if resp.nil? # the last response was received yield resp end receive_and_check_status ensure set_input_stream_done end
ruby
def each_remote_read_then_finish return enum_for(:each_remote_read_then_finish) unless block_given? loop do resp = begin remote_read rescue GRPC::Core::CallError => e GRPC.logger.warn("In each_remote_read_then_finish: #{e}") nil end break if resp.nil? # the last response was received yield resp end receive_and_check_status ensure set_input_stream_done end
[ "def", "each_remote_read_then_finish", "return", "enum_for", "(", ":each_remote_read_then_finish", ")", "unless", "block_given?", "loop", "do", "resp", "=", "begin", "remote_read", "rescue", "GRPC", "::", "Core", "::", "CallError", "=>", "e", "GRPC", ".", "logger", ".", "warn", "(", "\"In each_remote_read_then_finish: #{e}\"", ")", "nil", "end", "break", "if", "resp", ".", "nil?", "# the last response was received", "yield", "resp", "end", "receive_and_check_status", "ensure", "set_input_stream_done", "end" ]
each_remote_read_then_finish passes each response to the given block or returns an enumerator of the responses if no block is given. It is like each_remote_read, but it blocks on finishing on detecting the final message. == Enumerator == * #next blocks until the remote endpoint sends a READ or FINISHED * for each read, enumerator#next yields the response * on status * if it's is OK, enumerator#next raises StopException * if is not OK, enumerator#next raises RuntimeException == Block == * if provided it is executed for each response * the call blocks until no more responses are provided @return [Enumerator] if no block was given
[ "each_remote_read_then_finish", "passes", "each", "response", "to", "the", "given", "block", "or", "returns", "an", "enumerator", "of", "the", "responses", "if", "no", "block", "is", "given", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L323-L341
10,408
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.request_response
def request_response(req, metadata: {}) raise_error_if_already_executed ops = { SEND_MESSAGE => @marshal.call(req), SEND_CLOSE_FROM_CLIENT => nil, RECV_INITIAL_METADATA => nil, RECV_MESSAGE => nil, RECV_STATUS_ON_CLIENT => nil } @send_initial_md_mutex.synchronize do # Metadata might have already been sent if this is an operation view unless @metadata_sent ops[SEND_INITIAL_METADATA] = @metadata_to_send.merge!(metadata) end @metadata_sent = true end begin batch_result = @call.run_batch(ops) # no need to check for cancellation after a CallError because this # batch contains a RECV_STATUS op ensure set_input_stream_done set_output_stream_done end @call.metadata = batch_result.metadata attach_status_results_and_complete_call(batch_result) get_message_from_batch_result(batch_result) end
ruby
def request_response(req, metadata: {}) raise_error_if_already_executed ops = { SEND_MESSAGE => @marshal.call(req), SEND_CLOSE_FROM_CLIENT => nil, RECV_INITIAL_METADATA => nil, RECV_MESSAGE => nil, RECV_STATUS_ON_CLIENT => nil } @send_initial_md_mutex.synchronize do # Metadata might have already been sent if this is an operation view unless @metadata_sent ops[SEND_INITIAL_METADATA] = @metadata_to_send.merge!(metadata) end @metadata_sent = true end begin batch_result = @call.run_batch(ops) # no need to check for cancellation after a CallError because this # batch contains a RECV_STATUS op ensure set_input_stream_done set_output_stream_done end @call.metadata = batch_result.metadata attach_status_results_and_complete_call(batch_result) get_message_from_batch_result(batch_result) end
[ "def", "request_response", "(", "req", ",", "metadata", ":", "{", "}", ")", "raise_error_if_already_executed", "ops", "=", "{", "SEND_MESSAGE", "=>", "@marshal", ".", "call", "(", "req", ")", ",", "SEND_CLOSE_FROM_CLIENT", "=>", "nil", ",", "RECV_INITIAL_METADATA", "=>", "nil", ",", "RECV_MESSAGE", "=>", "nil", ",", "RECV_STATUS_ON_CLIENT", "=>", "nil", "}", "@send_initial_md_mutex", ".", "synchronize", "do", "# Metadata might have already been sent if this is an operation view", "unless", "@metadata_sent", "ops", "[", "SEND_INITIAL_METADATA", "]", "=", "@metadata_to_send", ".", "merge!", "(", "metadata", ")", "end", "@metadata_sent", "=", "true", "end", "begin", "batch_result", "=", "@call", ".", "run_batch", "(", "ops", ")", "# no need to check for cancellation after a CallError because this", "# batch contains a RECV_STATUS op", "ensure", "set_input_stream_done", "set_output_stream_done", "end", "@call", ".", "metadata", "=", "batch_result", ".", "metadata", "attach_status_results_and_complete_call", "(", "batch_result", ")", "get_message_from_batch_result", "(", "batch_result", ")", "end" ]
request_response sends a request to a GRPC server, and returns the response. @param req [Object] the request sent to the server @param metadata [Hash] metadata to be sent to the server. If a value is a list, multiple metadata for its key are sent @return [Object] the response received from the server
[ "request_response", "sends", "a", "request", "to", "a", "GRPC", "server", "and", "returns", "the", "response", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L350-L379
10,409
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.client_streamer
def client_streamer(requests, metadata: {}) raise_error_if_already_executed begin send_initial_metadata(metadata) requests.each { |r| @call.run_batch(SEND_MESSAGE => @marshal.call(r)) } rescue GRPC::Core::CallError => e receive_and_check_status # check for Cancelled raise e rescue => e set_input_stream_done raise e ensure set_output_stream_done end batch_result = @call.run_batch( SEND_CLOSE_FROM_CLIENT => nil, RECV_INITIAL_METADATA => nil, RECV_MESSAGE => nil, RECV_STATUS_ON_CLIENT => nil ) set_input_stream_done @call.metadata = batch_result.metadata attach_status_results_and_complete_call(batch_result) get_message_from_batch_result(batch_result) end
ruby
def client_streamer(requests, metadata: {}) raise_error_if_already_executed begin send_initial_metadata(metadata) requests.each { |r| @call.run_batch(SEND_MESSAGE => @marshal.call(r)) } rescue GRPC::Core::CallError => e receive_and_check_status # check for Cancelled raise e rescue => e set_input_stream_done raise e ensure set_output_stream_done end batch_result = @call.run_batch( SEND_CLOSE_FROM_CLIENT => nil, RECV_INITIAL_METADATA => nil, RECV_MESSAGE => nil, RECV_STATUS_ON_CLIENT => nil ) set_input_stream_done @call.metadata = batch_result.metadata attach_status_results_and_complete_call(batch_result) get_message_from_batch_result(batch_result) end
[ "def", "client_streamer", "(", "requests", ",", "metadata", ":", "{", "}", ")", "raise_error_if_already_executed", "begin", "send_initial_metadata", "(", "metadata", ")", "requests", ".", "each", "{", "|", "r", "|", "@call", ".", "run_batch", "(", "SEND_MESSAGE", "=>", "@marshal", ".", "call", "(", "r", ")", ")", "}", "rescue", "GRPC", "::", "Core", "::", "CallError", "=>", "e", "receive_and_check_status", "# check for Cancelled", "raise", "e", "rescue", "=>", "e", "set_input_stream_done", "raise", "e", "ensure", "set_output_stream_done", "end", "batch_result", "=", "@call", ".", "run_batch", "(", "SEND_CLOSE_FROM_CLIENT", "=>", "nil", ",", "RECV_INITIAL_METADATA", "=>", "nil", ",", "RECV_MESSAGE", "=>", "nil", ",", "RECV_STATUS_ON_CLIENT", "=>", "nil", ")", "set_input_stream_done", "@call", ".", "metadata", "=", "batch_result", ".", "metadata", "attach_status_results_and_complete_call", "(", "batch_result", ")", "get_message_from_batch_result", "(", "batch_result", ")", "end" ]
client_streamer sends a stream of requests to a GRPC server, and returns a single response. requests provides an 'iterable' of Requests. I.e. it follows Ruby's #each enumeration protocol. In the simplest case, requests will be an array of marshallable objects; in typical case it will be an Enumerable that allows dynamic construction of the marshallable objects. @param requests [Object] an Enumerable of requests to send @param metadata [Hash] metadata to be sent to the server. If a value is a list, multiple metadata for its key are sent @return [Object] the response received from the server
[ "client_streamer", "sends", "a", "stream", "of", "requests", "to", "a", "GRPC", "server", "and", "returns", "a", "single", "response", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L393-L420
10,410
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.server_streamer
def server_streamer(req, metadata: {}) raise_error_if_already_executed ops = { SEND_MESSAGE => @marshal.call(req), SEND_CLOSE_FROM_CLIENT => nil } @send_initial_md_mutex.synchronize do # Metadata might have already been sent if this is an operation view unless @metadata_sent ops[SEND_INITIAL_METADATA] = @metadata_to_send.merge!(metadata) end @metadata_sent = true end begin @call.run_batch(ops) rescue GRPC::Core::CallError => e receive_and_check_status # checks for Cancelled raise e rescue => e set_input_stream_done raise e ensure set_output_stream_done end replies = enum_for(:each_remote_read_then_finish) return replies unless block_given? replies.each { |r| yield r } end
ruby
def server_streamer(req, metadata: {}) raise_error_if_already_executed ops = { SEND_MESSAGE => @marshal.call(req), SEND_CLOSE_FROM_CLIENT => nil } @send_initial_md_mutex.synchronize do # Metadata might have already been sent if this is an operation view unless @metadata_sent ops[SEND_INITIAL_METADATA] = @metadata_to_send.merge!(metadata) end @metadata_sent = true end begin @call.run_batch(ops) rescue GRPC::Core::CallError => e receive_and_check_status # checks for Cancelled raise e rescue => e set_input_stream_done raise e ensure set_output_stream_done end replies = enum_for(:each_remote_read_then_finish) return replies unless block_given? replies.each { |r| yield r } end
[ "def", "server_streamer", "(", "req", ",", "metadata", ":", "{", "}", ")", "raise_error_if_already_executed", "ops", "=", "{", "SEND_MESSAGE", "=>", "@marshal", ".", "call", "(", "req", ")", ",", "SEND_CLOSE_FROM_CLIENT", "=>", "nil", "}", "@send_initial_md_mutex", ".", "synchronize", "do", "# Metadata might have already been sent if this is an operation view", "unless", "@metadata_sent", "ops", "[", "SEND_INITIAL_METADATA", "]", "=", "@metadata_to_send", ".", "merge!", "(", "metadata", ")", "end", "@metadata_sent", "=", "true", "end", "begin", "@call", ".", "run_batch", "(", "ops", ")", "rescue", "GRPC", "::", "Core", "::", "CallError", "=>", "e", "receive_and_check_status", "# checks for Cancelled", "raise", "e", "rescue", "=>", "e", "set_input_stream_done", "raise", "e", "ensure", "set_output_stream_done", "end", "replies", "=", "enum_for", "(", ":each_remote_read_then_finish", ")", "return", "replies", "unless", "block_given?", "replies", ".", "each", "{", "|", "r", "|", "yield", "r", "}", "end" ]
server_streamer sends one request to the GRPC server, which yields a stream of responses. responses provides an enumerator over the streamed responses, i.e. it follows Ruby's #each iteration protocol. The enumerator blocks while waiting for each response, stops when the server signals that no further responses will be supplied. If the implicit block is provided, it is executed with each response as the argument and no result is returned. @param req [Object] the request sent to the server @param metadata [Hash] metadata to be sent to the server. If a value is a list, multiple metadata for its key are sent @return [Enumerator|nil] a response Enumerator
[ "server_streamer", "sends", "one", "request", "to", "the", "GRPC", "server", "which", "yields", "a", "stream", "of", "responses", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L436-L465
10,411
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.bidi_streamer
def bidi_streamer(requests, metadata: {}, &blk) raise_error_if_already_executed # Metadata might have already been sent if this is an operation view begin send_initial_metadata(metadata) rescue GRPC::Core::CallError => e batch_result = @call.run_batch(RECV_STATUS_ON_CLIENT => nil) set_input_stream_done set_output_stream_done attach_status_results_and_complete_call(batch_result) raise e rescue => e set_input_stream_done set_output_stream_done raise e end bd = BidiCall.new(@call, @marshal, @unmarshal, metadata_received: @metadata_received) bd.run_on_client(requests, proc { set_input_stream_done }, proc { set_output_stream_done }, &blk) end
ruby
def bidi_streamer(requests, metadata: {}, &blk) raise_error_if_already_executed # Metadata might have already been sent if this is an operation view begin send_initial_metadata(metadata) rescue GRPC::Core::CallError => e batch_result = @call.run_batch(RECV_STATUS_ON_CLIENT => nil) set_input_stream_done set_output_stream_done attach_status_results_and_complete_call(batch_result) raise e rescue => e set_input_stream_done set_output_stream_done raise e end bd = BidiCall.new(@call, @marshal, @unmarshal, metadata_received: @metadata_received) bd.run_on_client(requests, proc { set_input_stream_done }, proc { set_output_stream_done }, &blk) end
[ "def", "bidi_streamer", "(", "requests", ",", "metadata", ":", "{", "}", ",", "&", "blk", ")", "raise_error_if_already_executed", "# Metadata might have already been sent if this is an operation view", "begin", "send_initial_metadata", "(", "metadata", ")", "rescue", "GRPC", "::", "Core", "::", "CallError", "=>", "e", "batch_result", "=", "@call", ".", "run_batch", "(", "RECV_STATUS_ON_CLIENT", "=>", "nil", ")", "set_input_stream_done", "set_output_stream_done", "attach_status_results_and_complete_call", "(", "batch_result", ")", "raise", "e", "rescue", "=>", "e", "set_input_stream_done", "set_output_stream_done", "raise", "e", "end", "bd", "=", "BidiCall", ".", "new", "(", "@call", ",", "@marshal", ",", "@unmarshal", ",", "metadata_received", ":", "@metadata_received", ")", "bd", ".", "run_on_client", "(", "requests", ",", "proc", "{", "set_input_stream_done", "}", ",", "proc", "{", "set_output_stream_done", "}", ",", "blk", ")", "end" ]
bidi_streamer sends a stream of requests to the GRPC server, and yields a stream of responses. This method takes an Enumerable of requests, and returns and enumerable of responses. == requests == requests provides an 'iterable' of Requests. I.e. it follows Ruby's #each enumeration protocol. In the simplest case, requests will be an array of marshallable objects; in typical case it will be an Enumerable that allows dynamic construction of the marshallable objects. == responses == This is an enumerator of responses. I.e, its #next method blocks waiting for the next response. Also, if at any point the block needs to consume all the remaining responses, this can be done using #each or #collect. Calling #each or #collect should only be done if the_call#writes_done has been called, otherwise the block will loop forever. @param requests [Object] an Enumerable of requests to send @param metadata [Hash] metadata to be sent to the server. If a value is a list, multiple metadata for its key are sent @return [Enumerator, nil] a response Enumerator
[ "bidi_streamer", "sends", "a", "stream", "of", "requests", "to", "the", "GRPC", "server", "and", "yields", "a", "stream", "of", "responses", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L494-L520
10,412
grpc/grpc
src/ruby/lib/grpc/generic/active_call.rb
GRPC.ActiveCall.run_server_bidi
def run_server_bidi(mth, interception_ctx) view = multi_req_view bidi_call = BidiCall.new( @call, @marshal, @unmarshal, metadata_received: @metadata_received, req_view: view ) requests = bidi_call.read_next_loop(proc { set_input_stream_done }, false) interception_ctx.intercept!( :bidi_streamer, call: view, method: mth, requests: requests ) do bidi_call.run_on_server(mth, requests) end end
ruby
def run_server_bidi(mth, interception_ctx) view = multi_req_view bidi_call = BidiCall.new( @call, @marshal, @unmarshal, metadata_received: @metadata_received, req_view: view ) requests = bidi_call.read_next_loop(proc { set_input_stream_done }, false) interception_ctx.intercept!( :bidi_streamer, call: view, method: mth, requests: requests ) do bidi_call.run_on_server(mth, requests) end end
[ "def", "run_server_bidi", "(", "mth", ",", "interception_ctx", ")", "view", "=", "multi_req_view", "bidi_call", "=", "BidiCall", ".", "new", "(", "@call", ",", "@marshal", ",", "@unmarshal", ",", "metadata_received", ":", "@metadata_received", ",", "req_view", ":", "view", ")", "requests", "=", "bidi_call", ".", "read_next_loop", "(", "proc", "{", "set_input_stream_done", "}", ",", "false", ")", "interception_ctx", ".", "intercept!", "(", ":bidi_streamer", ",", "call", ":", "view", ",", "method", ":", "mth", ",", "requests", ":", "requests", ")", "do", "bidi_call", ".", "run_on_server", "(", "mth", ",", "requests", ")", "end", "end" ]
run_server_bidi orchestrates a BiDi stream processing on a server. N.B. gen_each_reply is a func(Enumerable<Requests>) It takes an enumerable of requests as an arg, in case there is a relationship between the stream of requests and the stream of replies. This does not mean that must necessarily be one. E.g, the replies produced by gen_each_reply could ignore the received_msgs @param mth [Proc] generates the BiDi stream replies @param interception_ctx [InterceptionContext]
[ "run_server_bidi", "orchestrates", "a", "BiDi", "stream", "processing", "on", "a", "server", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/active_call.rb#L535-L553
10,413
grpc/grpc
src/ruby/lib/grpc/generic/bidi_call.rb
GRPC.BidiCall.run_on_client
def run_on_client(requests, set_input_stream_done, set_output_stream_done, &blk) @enq_th = Thread.new do write_loop(requests, set_output_stream_done: set_output_stream_done) end read_loop(set_input_stream_done, &blk) end
ruby
def run_on_client(requests, set_input_stream_done, set_output_stream_done, &blk) @enq_th = Thread.new do write_loop(requests, set_output_stream_done: set_output_stream_done) end read_loop(set_input_stream_done, &blk) end
[ "def", "run_on_client", "(", "requests", ",", "set_input_stream_done", ",", "set_output_stream_done", ",", "&", "blk", ")", "@enq_th", "=", "Thread", ".", "new", "do", "write_loop", "(", "requests", ",", "set_output_stream_done", ":", "set_output_stream_done", ")", "end", "read_loop", "(", "set_input_stream_done", ",", "blk", ")", "end" ]
Creates a BidiCall. BidiCall should only be created after a call is accepted. That means different things on a client and a server. On the client, the call is accepted after call.invoke. On the server, this is after call.accept. #initialize cannot determine if the call is accepted or not; so if a call that's not accepted is used here, the error won't be visible until the BidiCall#run is called. deadline is the absolute deadline for the call. @param call [Call] the call used by the ActiveCall @param marshal [Function] f(obj)->string that marshal requests @param unmarshal [Function] f(string)->obj that unmarshals responses @param metadata_received [true|false] indicates if metadata has already been received. Should always be true for server calls Begins orchestration of the Bidi stream for a client sending requests. The method either returns an Enumerator of the responses, or accepts a block that can be invoked with each response. @param requests the Enumerable of requests to send @param set_input_stream_done [Proc] called back when we're done reading the input stream @param set_output_stream_done [Proc] called back when we're done sending data on the output stream @return an Enumerator of requests to yield
[ "Creates", "a", "BidiCall", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/bidi_call.rb#L70-L78
10,414
grpc/grpc
src/ruby/lib/grpc/generic/bidi_call.rb
GRPC.BidiCall.run_on_server
def run_on_server(gen_each_reply, requests) replies = nil # Pass in the optional call object parameter if possible if gen_each_reply.arity == 1 replies = gen_each_reply.call(requests) elsif gen_each_reply.arity == 2 replies = gen_each_reply.call(requests, @req_view) else fail 'Illegal arity of reply generator' end write_loop(replies, is_client: false) end
ruby
def run_on_server(gen_each_reply, requests) replies = nil # Pass in the optional call object parameter if possible if gen_each_reply.arity == 1 replies = gen_each_reply.call(requests) elsif gen_each_reply.arity == 2 replies = gen_each_reply.call(requests, @req_view) else fail 'Illegal arity of reply generator' end write_loop(replies, is_client: false) end
[ "def", "run_on_server", "(", "gen_each_reply", ",", "requests", ")", "replies", "=", "nil", "# Pass in the optional call object parameter if possible", "if", "gen_each_reply", ".", "arity", "==", "1", "replies", "=", "gen_each_reply", ".", "call", "(", "requests", ")", "elsif", "gen_each_reply", ".", "arity", "==", "2", "replies", "=", "gen_each_reply", ".", "call", "(", "requests", ",", "@req_view", ")", "else", "fail", "'Illegal arity of reply generator'", "end", "write_loop", "(", "replies", ",", "is_client", ":", "false", ")", "end" ]
Begins orchestration of the Bidi stream for a server generating replies. N.B. gen_each_reply is a func(Enumerable<Requests>) It takes an enumerable of requests as an arg, in case there is a relationship between the stream of requests and the stream of replies. This does not mean that must necessarily be one. E.g, the replies produced by gen_each_reply could ignore the received_msgs @param [Proc] gen_each_reply generates the BiDi stream replies. @param [Enumerable] requests The enumerable of requests to run
[ "Begins", "orchestration", "of", "the", "Bidi", "stream", "for", "a", "server", "generating", "replies", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/bidi_call.rb#L92-L105
10,415
grpc/grpc
src/ruby/lib/grpc/generic/bidi_call.rb
GRPC.BidiCall.read_using_run_batch
def read_using_run_batch ops = { RECV_MESSAGE => nil } ops[RECV_INITIAL_METADATA] = nil unless @metadata_received begin batch_result = @call.run_batch(ops) unless @metadata_received @call.metadata = batch_result.metadata @metadata_received = true end batch_result rescue GRPC::Core::CallError => e GRPC.logger.warn('bidi call: read_using_run_batch failed') GRPC.logger.warn(e) nil end end
ruby
def read_using_run_batch ops = { RECV_MESSAGE => nil } ops[RECV_INITIAL_METADATA] = nil unless @metadata_received begin batch_result = @call.run_batch(ops) unless @metadata_received @call.metadata = batch_result.metadata @metadata_received = true end batch_result rescue GRPC::Core::CallError => e GRPC.logger.warn('bidi call: read_using_run_batch failed') GRPC.logger.warn(e) nil end end
[ "def", "read_using_run_batch", "ops", "=", "{", "RECV_MESSAGE", "=>", "nil", "}", "ops", "[", "RECV_INITIAL_METADATA", "]", "=", "nil", "unless", "@metadata_received", "begin", "batch_result", "=", "@call", ".", "run_batch", "(", "ops", ")", "unless", "@metadata_received", "@call", ".", "metadata", "=", "batch_result", ".", "metadata", "@metadata_received", "=", "true", "end", "batch_result", "rescue", "GRPC", "::", "Core", "::", "CallError", "=>", "e", "GRPC", ".", "logger", ".", "warn", "(", "'bidi call: read_using_run_batch failed'", ")", "GRPC", ".", "logger", ".", "warn", "(", "e", ")", "nil", "end", "end" ]
performs a read using @call.run_batch, ensures metadata is set up
[ "performs", "a", "read", "using" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/bidi_call.rb#L124-L139
10,416
grpc/grpc
src/ruby/lib/grpc/generic/bidi_call.rb
GRPC.BidiCall.write_loop
def write_loop(requests, is_client: true, set_output_stream_done: nil) GRPC.logger.debug('bidi-write-loop: starting') count = 0 requests.each do |req| GRPC.logger.debug("bidi-write-loop: #{count}") count += 1 payload = @marshal.call(req) # Fails if status already received begin @req_view.send_initial_metadata unless @req_view.nil? @call.run_batch(SEND_MESSAGE => payload) rescue GRPC::Core::CallError => e # This is almost definitely caused by a status arriving while still # writing. Don't re-throw the error GRPC.logger.warn('bidi-write-loop: ended with error') GRPC.logger.warn(e) break end end GRPC.logger.debug("bidi-write-loop: #{count} writes done") if is_client GRPC.logger.debug("bidi-write-loop: client sent #{count}, waiting") begin @call.run_batch(SEND_CLOSE_FROM_CLIENT => nil) rescue GRPC::Core::CallError => e GRPC.logger.warn('bidi-write-loop: send close failed') GRPC.logger.warn(e) end GRPC.logger.debug('bidi-write-loop: done') end GRPC.logger.debug('bidi-write-loop: finished') rescue StandardError => e GRPC.logger.warn('bidi-write-loop: failed') GRPC.logger.warn(e) if is_client @call.cancel_with_status(GRPC::Core::StatusCodes::UNKNOWN, "GRPC bidi call error: #{e.inspect}") else raise e end ensure set_output_stream_done.call if is_client end
ruby
def write_loop(requests, is_client: true, set_output_stream_done: nil) GRPC.logger.debug('bidi-write-loop: starting') count = 0 requests.each do |req| GRPC.logger.debug("bidi-write-loop: #{count}") count += 1 payload = @marshal.call(req) # Fails if status already received begin @req_view.send_initial_metadata unless @req_view.nil? @call.run_batch(SEND_MESSAGE => payload) rescue GRPC::Core::CallError => e # This is almost definitely caused by a status arriving while still # writing. Don't re-throw the error GRPC.logger.warn('bidi-write-loop: ended with error') GRPC.logger.warn(e) break end end GRPC.logger.debug("bidi-write-loop: #{count} writes done") if is_client GRPC.logger.debug("bidi-write-loop: client sent #{count}, waiting") begin @call.run_batch(SEND_CLOSE_FROM_CLIENT => nil) rescue GRPC::Core::CallError => e GRPC.logger.warn('bidi-write-loop: send close failed') GRPC.logger.warn(e) end GRPC.logger.debug('bidi-write-loop: done') end GRPC.logger.debug('bidi-write-loop: finished') rescue StandardError => e GRPC.logger.warn('bidi-write-loop: failed') GRPC.logger.warn(e) if is_client @call.cancel_with_status(GRPC::Core::StatusCodes::UNKNOWN, "GRPC bidi call error: #{e.inspect}") else raise e end ensure set_output_stream_done.call if is_client end
[ "def", "write_loop", "(", "requests", ",", "is_client", ":", "true", ",", "set_output_stream_done", ":", "nil", ")", "GRPC", ".", "logger", ".", "debug", "(", "'bidi-write-loop: starting'", ")", "count", "=", "0", "requests", ".", "each", "do", "|", "req", "|", "GRPC", ".", "logger", ".", "debug", "(", "\"bidi-write-loop: #{count}\"", ")", "count", "+=", "1", "payload", "=", "@marshal", ".", "call", "(", "req", ")", "# Fails if status already received", "begin", "@req_view", ".", "send_initial_metadata", "unless", "@req_view", ".", "nil?", "@call", ".", "run_batch", "(", "SEND_MESSAGE", "=>", "payload", ")", "rescue", "GRPC", "::", "Core", "::", "CallError", "=>", "e", "# This is almost definitely caused by a status arriving while still", "# writing. Don't re-throw the error", "GRPC", ".", "logger", ".", "warn", "(", "'bidi-write-loop: ended with error'", ")", "GRPC", ".", "logger", ".", "warn", "(", "e", ")", "break", "end", "end", "GRPC", ".", "logger", ".", "debug", "(", "\"bidi-write-loop: #{count} writes done\"", ")", "if", "is_client", "GRPC", ".", "logger", ".", "debug", "(", "\"bidi-write-loop: client sent #{count}, waiting\"", ")", "begin", "@call", ".", "run_batch", "(", "SEND_CLOSE_FROM_CLIENT", "=>", "nil", ")", "rescue", "GRPC", "::", "Core", "::", "CallError", "=>", "e", "GRPC", ".", "logger", ".", "warn", "(", "'bidi-write-loop: send close failed'", ")", "GRPC", ".", "logger", ".", "warn", "(", "e", ")", "end", "GRPC", ".", "logger", ".", "debug", "(", "'bidi-write-loop: done'", ")", "end", "GRPC", ".", "logger", ".", "debug", "(", "'bidi-write-loop: finished'", ")", "rescue", "StandardError", "=>", "e", "GRPC", ".", "logger", ".", "warn", "(", "'bidi-write-loop: failed'", ")", "GRPC", ".", "logger", ".", "warn", "(", "e", ")", "if", "is_client", "@call", ".", "cancel_with_status", "(", "GRPC", "::", "Core", "::", "StatusCodes", "::", "UNKNOWN", ",", "\"GRPC bidi call error: #{e.inspect}\"", ")", "else", "raise", "e", "end", "ensure", "set_output_stream_done", ".", "call", "if", "is_client", "end" ]
set_output_stream_done is relevant on client-side
[ "set_output_stream_done", "is", "relevant", "on", "client", "-", "side" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/bidi_call.rb#L142-L184
10,417
grpc/grpc
src/ruby/lib/grpc/generic/bidi_call.rb
GRPC.BidiCall.read_loop
def read_loop(set_input_stream_done, is_client: true) return enum_for(:read_loop, set_input_stream_done, is_client: is_client) unless block_given? GRPC.logger.debug('bidi-read-loop: starting') begin count = 0 # queue the initial read before beginning the loop loop do GRPC.logger.debug("bidi-read-loop: #{count}") count += 1 batch_result = read_using_run_batch # handle the next message if batch_result.nil? || batch_result.message.nil? GRPC.logger.debug("bidi-read-loop: null batch #{batch_result}") if is_client batch_result = @call.run_batch(RECV_STATUS_ON_CLIENT => nil) @call.status = batch_result.status @call.trailing_metadata = @call.status.metadata if @call.status GRPC.logger.debug("bidi-read-loop: done status #{@call.status}") batch_result.check_status end GRPC.logger.debug('bidi-read-loop: done reading!') break end res = @unmarshal.call(batch_result.message) yield res end rescue StandardError => e GRPC.logger.warn('bidi: read-loop failed') GRPC.logger.warn(e) raise e ensure set_input_stream_done.call end GRPC.logger.debug('bidi-read-loop: finished') # Make sure that the write loop is done before finishing the call. # Note that blocking is ok at this point because we've already received # a status @enq_th.join if is_client end
ruby
def read_loop(set_input_stream_done, is_client: true) return enum_for(:read_loop, set_input_stream_done, is_client: is_client) unless block_given? GRPC.logger.debug('bidi-read-loop: starting') begin count = 0 # queue the initial read before beginning the loop loop do GRPC.logger.debug("bidi-read-loop: #{count}") count += 1 batch_result = read_using_run_batch # handle the next message if batch_result.nil? || batch_result.message.nil? GRPC.logger.debug("bidi-read-loop: null batch #{batch_result}") if is_client batch_result = @call.run_batch(RECV_STATUS_ON_CLIENT => nil) @call.status = batch_result.status @call.trailing_metadata = @call.status.metadata if @call.status GRPC.logger.debug("bidi-read-loop: done status #{@call.status}") batch_result.check_status end GRPC.logger.debug('bidi-read-loop: done reading!') break end res = @unmarshal.call(batch_result.message) yield res end rescue StandardError => e GRPC.logger.warn('bidi: read-loop failed') GRPC.logger.warn(e) raise e ensure set_input_stream_done.call end GRPC.logger.debug('bidi-read-loop: finished') # Make sure that the write loop is done before finishing the call. # Note that blocking is ok at this point because we've already received # a status @enq_th.join if is_client end
[ "def", "read_loop", "(", "set_input_stream_done", ",", "is_client", ":", "true", ")", "return", "enum_for", "(", ":read_loop", ",", "set_input_stream_done", ",", "is_client", ":", "is_client", ")", "unless", "block_given?", "GRPC", ".", "logger", ".", "debug", "(", "'bidi-read-loop: starting'", ")", "begin", "count", "=", "0", "# queue the initial read before beginning the loop", "loop", "do", "GRPC", ".", "logger", ".", "debug", "(", "\"bidi-read-loop: #{count}\"", ")", "count", "+=", "1", "batch_result", "=", "read_using_run_batch", "# handle the next message", "if", "batch_result", ".", "nil?", "||", "batch_result", ".", "message", ".", "nil?", "GRPC", ".", "logger", ".", "debug", "(", "\"bidi-read-loop: null batch #{batch_result}\"", ")", "if", "is_client", "batch_result", "=", "@call", ".", "run_batch", "(", "RECV_STATUS_ON_CLIENT", "=>", "nil", ")", "@call", ".", "status", "=", "batch_result", ".", "status", "@call", ".", "trailing_metadata", "=", "@call", ".", "status", ".", "metadata", "if", "@call", ".", "status", "GRPC", ".", "logger", ".", "debug", "(", "\"bidi-read-loop: done status #{@call.status}\"", ")", "batch_result", ".", "check_status", "end", "GRPC", ".", "logger", ".", "debug", "(", "'bidi-read-loop: done reading!'", ")", "break", "end", "res", "=", "@unmarshal", ".", "call", "(", "batch_result", ".", "message", ")", "yield", "res", "end", "rescue", "StandardError", "=>", "e", "GRPC", ".", "logger", ".", "warn", "(", "'bidi: read-loop failed'", ")", "GRPC", ".", "logger", ".", "warn", "(", "e", ")", "raise", "e", "ensure", "set_input_stream_done", ".", "call", "end", "GRPC", ".", "logger", ".", "debug", "(", "'bidi-read-loop: finished'", ")", "# Make sure that the write loop is done before finishing the call.", "# Note that blocking is ok at this point because we've already received", "# a status", "@enq_th", ".", "join", "if", "is_client", "end" ]
Provides an enumerator that yields results of remote reads
[ "Provides", "an", "enumerator", "that", "yields", "results", "of", "remote", "reads" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/bidi_call.rb#L187-L231
10,418
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.Pool.schedule
def schedule(*args, &blk) return if blk.nil? @stop_mutex.synchronize do if @stopped GRPC.logger.warn('did not schedule job, already stopped') return end GRPC.logger.info('schedule another job') fail 'No worker threads available' if @ready_workers.empty? worker_queue = @ready_workers.pop fail 'worker already has a task waiting' unless worker_queue.empty? worker_queue << [blk, args] end end
ruby
def schedule(*args, &blk) return if blk.nil? @stop_mutex.synchronize do if @stopped GRPC.logger.warn('did not schedule job, already stopped') return end GRPC.logger.info('schedule another job') fail 'No worker threads available' if @ready_workers.empty? worker_queue = @ready_workers.pop fail 'worker already has a task waiting' unless worker_queue.empty? worker_queue << [blk, args] end end
[ "def", "schedule", "(", "*", "args", ",", "&", "blk", ")", "return", "if", "blk", ".", "nil?", "@stop_mutex", ".", "synchronize", "do", "if", "@stopped", "GRPC", ".", "logger", ".", "warn", "(", "'did not schedule job, already stopped'", ")", "return", "end", "GRPC", ".", "logger", ".", "info", "(", "'schedule another job'", ")", "fail", "'No worker threads available'", "if", "@ready_workers", ".", "empty?", "worker_queue", "=", "@ready_workers", ".", "pop", "fail", "'worker already has a task waiting'", "unless", "worker_queue", ".", "empty?", "worker_queue", "<<", "[", "blk", ",", "args", "]", "end", "end" ]
Runs the given block on the queue with the provided args. @param args the args passed blk when it is called @param blk the block to call
[ "Runs", "the", "given", "block", "on", "the", "queue", "with", "the", "provided", "args", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L58-L72
10,419
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.Pool.start
def start @stop_mutex.synchronize do fail 'already stopped' if @stopped end until @workers.size == @size.to_i new_worker_queue = Queue.new @ready_workers << new_worker_queue next_thread = Thread.new(new_worker_queue) do |jobs| catch(:exit) do # allows { throw :exit } to kill a thread loop_execute_jobs(jobs) end remove_current_thread end @workers << next_thread end end
ruby
def start @stop_mutex.synchronize do fail 'already stopped' if @stopped end until @workers.size == @size.to_i new_worker_queue = Queue.new @ready_workers << new_worker_queue next_thread = Thread.new(new_worker_queue) do |jobs| catch(:exit) do # allows { throw :exit } to kill a thread loop_execute_jobs(jobs) end remove_current_thread end @workers << next_thread end end
[ "def", "start", "@stop_mutex", ".", "synchronize", "do", "fail", "'already stopped'", "if", "@stopped", "end", "until", "@workers", ".", "size", "==", "@size", ".", "to_i", "new_worker_queue", "=", "Queue", ".", "new", "@ready_workers", "<<", "new_worker_queue", "next_thread", "=", "Thread", ".", "new", "(", "new_worker_queue", ")", "do", "|", "jobs", "|", "catch", "(", ":exit", ")", "do", "# allows { throw :exit } to kill a thread", "loop_execute_jobs", "(", "jobs", ")", "end", "remove_current_thread", "end", "@workers", "<<", "next_thread", "end", "end" ]
Starts running the jobs in the thread pool.
[ "Starts", "running", "the", "jobs", "in", "the", "thread", "pool", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L75-L90
10,420
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.Pool.stop
def stop GRPC.logger.info('stopping, will wait for all the workers to exit') @stop_mutex.synchronize do # wait @keep_alive seconds for workers to stop @stopped = true loop do break unless ready_for_work? worker_queue = @ready_workers.pop worker_queue << [proc { throw :exit }, []] end @stop_cond.wait(@stop_mutex, @keep_alive) if @workers.size > 0 end forcibly_stop_workers GRPC.logger.info('stopped, all workers are shutdown') end
ruby
def stop GRPC.logger.info('stopping, will wait for all the workers to exit') @stop_mutex.synchronize do # wait @keep_alive seconds for workers to stop @stopped = true loop do break unless ready_for_work? worker_queue = @ready_workers.pop worker_queue << [proc { throw :exit }, []] end @stop_cond.wait(@stop_mutex, @keep_alive) if @workers.size > 0 end forcibly_stop_workers GRPC.logger.info('stopped, all workers are shutdown') end
[ "def", "stop", "GRPC", ".", "logger", ".", "info", "(", "'stopping, will wait for all the workers to exit'", ")", "@stop_mutex", ".", "synchronize", "do", "# wait @keep_alive seconds for workers to stop", "@stopped", "=", "true", "loop", "do", "break", "unless", "ready_for_work?", "worker_queue", "=", "@ready_workers", ".", "pop", "worker_queue", "<<", "[", "proc", "{", "throw", ":exit", "}", ",", "[", "]", "]", "end", "@stop_cond", ".", "wait", "(", "@stop_mutex", ",", "@keep_alive", ")", "if", "@workers", ".", "size", ">", "0", "end", "forcibly_stop_workers", "GRPC", ".", "logger", ".", "info", "(", "'stopped, all workers are shutdown'", ")", "end" ]
Stops the jobs in the pool
[ "Stops", "the", "jobs", "in", "the", "pool" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L93-L106
10,421
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.Pool.forcibly_stop_workers
def forcibly_stop_workers return unless @workers.size > 0 GRPC.logger.info("forcibly terminating #{@workers.size} worker(s)") @workers.each do |t| next unless t.alive? begin t.exit rescue StandardError => e GRPC.logger.warn('error while terminating a worker') GRPC.logger.warn(e) end end end
ruby
def forcibly_stop_workers return unless @workers.size > 0 GRPC.logger.info("forcibly terminating #{@workers.size} worker(s)") @workers.each do |t| next unless t.alive? begin t.exit rescue StandardError => e GRPC.logger.warn('error while terminating a worker') GRPC.logger.warn(e) end end end
[ "def", "forcibly_stop_workers", "return", "unless", "@workers", ".", "size", ">", "0", "GRPC", ".", "logger", ".", "info", "(", "\"forcibly terminating #{@workers.size} worker(s)\"", ")", "@workers", ".", "each", "do", "|", "t", "|", "next", "unless", "t", ".", "alive?", "begin", "t", ".", "exit", "rescue", "StandardError", "=>", "e", "GRPC", ".", "logger", ".", "warn", "(", "'error while terminating a worker'", ")", "GRPC", ".", "logger", ".", "warn", "(", "e", ")", "end", "end", "end" ]
Forcibly shutdown any threads that are still alive.
[ "Forcibly", "shutdown", "any", "threads", "that", "are", "still", "alive", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L111-L123
10,422
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.RpcServer.stop
def stop # if called via run_till_terminated_or_interrupted, # signal stop_server_thread and dont do anything if @stop_server.nil? == false && @stop_server == false @stop_server = true @stop_server_cv.broadcast return end @run_mutex.synchronize do fail 'Cannot stop before starting' if @running_state == :not_started return if @running_state != :running transition_running_state(:stopping) deadline = from_relative_time(@poll_period) @server.shutdown_and_notify(deadline) end @pool.stop end
ruby
def stop # if called via run_till_terminated_or_interrupted, # signal stop_server_thread and dont do anything if @stop_server.nil? == false && @stop_server == false @stop_server = true @stop_server_cv.broadcast return end @run_mutex.synchronize do fail 'Cannot stop before starting' if @running_state == :not_started return if @running_state != :running transition_running_state(:stopping) deadline = from_relative_time(@poll_period) @server.shutdown_and_notify(deadline) end @pool.stop end
[ "def", "stop", "# if called via run_till_terminated_or_interrupted,", "# signal stop_server_thread and dont do anything", "if", "@stop_server", ".", "nil?", "==", "false", "&&", "@stop_server", "==", "false", "@stop_server", "=", "true", "@stop_server_cv", ".", "broadcast", "return", "end", "@run_mutex", ".", "synchronize", "do", "fail", "'Cannot stop before starting'", "if", "@running_state", "==", ":not_started", "return", "if", "@running_state", "!=", ":running", "transition_running_state", "(", ":stopping", ")", "deadline", "=", "from_relative_time", "(", "@poll_period", ")", "@server", ".", "shutdown_and_notify", "(", "deadline", ")", "end", "@pool", ".", "stop", "end" ]
Creates a new RpcServer. The RPC server is configured using keyword arguments. There are some specific keyword args used to configure the RpcServer instance. * pool_size: the size of the thread pool the server uses to run its threads. No more concurrent requests can be made than the size of the thread pool * max_waiting_requests: Deprecated due to internal changes to the thread pool. This is still an argument for compatibility but is ignored. * poll_period: The amount of time in seconds to wait for currently-serviced RPC's to finish before cancelling them when shutting down the server. * pool_keep_alive: The amount of time in seconds to wait for currently busy thread-pool threads to finish before forcing an abrupt exit to each thread. * connect_md_proc: when non-nil is a proc for determining metadata to send back the client on receiving an invocation req. The proc signature is: {key: val, ..} func(method_name, {key: val, ...}) * server_args: A server arguments hash to be passed down to the underlying core server * interceptors: Am array of GRPC::ServerInterceptor objects that will be used for intercepting server handlers to provide extra functionality. Interceptors are an EXPERIMENTAL API. stops a running server the call has no impact if the server is already stopped, otherwise server's current call loop is it's last.
[ "Creates", "a", "new", "RpcServer", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L242-L258
10,423
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.RpcServer.transition_running_state
def transition_running_state(target_state) state_transitions = { not_started: :running, running: :stopping, stopping: :stopped } if state_transitions[@running_state] == target_state @running_state = target_state else fail "Bad server state transition: #{@running_state}->#{target_state}" end end
ruby
def transition_running_state(target_state) state_transitions = { not_started: :running, running: :stopping, stopping: :stopped } if state_transitions[@running_state] == target_state @running_state = target_state else fail "Bad server state transition: #{@running_state}->#{target_state}" end end
[ "def", "transition_running_state", "(", "target_state", ")", "state_transitions", "=", "{", "not_started", ":", ":running", ",", "running", ":", ":stopping", ",", "stopping", ":", ":stopped", "}", "if", "state_transitions", "[", "@running_state", "]", "==", "target_state", "@running_state", "=", "target_state", "else", "fail", "\"Bad server state transition: #{@running_state}->#{target_state}\"", "end", "end" ]
Can only be called while holding @run_mutex
[ "Can", "only", "be", "called", "while", "holding" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L267-L278
10,424
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.RpcServer.handle
def handle(service) @run_mutex.synchronize do unless @running_state == :not_started fail 'cannot add services if the server has been started' end cls = service.is_a?(Class) ? service : service.class assert_valid_service_class(cls) add_rpc_descs_for(service) end end
ruby
def handle(service) @run_mutex.synchronize do unless @running_state == :not_started fail 'cannot add services if the server has been started' end cls = service.is_a?(Class) ? service : service.class assert_valid_service_class(cls) add_rpc_descs_for(service) end end
[ "def", "handle", "(", "service", ")", "@run_mutex", ".", "synchronize", "do", "unless", "@running_state", "==", ":not_started", "fail", "'cannot add services if the server has been started'", "end", "cls", "=", "service", ".", "is_a?", "(", "Class", ")", "?", "service", ":", "service", ".", "class", "assert_valid_service_class", "(", "cls", ")", "add_rpc_descs_for", "(", "service", ")", "end", "end" ]
handle registration of classes service is either a class that includes GRPC::GenericService and whose #new function can be called without argument or any instance of such a class. E.g, after class Divider include GRPC::GenericService rpc :div DivArgs, DivReply # single request, single response def initialize(optional_arg='default option') # no args ... end srv = GRPC::RpcServer.new(...) # Either of these works srv.handle(Divider) # or srv.handle(Divider.new('replace optional arg')) It raises RuntimeError: - if service is not valid service class or object - its handler methods are already registered - if the server is already running @param service [Object|Class] a service class or object as described above
[ "handle", "registration", "of", "classes" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L333-L342
10,425
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.RpcServer.run
def run @run_mutex.synchronize do fail 'cannot run without registering services' if rpc_descs.size.zero? @pool.start @server.start transition_running_state(:running) @run_cond.broadcast end loop_handle_server_calls end
ruby
def run @run_mutex.synchronize do fail 'cannot run without registering services' if rpc_descs.size.zero? @pool.start @server.start transition_running_state(:running) @run_cond.broadcast end loop_handle_server_calls end
[ "def", "run", "@run_mutex", ".", "synchronize", "do", "fail", "'cannot run without registering services'", "if", "rpc_descs", ".", "size", ".", "zero?", "@pool", ".", "start", "@server", ".", "start", "transition_running_state", "(", ":running", ")", "@run_cond", ".", "broadcast", "end", "loop_handle_server_calls", "end" ]
runs the server - if no rpc_descs are registered, this exits immediately, otherwise it continues running permanently and does not return until program exit. - #running? returns true after this is called, until #stop cause the the server to stop.
[ "runs", "the", "server" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L351-L360
10,426
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.RpcServer.run_till_terminated_or_interrupted
def run_till_terminated_or_interrupted(signals, wait_interval = 60) @stop_server = false @stop_server_mu = Mutex.new @stop_server_cv = ConditionVariable.new @stop_server_thread = Thread.new do loop do break if @stop_server @stop_server_mu.synchronize do @stop_server_cv.wait(@stop_server_mu, wait_interval) end end # stop is surrounded by mutex, should handle multiple calls to stop # correctly stop end valid_signals = Signal.list # register signal handlers signals.each do |sig| # input validation if sig.class == String sig.upcase! if sig.start_with?('SIG') # cut out the SIG prefix to see if valid signal sig = sig[3..-1] end end # register signal traps for all valid signals if valid_signals.value?(sig) || valid_signals.key?(sig) Signal.trap(sig) do @stop_server = true @stop_server_cv.broadcast end else fail "#{sig} not a valid signal" end end run @stop_server_thread.join end
ruby
def run_till_terminated_or_interrupted(signals, wait_interval = 60) @stop_server = false @stop_server_mu = Mutex.new @stop_server_cv = ConditionVariable.new @stop_server_thread = Thread.new do loop do break if @stop_server @stop_server_mu.synchronize do @stop_server_cv.wait(@stop_server_mu, wait_interval) end end # stop is surrounded by mutex, should handle multiple calls to stop # correctly stop end valid_signals = Signal.list # register signal handlers signals.each do |sig| # input validation if sig.class == String sig.upcase! if sig.start_with?('SIG') # cut out the SIG prefix to see if valid signal sig = sig[3..-1] end end # register signal traps for all valid signals if valid_signals.value?(sig) || valid_signals.key?(sig) Signal.trap(sig) do @stop_server = true @stop_server_cv.broadcast end else fail "#{sig} not a valid signal" end end run @stop_server_thread.join end
[ "def", "run_till_terminated_or_interrupted", "(", "signals", ",", "wait_interval", "=", "60", ")", "@stop_server", "=", "false", "@stop_server_mu", "=", "Mutex", ".", "new", "@stop_server_cv", "=", "ConditionVariable", ".", "new", "@stop_server_thread", "=", "Thread", ".", "new", "do", "loop", "do", "break", "if", "@stop_server", "@stop_server_mu", ".", "synchronize", "do", "@stop_server_cv", ".", "wait", "(", "@stop_server_mu", ",", "wait_interval", ")", "end", "end", "# stop is surrounded by mutex, should handle multiple calls to stop", "# correctly", "stop", "end", "valid_signals", "=", "Signal", ".", "list", "# register signal handlers", "signals", ".", "each", "do", "|", "sig", "|", "# input validation", "if", "sig", ".", "class", "==", "String", "sig", ".", "upcase!", "if", "sig", ".", "start_with?", "(", "'SIG'", ")", "# cut out the SIG prefix to see if valid signal", "sig", "=", "sig", "[", "3", "..", "-", "1", "]", "end", "end", "# register signal traps for all valid signals", "if", "valid_signals", ".", "value?", "(", "sig", ")", "||", "valid_signals", ".", "key?", "(", "sig", ")", "Signal", ".", "trap", "(", "sig", ")", "do", "@stop_server", "=", "true", "@stop_server_cv", ".", "broadcast", "end", "else", "fail", "\"#{sig} not a valid signal\"", "end", "end", "run", "@stop_server_thread", ".", "join", "end" ]
runs the server with signal handlers @param signals List of String, Integer or both representing signals that the user would like to send to the server for graceful shutdown @param wait_interval (optional) Integer seconds that user would like stop_server_thread to poll stop_server
[ "runs", "the", "server", "with", "signal", "handlers" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L371-L416
10,427
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.RpcServer.available?
def available?(an_rpc) return an_rpc if @pool.ready_for_work? GRPC.logger.warn('no free worker threads currently') noop = proc { |x| x } # Create a new active call that knows that metadata hasn't been # sent yet c = ActiveCall.new(an_rpc.call, noop, noop, an_rpc.deadline, metadata_received: true, started: false) c.send_status(GRPC::Core::StatusCodes::RESOURCE_EXHAUSTED, 'No free threads in thread pool') nil end
ruby
def available?(an_rpc) return an_rpc if @pool.ready_for_work? GRPC.logger.warn('no free worker threads currently') noop = proc { |x| x } # Create a new active call that knows that metadata hasn't been # sent yet c = ActiveCall.new(an_rpc.call, noop, noop, an_rpc.deadline, metadata_received: true, started: false) c.send_status(GRPC::Core::StatusCodes::RESOURCE_EXHAUSTED, 'No free threads in thread pool') nil end
[ "def", "available?", "(", "an_rpc", ")", "return", "an_rpc", "if", "@pool", ".", "ready_for_work?", "GRPC", ".", "logger", ".", "warn", "(", "'no free worker threads currently'", ")", "noop", "=", "proc", "{", "|", "x", "|", "x", "}", "# Create a new active call that knows that metadata hasn't been", "# sent yet", "c", "=", "ActiveCall", ".", "new", "(", "an_rpc", ".", "call", ",", "noop", ",", "noop", ",", "an_rpc", ".", "deadline", ",", "metadata_received", ":", "true", ",", "started", ":", "false", ")", "c", ".", "send_status", "(", "GRPC", "::", "Core", "::", "StatusCodes", "::", "RESOURCE_EXHAUSTED", ",", "'No free threads in thread pool'", ")", "nil", "end" ]
Sends RESOURCE_EXHAUSTED if there are too many unprocessed jobs
[ "Sends", "RESOURCE_EXHAUSTED", "if", "there", "are", "too", "many", "unprocessed", "jobs" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L419-L431
10,428
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.RpcServer.implemented?
def implemented?(an_rpc) mth = an_rpc.method.to_sym return an_rpc if rpc_descs.key?(mth) GRPC.logger.warn("UNIMPLEMENTED: #{an_rpc}") noop = proc { |x| x } # Create a new active call that knows that # metadata hasn't been sent yet c = ActiveCall.new(an_rpc.call, noop, noop, an_rpc.deadline, metadata_received: true, started: false) c.send_status(GRPC::Core::StatusCodes::UNIMPLEMENTED, '') nil end
ruby
def implemented?(an_rpc) mth = an_rpc.method.to_sym return an_rpc if rpc_descs.key?(mth) GRPC.logger.warn("UNIMPLEMENTED: #{an_rpc}") noop = proc { |x| x } # Create a new active call that knows that # metadata hasn't been sent yet c = ActiveCall.new(an_rpc.call, noop, noop, an_rpc.deadline, metadata_received: true, started: false) c.send_status(GRPC::Core::StatusCodes::UNIMPLEMENTED, '') nil end
[ "def", "implemented?", "(", "an_rpc", ")", "mth", "=", "an_rpc", ".", "method", ".", "to_sym", "return", "an_rpc", "if", "rpc_descs", ".", "key?", "(", "mth", ")", "GRPC", ".", "logger", ".", "warn", "(", "\"UNIMPLEMENTED: #{an_rpc}\"", ")", "noop", "=", "proc", "{", "|", "x", "|", "x", "}", "# Create a new active call that knows that", "# metadata hasn't been sent yet", "c", "=", "ActiveCall", ".", "new", "(", "an_rpc", ".", "call", ",", "noop", ",", "noop", ",", "an_rpc", ".", "deadline", ",", "metadata_received", ":", "true", ",", "started", ":", "false", ")", "c", ".", "send_status", "(", "GRPC", "::", "Core", "::", "StatusCodes", "::", "UNIMPLEMENTED", ",", "''", ")", "nil", "end" ]
Sends UNIMPLEMENTED if the method is not implemented by this server
[ "Sends", "UNIMPLEMENTED", "if", "the", "method", "is", "not", "implemented", "by", "this", "server" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L434-L446
10,429
grpc/grpc
src/ruby/lib/grpc/generic/rpc_server.rb
GRPC.RpcServer.loop_handle_server_calls
def loop_handle_server_calls fail 'not started' if running_state == :not_started while running_state == :running begin an_rpc = @server.request_call break if (!an_rpc.nil?) && an_rpc.call.nil? active_call = new_active_server_call(an_rpc) unless active_call.nil? @pool.schedule(active_call) do |ac| c, mth = ac begin rpc_descs[mth].run_server_method( c, rpc_handlers[mth], @interceptors.build_context ) rescue StandardError c.send_status(GRPC::Core::StatusCodes::INTERNAL, 'Server handler failed') end end end rescue Core::CallError, RuntimeError => e # these might happen for various reasons. The correct behavior of # the server is to log them and continue, if it's not shutting down. if running_state == :running GRPC.logger.warn("server call failed: #{e}") end next end end # @running_state should be :stopping here @run_mutex.synchronize do transition_running_state(:stopped) GRPC.logger.info("stopped: #{self}") @server.close end end
ruby
def loop_handle_server_calls fail 'not started' if running_state == :not_started while running_state == :running begin an_rpc = @server.request_call break if (!an_rpc.nil?) && an_rpc.call.nil? active_call = new_active_server_call(an_rpc) unless active_call.nil? @pool.schedule(active_call) do |ac| c, mth = ac begin rpc_descs[mth].run_server_method( c, rpc_handlers[mth], @interceptors.build_context ) rescue StandardError c.send_status(GRPC::Core::StatusCodes::INTERNAL, 'Server handler failed') end end end rescue Core::CallError, RuntimeError => e # these might happen for various reasons. The correct behavior of # the server is to log them and continue, if it's not shutting down. if running_state == :running GRPC.logger.warn("server call failed: #{e}") end next end end # @running_state should be :stopping here @run_mutex.synchronize do transition_running_state(:stopped) GRPC.logger.info("stopped: #{self}") @server.close end end
[ "def", "loop_handle_server_calls", "fail", "'not started'", "if", "running_state", "==", ":not_started", "while", "running_state", "==", ":running", "begin", "an_rpc", "=", "@server", ".", "request_call", "break", "if", "(", "!", "an_rpc", ".", "nil?", ")", "&&", "an_rpc", ".", "call", ".", "nil?", "active_call", "=", "new_active_server_call", "(", "an_rpc", ")", "unless", "active_call", ".", "nil?", "@pool", ".", "schedule", "(", "active_call", ")", "do", "|", "ac", "|", "c", ",", "mth", "=", "ac", "begin", "rpc_descs", "[", "mth", "]", ".", "run_server_method", "(", "c", ",", "rpc_handlers", "[", "mth", "]", ",", "@interceptors", ".", "build_context", ")", "rescue", "StandardError", "c", ".", "send_status", "(", "GRPC", "::", "Core", "::", "StatusCodes", "::", "INTERNAL", ",", "'Server handler failed'", ")", "end", "end", "end", "rescue", "Core", "::", "CallError", ",", "RuntimeError", "=>", "e", "# these might happen for various reasons. The correct behavior of", "# the server is to log them and continue, if it's not shutting down.", "if", "running_state", "==", ":running", "GRPC", ".", "logger", ".", "warn", "(", "\"server call failed: #{e}\"", ")", "end", "next", "end", "end", "# @running_state should be :stopping here", "@run_mutex", ".", "synchronize", "do", "transition_running_state", "(", ":stopped", ")", "GRPC", ".", "logger", ".", "info", "(", "\"stopped: #{self}\"", ")", "@server", ".", "close", "end", "end" ]
handles calls to the server
[ "handles", "calls", "to", "the", "server" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/rpc_server.rb#L449-L486
10,430
grpc/grpc
src/ruby/lib/grpc/generic/client_stub.rb
GRPC.ClientStub.request_response
def request_response(method, req, marshal, unmarshal, deadline: nil, return_op: false, parent: nil, credentials: nil, metadata: {}) c = new_active_call(method, marshal, unmarshal, deadline: deadline, parent: parent, credentials: credentials) interception_context = @interceptors.build_context intercept_args = { method: method, request: req, call: c.interceptable, metadata: metadata } if return_op # return the operation view of the active_call; define #execute as a # new method for this instance that invokes #request_response. c.merge_metadata_to_send(metadata) op = c.operation op.define_singleton_method(:execute) do interception_context.intercept!(:request_response, intercept_args) do c.request_response(req, metadata: metadata) end end op else interception_context.intercept!(:request_response, intercept_args) do c.request_response(req, metadata: metadata) end end end
ruby
def request_response(method, req, marshal, unmarshal, deadline: nil, return_op: false, parent: nil, credentials: nil, metadata: {}) c = new_active_call(method, marshal, unmarshal, deadline: deadline, parent: parent, credentials: credentials) interception_context = @interceptors.build_context intercept_args = { method: method, request: req, call: c.interceptable, metadata: metadata } if return_op # return the operation view of the active_call; define #execute as a # new method for this instance that invokes #request_response. c.merge_metadata_to_send(metadata) op = c.operation op.define_singleton_method(:execute) do interception_context.intercept!(:request_response, intercept_args) do c.request_response(req, metadata: metadata) end end op else interception_context.intercept!(:request_response, intercept_args) do c.request_response(req, metadata: metadata) end end end
[ "def", "request_response", "(", "method", ",", "req", ",", "marshal", ",", "unmarshal", ",", "deadline", ":", "nil", ",", "return_op", ":", "false", ",", "parent", ":", "nil", ",", "credentials", ":", "nil", ",", "metadata", ":", "{", "}", ")", "c", "=", "new_active_call", "(", "method", ",", "marshal", ",", "unmarshal", ",", "deadline", ":", "deadline", ",", "parent", ":", "parent", ",", "credentials", ":", "credentials", ")", "interception_context", "=", "@interceptors", ".", "build_context", "intercept_args", "=", "{", "method", ":", "method", ",", "request", ":", "req", ",", "call", ":", "c", ".", "interceptable", ",", "metadata", ":", "metadata", "}", "if", "return_op", "# return the operation view of the active_call; define #execute as a", "# new method for this instance that invokes #request_response.", "c", ".", "merge_metadata_to_send", "(", "metadata", ")", "op", "=", "c", ".", "operation", "op", ".", "define_singleton_method", "(", ":execute", ")", "do", "interception_context", ".", "intercept!", "(", ":request_response", ",", "intercept_args", ")", "do", "c", ".", "request_response", "(", "req", ",", "metadata", ":", "metadata", ")", "end", "end", "op", "else", "interception_context", ".", "intercept!", "(", ":request_response", ",", "intercept_args", ")", "do", "c", ".", "request_response", "(", "req", ",", "metadata", ":", "metadata", ")", "end", "end", "end" ]
Creates a new ClientStub. Minimally, a stub is created with the just the host of the gRPC service it wishes to access, e.g., my_stub = ClientStub.new(example.host.com:50505, :this_channel_is_insecure) If a channel_override argument is passed, it will be used as the underlying channel. Otherwise, the channel_args argument will be used to construct a new underlying channel. There are some specific keyword args that are not used to configure the channel: - :channel_override when present, this must be a pre-created GRPC::Core::Channel. If it's present the host and arbitrary keyword arg areignored, and the RPC connection uses this channel. - :timeout when present, this is the default timeout used for calls @param host [String] the host the stub connects to @param creds [Core::ChannelCredentials|Symbol] the channel credentials, or :this_channel_is_insecure, which explicitly indicates that the client should be created with an insecure connection. Note: this argument is ignored if the channel_override argument is provided. @param channel_override [Core::Channel] a pre-created channel @param timeout [Number] the default timeout to use in requests @param propagate_mask [Number] A bitwise combination of flags in GRPC::Core::PropagateMasks. Indicates how data should be propagated from parent server calls to child client calls if this client is being used within a gRPC server. @param channel_args [Hash] the channel arguments. Note: this argument is ignored if the channel_override argument is provided. @param interceptors [Array<GRPC::ClientInterceptor>] An array of GRPC::ClientInterceptor objects that will be used for intercepting calls before they are executed Interceptors are an EXPERIMENTAL API. request_response sends a request to a GRPC server, and returns the response. == Flow Control == This is a blocking call. * it does not return until a response is received. * the requests is sent only when GRPC core's flow control allows it to be sent. == Errors == An RuntimeError is raised if * the server responds with a non-OK status * the deadline is exceeded == Return Value == If return_op is false, the call returns the response If return_op is true, the call returns an Operation, calling execute on the Operation returns the response. @param method [String] the RPC method to call on the GRPC server @param req [Object] the request sent to the server @param marshal [Function] f(obj)->string that marshals requests @param unmarshal [Function] f(string)->obj that unmarshals responses @param deadline [Time] (optional) the time the request should complete @param return_op [true|false] return an Operation if true @param parent [Core::Call] a prior call whose reserved metadata will be propagated by this one. @param credentials [Core::CallCredentials] credentials to use when making the call @param metadata [Hash] metadata to be sent to the server @return [Object] the response received from the server
[ "Creates", "a", "new", "ClientStub", "." ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/client_stub.rb#L148-L181
10,431
grpc/grpc
src/ruby/lib/grpc/generic/client_stub.rb
GRPC.ClientStub.new_active_call
def new_active_call(method, marshal, unmarshal, deadline: nil, parent: nil, credentials: nil) deadline = from_relative_time(@timeout) if deadline.nil? # Provide each new client call with its own completion queue call = @ch.create_call(parent, # parent call @propagate_mask, # propagation options method, nil, # host use nil, deadline) call.set_credentials! credentials unless credentials.nil? ActiveCall.new(call, marshal, unmarshal, deadline, started: false) end
ruby
def new_active_call(method, marshal, unmarshal, deadline: nil, parent: nil, credentials: nil) deadline = from_relative_time(@timeout) if deadline.nil? # Provide each new client call with its own completion queue call = @ch.create_call(parent, # parent call @propagate_mask, # propagation options method, nil, # host use nil, deadline) call.set_credentials! credentials unless credentials.nil? ActiveCall.new(call, marshal, unmarshal, deadline, started: false) end
[ "def", "new_active_call", "(", "method", ",", "marshal", ",", "unmarshal", ",", "deadline", ":", "nil", ",", "parent", ":", "nil", ",", "credentials", ":", "nil", ")", "deadline", "=", "from_relative_time", "(", "@timeout", ")", "if", "deadline", ".", "nil?", "# Provide each new client call with its own completion queue", "call", "=", "@ch", ".", "create_call", "(", "parent", ",", "# parent call", "@propagate_mask", ",", "# propagation options", "method", ",", "nil", ",", "# host use nil,", "deadline", ")", "call", ".", "set_credentials!", "credentials", "unless", "credentials", ".", "nil?", "ActiveCall", ".", "new", "(", "call", ",", "marshal", ",", "unmarshal", ",", "deadline", ",", "started", ":", "false", ")", "end" ]
Creates a new active stub @param method [string] the method being called. @param marshal [Function] f(obj)->string that marshals requests @param unmarshal [Function] f(string)->obj that unmarshals responses @param parent [Grpc::Call] a parent call, available when calls are made from server @param credentials [Core::CallCredentials] credentials to use when making the call
[ "Creates", "a", "new", "active", "stub" ]
f3937f0e55227a4ef3a23f895d3b204a947610f8
https://github.com/grpc/grpc/blob/f3937f0e55227a4ef3a23f895d3b204a947610f8/src/ruby/lib/grpc/generic/client_stub.rb#L485-L499
10,432
jekyll/jekyll
lib/jekyll/liquid_extensions.rb
Jekyll.LiquidExtensions.lookup_variable
def lookup_variable(context, variable) lookup = context variable.split(".").each do |value| lookup = lookup[value] end lookup || variable end
ruby
def lookup_variable(context, variable) lookup = context variable.split(".").each do |value| lookup = lookup[value] end lookup || variable end
[ "def", "lookup_variable", "(", "context", ",", "variable", ")", "lookup", "=", "context", "variable", ".", "split", "(", "\".\"", ")", ".", "each", "do", "|", "value", "|", "lookup", "=", "lookup", "[", "value", "]", "end", "lookup", "||", "variable", "end" ]
Lookup a Liquid variable in the given context. context - the Liquid context in question. variable - the variable name, as a string. Returns the value of the variable in the context or the variable name if not found.
[ "Lookup", "a", "Liquid", "variable", "in", "the", "given", "context", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/liquid_extensions.rb#L12-L20
10,433
jekyll/jekyll
lib/jekyll/renderer.rb
Jekyll.Renderer.converters
def converters @converters ||= site.converters.select { |c| c.matches(document.extname) }.sort end
ruby
def converters @converters ||= site.converters.select { |c| c.matches(document.extname) }.sort end
[ "def", "converters", "@converters", "||=", "site", ".", "converters", ".", "select", "{", "|", "c", "|", "c", ".", "matches", "(", "document", ".", "extname", ")", "}", ".", "sort", "end" ]
Determine which converters to use based on this document's extension. Returns Array of Converter instances.
[ "Determine", "which", "converters", "to", "use", "based", "on", "this", "document", "s", "extension", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/renderer.rb#L38-L40
10,434
jekyll/jekyll
lib/jekyll/renderer.rb
Jekyll.Renderer.run
def run Jekyll.logger.debug "Rendering:", document.relative_path assign_pages! assign_current_document! assign_highlighter_options! assign_layout_data! Jekyll.logger.debug "Pre-Render Hooks:", document.relative_path document.trigger_hooks(:pre_render, payload) render_document end
ruby
def run Jekyll.logger.debug "Rendering:", document.relative_path assign_pages! assign_current_document! assign_highlighter_options! assign_layout_data! Jekyll.logger.debug "Pre-Render Hooks:", document.relative_path document.trigger_hooks(:pre_render, payload) render_document end
[ "def", "run", "Jekyll", ".", "logger", ".", "debug", "\"Rendering:\"", ",", "document", ".", "relative_path", "assign_pages!", "assign_current_document!", "assign_highlighter_options!", "assign_layout_data!", "Jekyll", ".", "logger", ".", "debug", "\"Pre-Render Hooks:\"", ",", "document", ".", "relative_path", "document", ".", "trigger_hooks", "(", ":pre_render", ",", "payload", ")", "render_document", "end" ]
Prepare payload and render the document Returns String rendered document output
[ "Prepare", "payload", "and", "render", "the", "document" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/renderer.rb#L52-L64
10,435
jekyll/jekyll
lib/jekyll/renderer.rb
Jekyll.Renderer.render_document
def render_document info = { :registers => { :site => site, :page => payload["page"] }, :strict_filters => liquid_options["strict_filters"], :strict_variables => liquid_options["strict_variables"], } output = document.content if document.render_with_liquid? Jekyll.logger.debug "Rendering Liquid:", document.relative_path output = render_liquid(output, payload, info, document.path) end Jekyll.logger.debug "Rendering Markup:", document.relative_path output = convert(output.to_s) document.content = output if document.place_in_layout? Jekyll.logger.debug "Rendering Layout:", document.relative_path output = place_in_layouts(output, payload, info) end output end
ruby
def render_document info = { :registers => { :site => site, :page => payload["page"] }, :strict_filters => liquid_options["strict_filters"], :strict_variables => liquid_options["strict_variables"], } output = document.content if document.render_with_liquid? Jekyll.logger.debug "Rendering Liquid:", document.relative_path output = render_liquid(output, payload, info, document.path) end Jekyll.logger.debug "Rendering Markup:", document.relative_path output = convert(output.to_s) document.content = output if document.place_in_layout? Jekyll.logger.debug "Rendering Layout:", document.relative_path output = place_in_layouts(output, payload, info) end output end
[ "def", "render_document", "info", "=", "{", ":registers", "=>", "{", ":site", "=>", "site", ",", ":page", "=>", "payload", "[", "\"page\"", "]", "}", ",", ":strict_filters", "=>", "liquid_options", "[", "\"strict_filters\"", "]", ",", ":strict_variables", "=>", "liquid_options", "[", "\"strict_variables\"", "]", ",", "}", "output", "=", "document", ".", "content", "if", "document", ".", "render_with_liquid?", "Jekyll", ".", "logger", ".", "debug", "\"Rendering Liquid:\"", ",", "document", ".", "relative_path", "output", "=", "render_liquid", "(", "output", ",", "payload", ",", "info", ",", "document", ".", "path", ")", "end", "Jekyll", ".", "logger", ".", "debug", "\"Rendering Markup:\"", ",", "document", ".", "relative_path", "output", "=", "convert", "(", "output", ".", "to_s", ")", "document", ".", "content", "=", "output", "if", "document", ".", "place_in_layout?", "Jekyll", ".", "logger", ".", "debug", "\"Rendering Layout:\"", ",", "document", ".", "relative_path", "output", "=", "place_in_layouts", "(", "output", ",", "payload", ",", "info", ")", "end", "output", "end" ]
Render the document. Returns String rendered document output rubocop: disable AbcSize
[ "Render", "the", "document", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/renderer.rb#L70-L93
10,436
jekyll/jekyll
lib/jekyll/renderer.rb
Jekyll.Renderer.place_in_layouts
def place_in_layouts(content, payload, info) output = content.dup layout = layouts[document.data["layout"].to_s] validate_layout(layout) used = Set.new([layout]) # Reset the payload layout data to ensure it starts fresh for each page. payload["layout"] = nil while layout output = render_layout(output, layout, info) add_regenerator_dependencies(layout) next unless (layout = site.layouts[layout.data["layout"]]) break if used.include?(layout) used << layout end output end
ruby
def place_in_layouts(content, payload, info) output = content.dup layout = layouts[document.data["layout"].to_s] validate_layout(layout) used = Set.new([layout]) # Reset the payload layout data to ensure it starts fresh for each page. payload["layout"] = nil while layout output = render_layout(output, layout, info) add_regenerator_dependencies(layout) next unless (layout = site.layouts[layout.data["layout"]]) break if used.include?(layout) used << layout end output end
[ "def", "place_in_layouts", "(", "content", ",", "payload", ",", "info", ")", "output", "=", "content", ".", "dup", "layout", "=", "layouts", "[", "document", ".", "data", "[", "\"layout\"", "]", ".", "to_s", "]", "validate_layout", "(", "layout", ")", "used", "=", "Set", ".", "new", "(", "[", "layout", "]", ")", "# Reset the payload layout data to ensure it starts fresh for each page.", "payload", "[", "\"layout\"", "]", "=", "nil", "while", "layout", "output", "=", "render_layout", "(", "output", ",", "layout", ",", "info", ")", "add_regenerator_dependencies", "(", "layout", ")", "next", "unless", "(", "layout", "=", "site", ".", "layouts", "[", "layout", ".", "data", "[", "\"layout\"", "]", "]", ")", "break", "if", "used", ".", "include?", "(", "layout", ")", "used", "<<", "layout", "end", "output", "end" ]
Render layouts and place document content inside. Returns String rendered content
[ "Render", "layouts", "and", "place", "document", "content", "inside", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/renderer.rb#L148-L168
10,437
jekyll/jekyll
lib/jekyll/renderer.rb
Jekyll.Renderer.validate_layout
def validate_layout(layout) if invalid_layout?(layout) Jekyll.logger.warn( "Build Warning:", "Layout '#{document.data["layout"]}' requested "\ "in #{document.relative_path} does not exist." ) elsif !layout.nil? layout_source = layout.path.start_with?(site.source) ? :site : :theme Jekyll.logger.debug "Layout source:", layout_source end end
ruby
def validate_layout(layout) if invalid_layout?(layout) Jekyll.logger.warn( "Build Warning:", "Layout '#{document.data["layout"]}' requested "\ "in #{document.relative_path} does not exist." ) elsif !layout.nil? layout_source = layout.path.start_with?(site.source) ? :site : :theme Jekyll.logger.debug "Layout source:", layout_source end end
[ "def", "validate_layout", "(", "layout", ")", "if", "invalid_layout?", "(", "layout", ")", "Jekyll", ".", "logger", ".", "warn", "(", "\"Build Warning:\"", ",", "\"Layout '#{document.data[\"layout\"]}' requested \"", "\"in #{document.relative_path} does not exist.\"", ")", "elsif", "!", "layout", ".", "nil?", "layout_source", "=", "layout", ".", "path", ".", "start_with?", "(", "site", ".", "source", ")", "?", ":site", ":", ":theme", "Jekyll", ".", "logger", ".", "debug", "\"Layout source:\"", ",", "layout_source", "end", "end" ]
Checks if the layout specified in the document actually exists layout - the layout to check Returns nothing
[ "Checks", "if", "the", "layout", "specified", "in", "the", "document", "actually", "exists" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/renderer.rb#L176-L187
10,438
jekyll/jekyll
lib/jekyll/renderer.rb
Jekyll.Renderer.render_layout
def render_layout(output, layout, info) payload["content"] = output payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {}) render_liquid( layout.content, payload, info, layout.relative_path ) end
ruby
def render_layout(output, layout, info) payload["content"] = output payload["layout"] = Utils.deep_merge_hashes(layout.data, payload["layout"] || {}) render_liquid( layout.content, payload, info, layout.relative_path ) end
[ "def", "render_layout", "(", "output", ",", "layout", ",", "info", ")", "payload", "[", "\"content\"", "]", "=", "output", "payload", "[", "\"layout\"", "]", "=", "Utils", ".", "deep_merge_hashes", "(", "layout", ".", "data", ",", "payload", "[", "\"layout\"", "]", "||", "{", "}", ")", "render_liquid", "(", "layout", ".", "content", ",", "payload", ",", "info", ",", "layout", ".", "relative_path", ")", "end" ]
Render layout content into document.output Returns String rendered content
[ "Render", "layout", "content", "into", "document", ".", "output" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/renderer.rb#L192-L202
10,439
jekyll/jekyll
lib/jekyll/renderer.rb
Jekyll.Renderer.assign_pages!
def assign_pages! payload["page"] = document.to_liquid payload["paginator"] = (document.pager.to_liquid if document.respond_to?(:pager)) end
ruby
def assign_pages! payload["page"] = document.to_liquid payload["paginator"] = (document.pager.to_liquid if document.respond_to?(:pager)) end
[ "def", "assign_pages!", "payload", "[", "\"page\"", "]", "=", "document", ".", "to_liquid", "payload", "[", "\"paginator\"", "]", "=", "(", "document", ".", "pager", ".", "to_liquid", "if", "document", ".", "respond_to?", "(", ":pager", ")", ")", "end" ]
Set page content to payload and assign pager if document has one. Returns nothing
[ "Set", "page", "content", "to", "payload", "and", "assign", "pager", "if", "document", "has", "one", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/renderer.rb#L216-L219
10,440
jekyll/jekyll
lib/jekyll/reader.rb
Jekyll.Reader.read
def read @site.layouts = LayoutReader.new(site).read read_directories read_included_excludes sort_files! @site.data = DataReader.new(site).read(site.config["data_dir"]) CollectionReader.new(site).read ThemeAssetsReader.new(site).read end
ruby
def read @site.layouts = LayoutReader.new(site).read read_directories read_included_excludes sort_files! @site.data = DataReader.new(site).read(site.config["data_dir"]) CollectionReader.new(site).read ThemeAssetsReader.new(site).read end
[ "def", "read", "@site", ".", "layouts", "=", "LayoutReader", ".", "new", "(", "site", ")", ".", "read", "read_directories", "read_included_excludes", "sort_files!", "@site", ".", "data", "=", "DataReader", ".", "new", "(", "site", ")", ".", "read", "(", "site", ".", "config", "[", "\"data_dir\"", "]", ")", "CollectionReader", ".", "new", "(", "site", ")", ".", "read", "ThemeAssetsReader", ".", "new", "(", "site", ")", ".", "read", "end" ]
Read Site data from disk and load it into internal data structures. Returns nothing.
[ "Read", "Site", "data", "from", "disk", "and", "load", "it", "into", "internal", "data", "structures", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/reader.rb#L14-L22
10,441
jekyll/jekyll
lib/jekyll/reader.rb
Jekyll.Reader.retrieve_dirs
def retrieve_dirs(_base, dir, dot_dirs) dot_dirs.each do |file| dir_path = site.in_source_dir(dir, file) rel_path = File.join(dir, file) @site.reader.read_directories(rel_path) unless @site.dest.chomp("/") == dir_path end end
ruby
def retrieve_dirs(_base, dir, dot_dirs) dot_dirs.each do |file| dir_path = site.in_source_dir(dir, file) rel_path = File.join(dir, file) @site.reader.read_directories(rel_path) unless @site.dest.chomp("/") == dir_path end end
[ "def", "retrieve_dirs", "(", "_base", ",", "dir", ",", "dot_dirs", ")", "dot_dirs", ".", "each", "do", "|", "file", "|", "dir_path", "=", "site", ".", "in_source_dir", "(", "dir", ",", "file", ")", "rel_path", "=", "File", ".", "join", "(", "dir", ",", "file", ")", "@site", ".", "reader", ".", "read_directories", "(", "rel_path", ")", "unless", "@site", ".", "dest", ".", "chomp", "(", "\"/\"", ")", "==", "dir_path", "end", "end" ]
Recursively traverse directories with the read_directories function. base - The String representing the site's base directory. dir - The String representing the directory to traverse down. dot_dirs - The Array of subdirectories in the dir. Returns nothing.
[ "Recursively", "traverse", "directories", "with", "the", "read_directories", "function", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/reader.rb#L85-L91
10,442
jekyll/jekyll
lib/jekyll/reader.rb
Jekyll.Reader.get_entries
def get_entries(dir, subfolder) base = site.in_source_dir(dir, subfolder) return [] unless File.exist?(base) entries = Dir.chdir(base) { filter_entries(Dir["**/*"], base) } entries.delete_if { |e| File.directory?(site.in_source_dir(base, e)) } end
ruby
def get_entries(dir, subfolder) base = site.in_source_dir(dir, subfolder) return [] unless File.exist?(base) entries = Dir.chdir(base) { filter_entries(Dir["**/*"], base) } entries.delete_if { |e| File.directory?(site.in_source_dir(base, e)) } end
[ "def", "get_entries", "(", "dir", ",", "subfolder", ")", "base", "=", "site", ".", "in_source_dir", "(", "dir", ",", "subfolder", ")", "return", "[", "]", "unless", "File", ".", "exist?", "(", "base", ")", "entries", "=", "Dir", ".", "chdir", "(", "base", ")", "{", "filter_entries", "(", "Dir", "[", "\"**/*\"", "]", ",", "base", ")", "}", "entries", ".", "delete_if", "{", "|", "e", "|", "File", ".", "directory?", "(", "site", ".", "in_source_dir", "(", "base", ",", "e", ")", ")", "}", "end" ]
Read the entries from a particular directory for processing dir - The String representing the relative path of the directory to read. subfolder - The String representing the directory to read. Returns the list of entries to process
[ "Read", "the", "entries", "from", "a", "particular", "directory", "for", "processing" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/reader.rb#L134-L140
10,443
jekyll/jekyll
lib/jekyll/site.rb
Jekyll.Site.write
def write each_site_file do |item| item.write(dest) if regenerator.regenerate?(item) end regenerator.write_metadata Jekyll::Hooks.trigger :site, :post_write, self end
ruby
def write each_site_file do |item| item.write(dest) if regenerator.regenerate?(item) end regenerator.write_metadata Jekyll::Hooks.trigger :site, :post_write, self end
[ "def", "write", "each_site_file", "do", "|", "item", "|", "item", ".", "write", "(", "dest", ")", "if", "regenerator", ".", "regenerate?", "(", "item", ")", "end", "regenerator", ".", "write_metadata", "Jekyll", "::", "Hooks", ".", "trigger", ":site", ",", ":post_write", ",", "self", "end" ]
Write static files, pages, and posts. Returns nothing.
[ "Write", "static", "files", "pages", "and", "posts", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/site.rb#L217-L223
10,444
jekyll/jekyll
lib/jekyll/site.rb
Jekyll.Site.post_attr_hash
def post_attr_hash(post_attr) # Build a hash map based on the specified post attribute ( post attr => # array of posts ) then sort each array in reverse order. @post_attr_hash[post_attr] ||= begin hash = Hash.new { |h, key| h[key] = [] } posts.docs.each do |p| p.data[post_attr]&.each { |t| hash[t] << p } end hash.each_value { |posts| posts.sort!.reverse! } hash end end
ruby
def post_attr_hash(post_attr) # Build a hash map based on the specified post attribute ( post attr => # array of posts ) then sort each array in reverse order. @post_attr_hash[post_attr] ||= begin hash = Hash.new { |h, key| h[key] = [] } posts.docs.each do |p| p.data[post_attr]&.each { |t| hash[t] << p } end hash.each_value { |posts| posts.sort!.reverse! } hash end end
[ "def", "post_attr_hash", "(", "post_attr", ")", "# Build a hash map based on the specified post attribute ( post attr =>", "# array of posts ) then sort each array in reverse order.", "@post_attr_hash", "[", "post_attr", "]", "||=", "begin", "hash", "=", "Hash", ".", "new", "{", "|", "h", ",", "key", "|", "h", "[", "key", "]", "=", "[", "]", "}", "posts", ".", "docs", ".", "each", "do", "|", "p", "|", "p", ".", "data", "[", "post_attr", "]", "&.", "each", "{", "|", "t", "|", "hash", "[", "t", "]", "<<", "p", "}", "end", "hash", ".", "each_value", "{", "|", "posts", "|", "posts", ".", "sort!", ".", "reverse!", "}", "hash", "end", "end" ]
Construct a Hash of Posts indexed by the specified Post attribute. post_attr - The String name of the Post attribute. Examples post_attr_hash('categories') # => { 'tech' => [<Post A>, <Post B>], # 'ruby' => [<Post B>] } Returns the Hash: { attr => posts } where attr - One of the values for the requested attribute. posts - The Array of Posts with the given attr value.
[ "Construct", "a", "Hash", "of", "Posts", "indexed", "by", "the", "specified", "Post", "attribute", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/site.rb#L242-L253
10,445
jekyll/jekyll
lib/jekyll/site.rb
Jekyll.Site.find_converter_instance
def find_converter_instance(klass) @find_converter_instance ||= {} @find_converter_instance[klass] ||= begin converters.find { |converter| converter.instance_of?(klass) } || \ raise("No Converters found for #{klass}") end end
ruby
def find_converter_instance(klass) @find_converter_instance ||= {} @find_converter_instance[klass] ||= begin converters.find { |converter| converter.instance_of?(klass) } || \ raise("No Converters found for #{klass}") end end
[ "def", "find_converter_instance", "(", "klass", ")", "@find_converter_instance", "||=", "{", "}", "@find_converter_instance", "[", "klass", "]", "||=", "begin", "converters", ".", "find", "{", "|", "converter", "|", "converter", ".", "instance_of?", "(", "klass", ")", "}", "||", "raise", "(", "\"No Converters found for #{klass}\"", ")", "end", "end" ]
Get the implementation class for the given Converter. Returns the Converter instance implementing the given Converter. klass - The Class of the Converter to fetch.
[ "Get", "the", "implementation", "class", "for", "the", "given", "Converter", ".", "Returns", "the", "Converter", "instance", "implementing", "the", "given", "Converter", ".", "klass", "-", "The", "Class", "of", "the", "Converter", "to", "fetch", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/site.rb#L292-L298
10,446
jekyll/jekyll
lib/jekyll/site.rb
Jekyll.Site.instantiate_subclasses
def instantiate_subclasses(klass) klass.descendants.select { |c| !safe || c.safe }.sort.map do |c| c.new(config) end end
ruby
def instantiate_subclasses(klass) klass.descendants.select { |c| !safe || c.safe }.sort.map do |c| c.new(config) end end
[ "def", "instantiate_subclasses", "(", "klass", ")", "klass", ".", "descendants", ".", "select", "{", "|", "c", "|", "!", "safe", "||", "c", ".", "safe", "}", ".", "sort", ".", "map", "do", "|", "c", "|", "c", ".", "new", "(", "config", ")", "end", "end" ]
klass - class or module containing the subclasses. Returns array of instances of subclasses of parameter. Create array of instances of the subclasses of the class or module passed in as argument.
[ "klass", "-", "class", "or", "module", "containing", "the", "subclasses", ".", "Returns", "array", "of", "instances", "of", "subclasses", "of", "parameter", ".", "Create", "array", "of", "instances", "of", "the", "subclasses", "of", "the", "class", "or", "module", "passed", "in", "as", "argument", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/site.rb#L305-L309
10,447
jekyll/jekyll
lib/jekyll/site.rb
Jekyll.Site.documents
def documents @documents ||= collections.reduce(Set.new) do |docs, (_, collection)| docs + collection.docs + collection.files end.to_a end
ruby
def documents @documents ||= collections.reduce(Set.new) do |docs, (_, collection)| docs + collection.docs + collection.files end.to_a end
[ "def", "documents", "@documents", "||=", "collections", ".", "reduce", "(", "Set", ".", "new", ")", "do", "|", "docs", ",", "(", "_", ",", "collection", ")", "|", "docs", "+", "collection", ".", "docs", "+", "collection", ".", "files", "end", ".", "to_a", "end" ]
Get all the documents Returns an Array of all Documents
[ "Get", "all", "the", "documents" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/site.rb#L335-L339
10,448
jekyll/jekyll
lib/jekyll/site.rb
Jekyll.Site.configure_cache
def configure_cache Jekyll::Cache.cache_dir = in_source_dir(config["cache_dir"], "Jekyll/Cache") Jekyll::Cache.disable_disk_cache! if safe end
ruby
def configure_cache Jekyll::Cache.cache_dir = in_source_dir(config["cache_dir"], "Jekyll/Cache") Jekyll::Cache.disable_disk_cache! if safe end
[ "def", "configure_cache", "Jekyll", "::", "Cache", ".", "cache_dir", "=", "in_source_dir", "(", "config", "[", "\"cache_dir\"", "]", ",", "\"Jekyll/Cache\"", ")", "Jekyll", "::", "Cache", ".", "disable_disk_cache!", "if", "safe", "end" ]
Disable Marshaling cache to disk in Safe Mode
[ "Disable", "Marshaling", "cache", "to", "disk", "in", "Safe", "Mode" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/site.rb#L471-L474
10,449
jekyll/jekyll
lib/jekyll/frontmatter_defaults.rb
Jekyll.FrontmatterDefaults.find
def find(path, type, setting) value = nil old_scope = nil matching_sets(path, type).each do |set| if set["values"].key?(setting) && has_precedence?(old_scope, set["scope"]) value = set["values"][setting] old_scope = set["scope"] end end value end
ruby
def find(path, type, setting) value = nil old_scope = nil matching_sets(path, type).each do |set| if set["values"].key?(setting) && has_precedence?(old_scope, set["scope"]) value = set["values"][setting] old_scope = set["scope"] end end value end
[ "def", "find", "(", "path", ",", "type", ",", "setting", ")", "value", "=", "nil", "old_scope", "=", "nil", "matching_sets", "(", "path", ",", "type", ")", ".", "each", "do", "|", "set", "|", "if", "set", "[", "\"values\"", "]", ".", "key?", "(", "setting", ")", "&&", "has_precedence?", "(", "old_scope", ",", "set", "[", "\"scope\"", "]", ")", "value", "=", "set", "[", "\"values\"", "]", "[", "setting", "]", "old_scope", "=", "set", "[", "\"scope\"", "]", "end", "end", "value", "end" ]
Finds a default value for a given setting, filtered by path and type path - the path (relative to the source) of the page, post or :draft the default is used in type - a symbol indicating whether a :page, a :post or a :draft calls this method Returns the default value or nil if none was found
[ "Finds", "a", "default", "value", "for", "a", "given", "setting", "filtered", "by", "path", "and", "type" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/frontmatter_defaults.rb#L60-L71
10,450
jekyll/jekyll
lib/jekyll/frontmatter_defaults.rb
Jekyll.FrontmatterDefaults.all
def all(path, type) defaults = {} old_scope = nil matching_sets(path, type).each do |set| if has_precedence?(old_scope, set["scope"]) defaults = Utils.deep_merge_hashes(defaults, set["values"]) old_scope = set["scope"] else defaults = Utils.deep_merge_hashes(set["values"], defaults) end end defaults end
ruby
def all(path, type) defaults = {} old_scope = nil matching_sets(path, type).each do |set| if has_precedence?(old_scope, set["scope"]) defaults = Utils.deep_merge_hashes(defaults, set["values"]) old_scope = set["scope"] else defaults = Utils.deep_merge_hashes(set["values"], defaults) end end defaults end
[ "def", "all", "(", "path", ",", "type", ")", "defaults", "=", "{", "}", "old_scope", "=", "nil", "matching_sets", "(", "path", ",", "type", ")", ".", "each", "do", "|", "set", "|", "if", "has_precedence?", "(", "old_scope", ",", "set", "[", "\"scope\"", "]", ")", "defaults", "=", "Utils", ".", "deep_merge_hashes", "(", "defaults", ",", "set", "[", "\"values\"", "]", ")", "old_scope", "=", "set", "[", "\"scope\"", "]", "else", "defaults", "=", "Utils", ".", "deep_merge_hashes", "(", "set", "[", "\"values\"", "]", ",", "defaults", ")", "end", "end", "defaults", "end" ]
Collects a hash with all default values for a page or post path - the relative path of the page or post type - a symbol indicating the type (:post, :page or :draft) Returns a hash with all default values (an empty hash if there are none)
[ "Collects", "a", "hash", "with", "all", "default", "values", "for", "a", "page", "or", "post" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/frontmatter_defaults.rb#L79-L91
10,451
jekyll/jekyll
lib/jekyll/frontmatter_defaults.rb
Jekyll.FrontmatterDefaults.valid_sets
def valid_sets sets = @site.config["defaults"] return [] unless sets.is_a?(Array) sets.map do |set| if valid?(set) ensure_time!(update_deprecated_types(set)) else Jekyll.logger.warn "Defaults:", "An invalid front-matter default set was found:" Jekyll.logger.warn set.to_s nil end end.compact end
ruby
def valid_sets sets = @site.config["defaults"] return [] unless sets.is_a?(Array) sets.map do |set| if valid?(set) ensure_time!(update_deprecated_types(set)) else Jekyll.logger.warn "Defaults:", "An invalid front-matter default set was found:" Jekyll.logger.warn set.to_s nil end end.compact end
[ "def", "valid_sets", "sets", "=", "@site", ".", "config", "[", "\"defaults\"", "]", "return", "[", "]", "unless", "sets", ".", "is_a?", "(", "Array", ")", "sets", ".", "map", "do", "|", "set", "|", "if", "valid?", "(", "set", ")", "ensure_time!", "(", "update_deprecated_types", "(", "set", ")", ")", "else", "Jekyll", ".", "logger", ".", "warn", "\"Defaults:\"", ",", "\"An invalid front-matter default set was found:\"", "Jekyll", ".", "logger", ".", "warn", "set", ".", "to_s", "nil", "end", "end", ".", "compact", "end" ]
Returns a list of valid sets This is not cached to allow plugins to modify the configuration and have their changes take effect Returns an array of hashes
[ "Returns", "a", "list", "of", "valid", "sets" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/frontmatter_defaults.rb#L218-L231
10,452
jekyll/jekyll
lib/jekyll/cache.rb
Jekyll.Cache.[]
def [](key) return @cache[key] if @cache.key?(key) path = path_to(hash(key)) if disk_cache_enabled? && File.file?(path) && File.readable?(path) @cache[key] = load(path) else raise end end
ruby
def [](key) return @cache[key] if @cache.key?(key) path = path_to(hash(key)) if disk_cache_enabled? && File.file?(path) && File.readable?(path) @cache[key] = load(path) else raise end end
[ "def", "[]", "(", "key", ")", "return", "@cache", "[", "key", "]", "if", "@cache", ".", "key?", "(", "key", ")", "path", "=", "path_to", "(", "hash", "(", "key", ")", ")", "if", "disk_cache_enabled?", "&&", "File", ".", "file?", "(", "path", ")", "&&", "File", ".", "readable?", "(", "path", ")", "@cache", "[", "key", "]", "=", "load", "(", "path", ")", "else", "raise", "end", "end" ]
Retrieve a cached item Raises if key does not exist in cache Returns cached value
[ "Retrieve", "a", "cached", "item", "Raises", "if", "key", "does", "not", "exist", "in", "cache" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/cache.rb#L81-L90
10,453
jekyll/jekyll
lib/jekyll/cache.rb
Jekyll.Cache.[]=
def []=(key, value) @cache[key] = value return unless disk_cache_enabled? path = path_to(hash(key)) value = new Hash(value) if value.is_a?(Hash) && !value.default.nil? dump(path, value) rescue TypeError Jekyll.logger.debug "Cache:", "Cannot dump object #{key}" end
ruby
def []=(key, value) @cache[key] = value return unless disk_cache_enabled? path = path_to(hash(key)) value = new Hash(value) if value.is_a?(Hash) && !value.default.nil? dump(path, value) rescue TypeError Jekyll.logger.debug "Cache:", "Cannot dump object #{key}" end
[ "def", "[]=", "(", "key", ",", "value", ")", "@cache", "[", "key", "]", "=", "value", "return", "unless", "disk_cache_enabled?", "path", "=", "path_to", "(", "hash", "(", "key", ")", ")", "value", "=", "new", "Hash", "(", "value", ")", "if", "value", ".", "is_a?", "(", "Hash", ")", "&&", "!", "value", ".", "default", ".", "nil?", "dump", "(", "path", ",", "value", ")", "rescue", "TypeError", "Jekyll", ".", "logger", ".", "debug", "\"Cache:\"", ",", "\"Cannot dump object #{key}\"", "end" ]
Add an item to cache Returns nothing.
[ "Add", "an", "item", "to", "cache" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/cache.rb#L95-L104
10,454
jekyll/jekyll
lib/jekyll/cache.rb
Jekyll.Cache.delete
def delete(key) @cache.delete(key) File.delete(path_to(hash(key))) if disk_cache_enabled? end
ruby
def delete(key) @cache.delete(key) File.delete(path_to(hash(key))) if disk_cache_enabled? end
[ "def", "delete", "(", "key", ")", "@cache", ".", "delete", "(", "key", ")", "File", ".", "delete", "(", "path_to", "(", "hash", "(", "key", ")", ")", ")", "if", "disk_cache_enabled?", "end" ]
Remove one particular item from the cache Returns nothing.
[ "Remove", "one", "particular", "item", "from", "the", "cache" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/cache.rb#L119-L122
10,455
jekyll/jekyll
lib/jekyll/cache.rb
Jekyll.Cache.key?
def key?(key) # First, check if item is already cached in memory return true if @cache.key?(key) # Otherwise, it might be cached on disk # but we should not consider the disk cache if it is disabled return false unless disk_cache_enabled? path = path_to(hash(key)) File.file?(path) && File.readable?(path) end
ruby
def key?(key) # First, check if item is already cached in memory return true if @cache.key?(key) # Otherwise, it might be cached on disk # but we should not consider the disk cache if it is disabled return false unless disk_cache_enabled? path = path_to(hash(key)) File.file?(path) && File.readable?(path) end
[ "def", "key?", "(", "key", ")", "# First, check if item is already cached in memory", "return", "true", "if", "@cache", ".", "key?", "(", "key", ")", "# Otherwise, it might be cached on disk", "# but we should not consider the disk cache if it is disabled", "return", "false", "unless", "disk_cache_enabled?", "path", "=", "path_to", "(", "hash", "(", "key", ")", ")", "File", ".", "file?", "(", "path", ")", "&&", "File", ".", "readable?", "(", "path", ")", "end" ]
Check if `key` already exists in this cache Returns true if key exists in the cache, false otherwise
[ "Check", "if", "key", "already", "exists", "in", "this", "cache" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/cache.rb#L127-L136
10,456
jekyll/jekyll
lib/jekyll/cache.rb
Jekyll.Cache.path_to
def path_to(hash = nil) @base_dir ||= File.join(Jekyll::Cache.cache_dir, @name) return @base_dir if hash.nil? File.join(@base_dir, hash[0..1], hash[2..-1]).freeze end
ruby
def path_to(hash = nil) @base_dir ||= File.join(Jekyll::Cache.cache_dir, @name) return @base_dir if hash.nil? File.join(@base_dir, hash[0..1], hash[2..-1]).freeze end
[ "def", "path_to", "(", "hash", "=", "nil", ")", "@base_dir", "||=", "File", ".", "join", "(", "Jekyll", "::", "Cache", ".", "cache_dir", ",", "@name", ")", "return", "@base_dir", "if", "hash", ".", "nil?", "File", ".", "join", "(", "@base_dir", ",", "hash", "[", "0", "..", "1", "]", ",", "hash", "[", "2", "..", "-", "1", "]", ")", ".", "freeze", "end" ]
Given a hashed key, return the path to where this item would be saved on disk.
[ "Given", "a", "hashed", "key", "return", "the", "path", "to", "where", "this", "item", "would", "be", "saved", "on", "disk", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/cache.rb#L145-L150
10,457
jekyll/jekyll
lib/jekyll/convertible.rb
Jekyll.Convertible.render_liquid
def render_liquid(content, payload, info, path) _renderer.render_liquid(content, payload, info, path) end
ruby
def render_liquid(content, payload, info, path) _renderer.render_liquid(content, payload, info, path) end
[ "def", "render_liquid", "(", "content", ",", "payload", ",", "info", ",", "path", ")", "_renderer", ".", "render_liquid", "(", "content", ",", "payload", ",", "info", ",", "path", ")", "end" ]
Render Liquid in the content content - the raw Liquid content to render payload - the payload for Liquid info - the info for Liquid Returns the converted content
[ "Render", "Liquid", "in", "the", "content" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/convertible.rb#L107-L109
10,458
jekyll/jekyll
lib/jekyll/convertible.rb
Jekyll.Convertible.to_liquid
def to_liquid(attrs = nil) further_data = Hash[(attrs || self.class::ATTRIBUTES_FOR_LIQUID).map do |attribute| [attribute, send(attribute)] end] defaults = site.frontmatter_defaults.all(relative_path, type) Utils.deep_merge_hashes defaults, Utils.deep_merge_hashes(data, further_data) end
ruby
def to_liquid(attrs = nil) further_data = Hash[(attrs || self.class::ATTRIBUTES_FOR_LIQUID).map do |attribute| [attribute, send(attribute)] end] defaults = site.frontmatter_defaults.all(relative_path, type) Utils.deep_merge_hashes defaults, Utils.deep_merge_hashes(data, further_data) end
[ "def", "to_liquid", "(", "attrs", "=", "nil", ")", "further_data", "=", "Hash", "[", "(", "attrs", "||", "self", ".", "class", "::", "ATTRIBUTES_FOR_LIQUID", ")", ".", "map", "do", "|", "attribute", "|", "[", "attribute", ",", "send", "(", "attribute", ")", "]", "end", "]", "defaults", "=", "site", ".", "frontmatter_defaults", ".", "all", "(", "relative_path", ",", "type", ")", "Utils", ".", "deep_merge_hashes", "defaults", ",", "Utils", ".", "deep_merge_hashes", "(", "data", ",", "further_data", ")", "end" ]
Convert this Convertible's data to a Hash suitable for use by Liquid. Returns the Hash representation of this Convertible.
[ "Convert", "this", "Convertible", "s", "data", "to", "a", "Hash", "suitable", "for", "use", "by", "Liquid", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/convertible.rb#L114-L121
10,459
jekyll/jekyll
lib/jekyll/convertible.rb
Jekyll.Convertible.render_all_layouts
def render_all_layouts(layouts, payload, info) _renderer.layouts = layouts self.output = _renderer.place_in_layouts(output, payload, info) ensure @_renderer = nil # this will allow the modifications above to disappear end
ruby
def render_all_layouts(layouts, payload, info) _renderer.layouts = layouts self.output = _renderer.place_in_layouts(output, payload, info) ensure @_renderer = nil # this will allow the modifications above to disappear end
[ "def", "render_all_layouts", "(", "layouts", ",", "payload", ",", "info", ")", "_renderer", ".", "layouts", "=", "layouts", "self", ".", "output", "=", "_renderer", ".", "place_in_layouts", "(", "output", ",", "payload", ",", "info", ")", "ensure", "@_renderer", "=", "nil", "# this will allow the modifications above to disappear", "end" ]
Recursively render layouts layouts - a list of the layouts payload - the payload for Liquid info - the info for Liquid Returns nothing
[ "Recursively", "render", "layouts" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/convertible.rb#L192-L197
10,460
jekyll/jekyll
lib/jekyll/convertible.rb
Jekyll.Convertible.do_layout
def do_layout(payload, layouts) self.output = _renderer.tap do |renderer| renderer.layouts = layouts renderer.payload = payload end.run Jekyll.logger.debug "Post-Render Hooks:", relative_path Jekyll::Hooks.trigger hook_owner, :post_render, self ensure @_renderer = nil # this will allow the modifications above to disappear end
ruby
def do_layout(payload, layouts) self.output = _renderer.tap do |renderer| renderer.layouts = layouts renderer.payload = payload end.run Jekyll.logger.debug "Post-Render Hooks:", relative_path Jekyll::Hooks.trigger hook_owner, :post_render, self ensure @_renderer = nil # this will allow the modifications above to disappear end
[ "def", "do_layout", "(", "payload", ",", "layouts", ")", "self", ".", "output", "=", "_renderer", ".", "tap", "do", "|", "renderer", "|", "renderer", ".", "layouts", "=", "layouts", "renderer", ".", "payload", "=", "payload", "end", ".", "run", "Jekyll", ".", "logger", ".", "debug", "\"Post-Render Hooks:\"", ",", "relative_path", "Jekyll", "::", "Hooks", ".", "trigger", "hook_owner", ",", ":post_render", ",", "self", "ensure", "@_renderer", "=", "nil", "# this will allow the modifications above to disappear", "end" ]
Add any necessary layouts to this convertible document. payload - The site payload Drop or Hash. layouts - A Hash of {"name" => "layout"}. Returns nothing.
[ "Add", "any", "necessary", "layouts", "to", "this", "convertible", "document", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/convertible.rb#L205-L215
10,461
jekyll/jekyll
lib/jekyll/plugin_manager.rb
Jekyll.PluginManager.require_theme_deps
def require_theme_deps return false unless site.theme.runtime_dependencies site.theme.runtime_dependencies.each do |dep| next if dep.name == "jekyll" External.require_with_graceful_fail(dep.name) if plugin_allowed?(dep.name) end end
ruby
def require_theme_deps return false unless site.theme.runtime_dependencies site.theme.runtime_dependencies.each do |dep| next if dep.name == "jekyll" External.require_with_graceful_fail(dep.name) if plugin_allowed?(dep.name) end end
[ "def", "require_theme_deps", "return", "false", "unless", "site", ".", "theme", ".", "runtime_dependencies", "site", ".", "theme", ".", "runtime_dependencies", ".", "each", "do", "|", "dep", "|", "next", "if", "dep", ".", "name", "==", "\"jekyll\"", "External", ".", "require_with_graceful_fail", "(", "dep", ".", "name", ")", "if", "plugin_allowed?", "(", "dep", ".", "name", ")", "end", "end" ]
Require each of the runtime_dependencies specified by the theme's gemspec. Returns false only if no dependencies have been specified, otherwise nothing.
[ "Require", "each", "of", "the", "runtime_dependencies", "specified", "by", "the", "theme", "s", "gemspec", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/plugin_manager.rb#L38-L46
10,462
jekyll/jekyll
lib/jekyll/plugin_manager.rb
Jekyll.PluginManager.require_plugin_files
def require_plugin_files unless site.safe plugins_path.each do |plugin_search_path| plugin_files = Utils.safe_glob(plugin_search_path, File.join("**", "*.rb")) Jekyll::External.require_with_graceful_fail(plugin_files) end end end
ruby
def require_plugin_files unless site.safe plugins_path.each do |plugin_search_path| plugin_files = Utils.safe_glob(plugin_search_path, File.join("**", "*.rb")) Jekyll::External.require_with_graceful_fail(plugin_files) end end end
[ "def", "require_plugin_files", "unless", "site", ".", "safe", "plugins_path", ".", "each", "do", "|", "plugin_search_path", "|", "plugin_files", "=", "Utils", ".", "safe_glob", "(", "plugin_search_path", ",", "File", ".", "join", "(", "\"**\"", ",", "\"*.rb\"", ")", ")", "Jekyll", "::", "External", ".", "require_with_graceful_fail", "(", "plugin_files", ")", "end", "end", "end" ]
Require all .rb files if safe mode is off Returns nothing.
[ "Require", "all", ".", "rb", "files", "if", "safe", "mode", "is", "off" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/plugin_manager.rb#L85-L92
10,463
jekyll/jekyll
lib/jekyll/static_file.rb
Jekyll.StaticFile.path
def path # Static file is from a collection inside custom collections directory if !@collection.nil? && !@site.config["collections_dir"].empty? File.join(*[@base, @site.config["collections_dir"], @dir, @name].compact) else File.join(*[@base, @dir, @name].compact) end end
ruby
def path # Static file is from a collection inside custom collections directory if !@collection.nil? && !@site.config["collections_dir"].empty? File.join(*[@base, @site.config["collections_dir"], @dir, @name].compact) else File.join(*[@base, @dir, @name].compact) end end
[ "def", "path", "# Static file is from a collection inside custom collections directory", "if", "!", "@collection", ".", "nil?", "&&", "!", "@site", ".", "config", "[", "\"collections_dir\"", "]", ".", "empty?", "File", ".", "join", "(", "[", "@base", ",", "@site", ".", "config", "[", "\"collections_dir\"", "]", ",", "@dir", ",", "@name", "]", ".", "compact", ")", "else", "File", ".", "join", "(", "[", "@base", ",", "@dir", ",", "@name", "]", ".", "compact", ")", "end", "end" ]
Initialize a new StaticFile. site - The Site. base - The String path to the <source>. dir - The String path between <source> and the file. name - The String filename of the file. rubocop: disable ParameterLists rubocop: enable ParameterLists Returns source file path.
[ "Initialize", "a", "new", "StaticFile", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/static_file.rb#L42-L49
10,464
jekyll/jekyll
lib/jekyll/document.rb
Jekyll.Document.merge_data!
def merge_data!(other, source: "YAML front matter") merge_categories!(other) Utils.deep_merge_hashes!(data, other) merge_date!(source) data end
ruby
def merge_data!(other, source: "YAML front matter") merge_categories!(other) Utils.deep_merge_hashes!(data, other) merge_date!(source) data end
[ "def", "merge_data!", "(", "other", ",", "source", ":", "\"YAML front matter\"", ")", "merge_categories!", "(", "other", ")", "Utils", ".", "deep_merge_hashes!", "(", "data", ",", "other", ")", "merge_date!", "(", "source", ")", "data", "end" ]
Merge some data in with this document's data. Returns the merged data.
[ "Merge", "some", "data", "in", "with", "this", "document", "s", "data", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/document.rb#L59-L64
10,465
jekyll/jekyll
lib/jekyll/utils.rb
Jekyll.Utils.deep_merge_hashes!
def deep_merge_hashes!(target, overwrite) merge_values(target, overwrite) merge_default_proc(target, overwrite) duplicate_frozen_values(target) target end
ruby
def deep_merge_hashes!(target, overwrite) merge_values(target, overwrite) merge_default_proc(target, overwrite) duplicate_frozen_values(target) target end
[ "def", "deep_merge_hashes!", "(", "target", ",", "overwrite", ")", "merge_values", "(", "target", ",", "overwrite", ")", "merge_default_proc", "(", "target", ",", "overwrite", ")", "duplicate_frozen_values", "(", "target", ")", "target", "end" ]
Merges a master hash with another hash, recursively. master_hash - the "parent" hash whose values will be overridden other_hash - the other hash whose values will be persisted after the merge This code was lovingly stolen from some random gem: http://gemjack.com/gems/tartan-0.1.1/classes/Hash.html Thanks to whoever made it.
[ "Merges", "a", "master", "hash", "with", "another", "hash", "recursively", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/utils.rb#L41-L47
10,466
jekyll/jekyll
lib/jekyll/utils.rb
Jekyll.Utils.pluralized_array_from_hash
def pluralized_array_from_hash(hash, singular_key, plural_key) [].tap do |array| value = value_from_singular_key(hash, singular_key) value ||= value_from_plural_key(hash, plural_key) array << value end.flatten.compact end
ruby
def pluralized_array_from_hash(hash, singular_key, plural_key) [].tap do |array| value = value_from_singular_key(hash, singular_key) value ||= value_from_plural_key(hash, plural_key) array << value end.flatten.compact end
[ "def", "pluralized_array_from_hash", "(", "hash", ",", "singular_key", ",", "plural_key", ")", "[", "]", ".", "tap", "do", "|", "array", "|", "value", "=", "value_from_singular_key", "(", "hash", ",", "singular_key", ")", "value", "||=", "value_from_plural_key", "(", "hash", ",", "plural_key", ")", "array", "<<", "value", "end", ".", "flatten", ".", "compact", "end" ]
Read array from the supplied hash favouring the singular key and then the plural key, and handling any nil entries. hash - the hash to read from singular_key - the singular key plural_key - the plural key Returns an array
[ "Read", "array", "from", "the", "supplied", "hash", "favouring", "the", "singular", "key", "and", "then", "the", "plural", "key", "and", "handling", "any", "nil", "entries", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/utils.rb#L70-L76
10,467
jekyll/jekyll
lib/jekyll/utils.rb
Jekyll.Utils.has_liquid_construct?
def has_liquid_construct?(content) return false if content.nil? || content.empty? content.include?("{%") || content.include?("{{") end
ruby
def has_liquid_construct?(content) return false if content.nil? || content.empty? content.include?("{%") || content.include?("{{") end
[ "def", "has_liquid_construct?", "(", "content", ")", "return", "false", "if", "content", ".", "nil?", "||", "content", ".", "empty?", "content", ".", "include?", "(", "\"{%\"", ")", "||", "content", ".", "include?", "(", "\"{{\"", ")", "end" ]
Determine whether the given content string contains Liquid Tags or Vaiables Returns true is the string contains sequences of `{%` or `{{`
[ "Determine", "whether", "the", "given", "content", "string", "contains", "Liquid", "Tags", "or", "Vaiables" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/utils.rb#L146-L150
10,468
jekyll/jekyll
lib/jekyll/utils.rb
Jekyll.Utils.add_permalink_suffix
def add_permalink_suffix(template, permalink_style) template = template.dup case permalink_style when :pretty template << "/" when :date, :ordinal, :none template << ":output_ext" else template << "/" if permalink_style.to_s.end_with?("/") template << ":output_ext" if permalink_style.to_s.end_with?(":output_ext") end template end
ruby
def add_permalink_suffix(template, permalink_style) template = template.dup case permalink_style when :pretty template << "/" when :date, :ordinal, :none template << ":output_ext" else template << "/" if permalink_style.to_s.end_with?("/") template << ":output_ext" if permalink_style.to_s.end_with?(":output_ext") end template end
[ "def", "add_permalink_suffix", "(", "template", ",", "permalink_style", ")", "template", "=", "template", ".", "dup", "case", "permalink_style", "when", ":pretty", "template", "<<", "\"/\"", "when", ":date", ",", ":ordinal", ",", ":none", "template", "<<", "\":output_ext\"", "else", "template", "<<", "\"/\"", "if", "permalink_style", ".", "to_s", ".", "end_with?", "(", "\"/\"", ")", "template", "<<", "\":output_ext\"", "if", "permalink_style", ".", "to_s", ".", "end_with?", "(", "\":output_ext\"", ")", "end", "template", "end" ]
Add an appropriate suffix to template so that it matches the specified permalink style. template - permalink template without trailing slash or file extension permalink_style - permalink style, either built-in or custom The returned permalink template will use the same ending style as specified in permalink_style. For example, if permalink_style contains a trailing slash (or is :pretty, which indirectly has a trailing slash), then so will the returned template. If permalink_style has a trailing ":output_ext" (or is :none, :date, or :ordinal) then so will the returned template. Otherwise, template will be returned without modification. Examples: add_permalink_suffix("/:basename", :pretty) # => "/:basename/" add_permalink_suffix("/:basename", :date) # => "/:basename:output_ext" add_permalink_suffix("/:basename", "/:year/:month/:title/") # => "/:basename/" add_permalink_suffix("/:basename", "/:year/:month/:title") # => "/:basename" Returns the updated permalink template
[ "Add", "an", "appropriate", "suffix", "to", "template", "so", "that", "it", "matches", "the", "specified", "permalink", "style", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/utils.rb#L249-L263
10,469
jekyll/jekyll
lib/jekyll/utils.rb
Jekyll.Utils.replace_character_sequence_with_hyphen
def replace_character_sequence_with_hyphen(string, mode: "default") replaceable_char = case mode when "raw" SLUGIFY_RAW_REGEXP when "pretty" # "._~!$&'()+,;=@" is human readable (not URI-escaped) in URL # and is allowed in both extN and NTFS. SLUGIFY_PRETTY_REGEXP when "ascii" # For web servers not being able to handle Unicode, the safe # method is to ditch anything else but latin letters and numeric # digits. SLUGIFY_ASCII_REGEXP else SLUGIFY_DEFAULT_REGEXP end # Strip according to the mode string.gsub(replaceable_char, "-") end
ruby
def replace_character_sequence_with_hyphen(string, mode: "default") replaceable_char = case mode when "raw" SLUGIFY_RAW_REGEXP when "pretty" # "._~!$&'()+,;=@" is human readable (not URI-escaped) in URL # and is allowed in both extN and NTFS. SLUGIFY_PRETTY_REGEXP when "ascii" # For web servers not being able to handle Unicode, the safe # method is to ditch anything else but latin letters and numeric # digits. SLUGIFY_ASCII_REGEXP else SLUGIFY_DEFAULT_REGEXP end # Strip according to the mode string.gsub(replaceable_char, "-") end
[ "def", "replace_character_sequence_with_hyphen", "(", "string", ",", "mode", ":", "\"default\"", ")", "replaceable_char", "=", "case", "mode", "when", "\"raw\"", "SLUGIFY_RAW_REGEXP", "when", "\"pretty\"", "# \"._~!$&'()+,;=@\" is human readable (not URI-escaped) in URL", "# and is allowed in both extN and NTFS.", "SLUGIFY_PRETTY_REGEXP", "when", "\"ascii\"", "# For web servers not being able to handle Unicode, the safe", "# method is to ditch anything else but latin letters and numeric", "# digits.", "SLUGIFY_ASCII_REGEXP", "else", "SLUGIFY_DEFAULT_REGEXP", "end", "# Strip according to the mode", "string", ".", "gsub", "(", "replaceable_char", ",", "\"-\"", ")", "end" ]
Replace each character sequence with a hyphen. See Utils#slugify for a description of the character sequence specified by each mode.
[ "Replace", "each", "character", "sequence", "with", "a", "hyphen", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/utils.rb#L342-L362
10,470
jekyll/jekyll
lib/jekyll/page.rb
Jekyll.Page.process
def process(name) self.ext = File.extname(name) self.basename = name[0..-ext.length - 1].gsub(%r!\.*\z!, "") end
ruby
def process(name) self.ext = File.extname(name) self.basename = name[0..-ext.length - 1].gsub(%r!\.*\z!, "") end
[ "def", "process", "(", "name", ")", "self", ".", "ext", "=", "File", ".", "extname", "(", "name", ")", "self", ".", "basename", "=", "name", "[", "0", "..", "-", "ext", ".", "length", "-", "1", "]", ".", "gsub", "(", "%r!", "\\.", "\\z", "!", ",", "\"\"", ")", "end" ]
Extract information from the page filename. name - The String filename of the page file. NOTE: `String#gsub` removes all trailing periods (in comparison to `String#chomp`) Returns nothing.
[ "Extract", "information", "from", "the", "page", "filename", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/page.rb#L121-L124
10,471
jekyll/jekyll
lib/jekyll/page.rb
Jekyll.Page.render
def render(layouts, site_payload) site_payload["page"] = to_liquid site_payload["paginator"] = pager.to_liquid do_layout(site_payload, layouts) end
ruby
def render(layouts, site_payload) site_payload["page"] = to_liquid site_payload["paginator"] = pager.to_liquid do_layout(site_payload, layouts) end
[ "def", "render", "(", "layouts", ",", "site_payload", ")", "site_payload", "[", "\"page\"", "]", "=", "to_liquid", "site_payload", "[", "\"paginator\"", "]", "=", "pager", ".", "to_liquid", "do_layout", "(", "site_payload", ",", "layouts", ")", "end" ]
Add any necessary layouts to this post layouts - The Hash of {"name" => "layout"}. site_payload - The site payload Hash. Returns String rendered page.
[ "Add", "any", "necessary", "layouts", "to", "this", "post" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/page.rb#L132-L137
10,472
jekyll/jekyll
lib/jekyll/filters.rb
Jekyll.Filters.where_exp
def where_exp(input, variable, expression) return input unless input.respond_to?(:select) input = input.values if input.is_a?(Hash) # FIXME condition = parse_condition(expression) @context.stack do input.select do |object| @context[variable] = object condition.evaluate(@context) end end || [] end
ruby
def where_exp(input, variable, expression) return input unless input.respond_to?(:select) input = input.values if input.is_a?(Hash) # FIXME condition = parse_condition(expression) @context.stack do input.select do |object| @context[variable] = object condition.evaluate(@context) end end || [] end
[ "def", "where_exp", "(", "input", ",", "variable", ",", "expression", ")", "return", "input", "unless", "input", ".", "respond_to?", "(", ":select", ")", "input", "=", "input", ".", "values", "if", "input", ".", "is_a?", "(", "Hash", ")", "# FIXME", "condition", "=", "parse_condition", "(", "expression", ")", "@context", ".", "stack", "do", "input", ".", "select", "do", "|", "object", "|", "@context", "[", "variable", "]", "=", "object", "condition", ".", "evaluate", "(", "@context", ")", "end", "end", "||", "[", "]", "end" ]
Filters an array of objects against an expression input - the object array variable - the variable to assign each item to in the expression expression - a Liquid comparison expression passed in as a string Returns the filtered array of objects
[ "Filters", "an", "array", "of", "objects", "against", "an", "expression" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/filters.rb#L199-L211
10,473
jekyll/jekyll
lib/jekyll/filters.rb
Jekyll.Filters.sort
def sort(input, property = nil, nils = "first") raise ArgumentError, "Cannot sort a null object." if input.nil? if property.nil? input.sort else if nils == "first" order = - 1 elsif nils == "last" order = + 1 else raise ArgumentError, "Invalid nils order: " \ "'#{nils}' is not a valid nils order. It must be 'first' or 'last'." end sort_input(input, property, order) end end
ruby
def sort(input, property = nil, nils = "first") raise ArgumentError, "Cannot sort a null object." if input.nil? if property.nil? input.sort else if nils == "first" order = - 1 elsif nils == "last" order = + 1 else raise ArgumentError, "Invalid nils order: " \ "'#{nils}' is not a valid nils order. It must be 'first' or 'last'." end sort_input(input, property, order) end end
[ "def", "sort", "(", "input", ",", "property", "=", "nil", ",", "nils", "=", "\"first\"", ")", "raise", "ArgumentError", ",", "\"Cannot sort a null object.\"", "if", "input", ".", "nil?", "if", "property", ".", "nil?", "input", ".", "sort", "else", "if", "nils", "==", "\"first\"", "order", "=", "-", "1", "elsif", "nils", "==", "\"last\"", "order", "=", "+", "1", "else", "raise", "ArgumentError", ",", "\"Invalid nils order: \"", "\"'#{nils}' is not a valid nils order. It must be 'first' or 'last'.\"", "end", "sort_input", "(", "input", ",", "property", ",", "order", ")", "end", "end" ]
Sort an array of objects input - the object array property - property within each object to filter by nils ('first' | 'last') - nils appear before or after non-nil values Returns the filtered array of objects
[ "Sort", "an", "array", "of", "objects" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/filters.rb#L232-L249
10,474
jekyll/jekyll
lib/jekyll/filters.rb
Jekyll.Filters.sort_input
def sort_input(input, property, order) input.map { |item| [item_property(item, property), item] } .sort! do |a_info, b_info| a_property = a_info.first b_property = b_info.first if !a_property.nil? && b_property.nil? - order elsif a_property.nil? && !b_property.nil? + order else a_property <=> b_property || a_property.to_s <=> b_property.to_s end end .map!(&:last) end
ruby
def sort_input(input, property, order) input.map { |item| [item_property(item, property), item] } .sort! do |a_info, b_info| a_property = a_info.first b_property = b_info.first if !a_property.nil? && b_property.nil? - order elsif a_property.nil? && !b_property.nil? + order else a_property <=> b_property || a_property.to_s <=> b_property.to_s end end .map!(&:last) end
[ "def", "sort_input", "(", "input", ",", "property", ",", "order", ")", "input", ".", "map", "{", "|", "item", "|", "[", "item_property", "(", "item", ",", "property", ")", ",", "item", "]", "}", ".", "sort!", "do", "|", "a_info", ",", "b_info", "|", "a_property", "=", "a_info", ".", "first", "b_property", "=", "b_info", ".", "first", "if", "!", "a_property", ".", "nil?", "&&", "b_property", ".", "nil?", "-", "order", "elsif", "a_property", ".", "nil?", "&&", "!", "b_property", ".", "nil?", "+", "order", "else", "a_property", "<=>", "b_property", "||", "a_property", ".", "to_s", "<=>", "b_property", ".", "to_s", "end", "end", ".", "map!", "(", ":last", ")", "end" ]
Sort the input Enumerable by the given property. If the property doesn't exist, return the sort order respective of which item doesn't have the property. We also utilize the Schwartzian transform to make this more efficient.
[ "Sort", "the", "input", "Enumerable", "by", "the", "given", "property", ".", "If", "the", "property", "doesn", "t", "exist", "return", "the", "sort", "order", "respective", "of", "which", "item", "doesn", "t", "have", "the", "property", ".", "We", "also", "utilize", "the", "Schwartzian", "transform", "to", "make", "this", "more", "efficient", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/filters.rb#L311-L326
10,475
jekyll/jekyll
lib/jekyll/filters.rb
Jekyll.Filters.compare_property_vs_target
def compare_property_vs_target(property, target) case target when NilClass return true if property.nil? when Liquid::Expression::MethodLiteral # `empty` or `blank` return true if Array(property).join == target.to_s else Array(property).each do |prop| return true if prop.to_s == target.to_s end end false end
ruby
def compare_property_vs_target(property, target) case target when NilClass return true if property.nil? when Liquid::Expression::MethodLiteral # `empty` or `blank` return true if Array(property).join == target.to_s else Array(property).each do |prop| return true if prop.to_s == target.to_s end end false end
[ "def", "compare_property_vs_target", "(", "property", ",", "target", ")", "case", "target", "when", "NilClass", "return", "true", "if", "property", ".", "nil?", "when", "Liquid", "::", "Expression", "::", "MethodLiteral", "# `empty` or `blank`", "return", "true", "if", "Array", "(", "property", ")", ".", "join", "==", "target", ".", "to_s", "else", "Array", "(", "property", ")", ".", "each", "do", "|", "prop", "|", "return", "true", "if", "prop", ".", "to_s", "==", "target", ".", "to_s", "end", "end", "false", "end" ]
`where` filter helper
[ "where", "filter", "helper" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/filters.rb#L329-L342
10,476
jekyll/jekyll
lib/jekyll/collection.rb
Jekyll.Collection.entries
def entries return [] unless exists? @entries ||= Utils.safe_glob(collection_dir, ["**", "*"], File::FNM_DOTMATCH).map do |entry| entry["#{collection_dir}/"] = "" entry end end
ruby
def entries return [] unless exists? @entries ||= Utils.safe_glob(collection_dir, ["**", "*"], File::FNM_DOTMATCH).map do |entry| entry["#{collection_dir}/"] = "" entry end end
[ "def", "entries", "return", "[", "]", "unless", "exists?", "@entries", "||=", "Utils", ".", "safe_glob", "(", "collection_dir", ",", "[", "\"**\"", ",", "\"*\"", "]", ",", "File", "::", "FNM_DOTMATCH", ")", ".", "map", "do", "|", "entry", "|", "entry", "[", "\"#{collection_dir}/\"", "]", "=", "\"\"", "entry", "end", "end" ]
All the entries in this collection. Returns an Array of file paths to the documents in this collection relative to the collection's directory
[ "All", "the", "entries", "in", "this", "collection", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/collection.rb#L75-L83
10,477
jekyll/jekyll
lib/jekyll/collection.rb
Jekyll.Collection.collection_dir
def collection_dir(*files) return directory if files.empty? site.in_source_dir(container, relative_directory, *files) end
ruby
def collection_dir(*files) return directory if files.empty? site.in_source_dir(container, relative_directory, *files) end
[ "def", "collection_dir", "(", "*", "files", ")", "return", "directory", "if", "files", ".", "empty?", "site", ".", "in_source_dir", "(", "container", ",", "relative_directory", ",", "files", ")", "end" ]
The full path to the directory containing the collection, with optional subpaths. *files - (optional) any other path pieces relative to the directory to append to the path Returns a String containing th directory name where the collection is stored on the filesystem.
[ "The", "full", "path", "to", "the", "directory", "containing", "the", "collection", "with", "optional", "subpaths", "." ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/collection.rb#L128-L132
10,478
jekyll/jekyll
lib/jekyll/regenerator.rb
Jekyll.Regenerator.add
def add(path) return true unless File.exist?(path) metadata[path] = { "mtime" => File.mtime(path), "deps" => [], } cache[path] = true end
ruby
def add(path) return true unless File.exist?(path) metadata[path] = { "mtime" => File.mtime(path), "deps" => [], } cache[path] = true end
[ "def", "add", "(", "path", ")", "return", "true", "unless", "File", ".", "exist?", "(", "path", ")", "metadata", "[", "path", "]", "=", "{", "\"mtime\"", "=>", "File", ".", "mtime", "(", "path", ")", ",", "\"deps\"", "=>", "[", "]", ",", "}", "cache", "[", "path", "]", "=", "true", "end" ]
Add a path to the metadata Returns true, also on failure.
[ "Add", "a", "path", "to", "the", "metadata" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/regenerator.rb#L40-L48
10,479
jekyll/jekyll
lib/jekyll/regenerator.rb
Jekyll.Regenerator.add_dependency
def add_dependency(path, dependency) return if metadata[path].nil? || disabled unless metadata[path]["deps"].include? dependency metadata[path]["deps"] << dependency add(dependency) unless metadata.include?(dependency) end regenerate? dependency end
ruby
def add_dependency(path, dependency) return if metadata[path].nil? || disabled unless metadata[path]["deps"].include? dependency metadata[path]["deps"] << dependency add(dependency) unless metadata.include?(dependency) end regenerate? dependency end
[ "def", "add_dependency", "(", "path", ",", "dependency", ")", "return", "if", "metadata", "[", "path", "]", ".", "nil?", "||", "disabled", "unless", "metadata", "[", "path", "]", "[", "\"deps\"", "]", ".", "include?", "dependency", "metadata", "[", "path", "]", "[", "\"deps\"", "]", "<<", "dependency", "add", "(", "dependency", ")", "unless", "metadata", ".", "include?", "(", "dependency", ")", "end", "regenerate?", "dependency", "end" ]
Add a dependency of a path Returns nothing.
[ "Add", "a", "dependency", "of", "a", "path" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/regenerator.rb#L106-L114
10,480
jekyll/jekyll
lib/jekyll/regenerator.rb
Jekyll.Regenerator.write_metadata
def write_metadata unless disabled? Jekyll.logger.debug "Writing Metadata:", ".jekyll-metadata" File.binwrite(metadata_file, Marshal.dump(metadata)) end end
ruby
def write_metadata unless disabled? Jekyll.logger.debug "Writing Metadata:", ".jekyll-metadata" File.binwrite(metadata_file, Marshal.dump(metadata)) end end
[ "def", "write_metadata", "unless", "disabled?", "Jekyll", ".", "logger", ".", "debug", "\"Writing Metadata:\"", ",", "\".jekyll-metadata\"", "File", ".", "binwrite", "(", "metadata_file", ",", "Marshal", ".", "dump", "(", "metadata", ")", ")", "end", "end" ]
Write the metadata to disk Returns nothing.
[ "Write", "the", "metadata", "to", "disk" ]
fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b
https://github.com/jekyll/jekyll/blob/fd74fe3e93a1fb506fa6621a2e271d7b9c5c3e3b/lib/jekyll/regenerator.rb#L119-L124
10,481
fastlane/fastlane
frameit/lib/frameit/config_parser.rb
Frameit.ConfigParser.fetch_value
def fetch_value(path) specifics = @data['data'].select { |a| path.include?(a['filter']) } default = @data['default'] values = default.clone specifics.each do |specific| values = values.fastlane_deep_merge(specific) end change_paths_to_absolutes!(values) validate_values(values) values end
ruby
def fetch_value(path) specifics = @data['data'].select { |a| path.include?(a['filter']) } default = @data['default'] values = default.clone specifics.each do |specific| values = values.fastlane_deep_merge(specific) end change_paths_to_absolutes!(values) validate_values(values) values end
[ "def", "fetch_value", "(", "path", ")", "specifics", "=", "@data", "[", "'data'", "]", ".", "select", "{", "|", "a", "|", "path", ".", "include?", "(", "a", "[", "'filter'", "]", ")", "}", "default", "=", "@data", "[", "'default'", "]", "values", "=", "default", ".", "clone", "specifics", ".", "each", "do", "|", "specific", "|", "values", "=", "values", ".", "fastlane_deep_merge", "(", "specific", ")", "end", "change_paths_to_absolutes!", "(", "values", ")", "validate_values", "(", "values", ")", "values", "end" ]
Fetches the finished configuration for a given path. This will try to look for a specific value and fallback to a default value if nothing was found
[ "Fetches", "the", "finished", "configuration", "for", "a", "given", "path", ".", "This", "will", "try", "to", "look", "for", "a", "specific", "value", "and", "fallback", "to", "a", "default", "value", "if", "nothing", "was", "found" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/config_parser.rb#L28-L42
10,482
fastlane/fastlane
frameit/lib/frameit/config_parser.rb
Frameit.ConfigParser.change_paths_to_absolutes!
def change_paths_to_absolutes!(values) values.each do |key, value| if value.kind_of?(Hash) change_paths_to_absolutes!(value) # recursive call elsif value.kind_of?(Array) value.each do |current| change_paths_to_absolutes!(current) if current.kind_of?(Hash) # recursive call end else if ['font', 'background'].include?(key) # Change the paths to relative ones # `replace`: to change the content of the string, so it's actually stored if @path # where is the config file. We don't have a config file in tests containing_folder = File.expand_path('..', @path) value.replace(File.join(containing_folder, value)) end end end end end
ruby
def change_paths_to_absolutes!(values) values.each do |key, value| if value.kind_of?(Hash) change_paths_to_absolutes!(value) # recursive call elsif value.kind_of?(Array) value.each do |current| change_paths_to_absolutes!(current) if current.kind_of?(Hash) # recursive call end else if ['font', 'background'].include?(key) # Change the paths to relative ones # `replace`: to change the content of the string, so it's actually stored if @path # where is the config file. We don't have a config file in tests containing_folder = File.expand_path('..', @path) value.replace(File.join(containing_folder, value)) end end end end end
[ "def", "change_paths_to_absolutes!", "(", "values", ")", "values", ".", "each", "do", "|", "key", ",", "value", "|", "if", "value", ".", "kind_of?", "(", "Hash", ")", "change_paths_to_absolutes!", "(", "value", ")", "# recursive call", "elsif", "value", ".", "kind_of?", "(", "Array", ")", "value", ".", "each", "do", "|", "current", "|", "change_paths_to_absolutes!", "(", "current", ")", "if", "current", ".", "kind_of?", "(", "Hash", ")", "# recursive call", "end", "else", "if", "[", "'font'", ",", "'background'", "]", ".", "include?", "(", "key", ")", "# Change the paths to relative ones", "# `replace`: to change the content of the string, so it's actually stored", "if", "@path", "# where is the config file. We don't have a config file in tests", "containing_folder", "=", "File", ".", "expand_path", "(", "'..'", ",", "@path", ")", "value", ".", "replace", "(", "File", ".", "join", "(", "containing_folder", ",", "value", ")", ")", "end", "end", "end", "end", "end" ]
Use absolute paths instead of relative
[ "Use", "absolute", "paths", "instead", "of", "relative" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/config_parser.rb#L45-L64
10,483
fastlane/fastlane
spaceship/lib/spaceship/portal/portal_client.rb
Spaceship.PortalClient.provisioning_profiles_via_xcode_api
def provisioning_profiles_via_xcode_api(mac: false) req = request(:post) do |r| r.url("https://developerservices2.apple.com/services/#{PROTOCOL_VERSION}/#{platform_slug(mac)}/listProvisioningProfiles.action") r.params = { teamId: team_id, includeInactiveProfiles: true, onlyCountLists: true } end result = parse_response(req, 'provisioningProfiles') csrf_cache[Spaceship::Portal::ProvisioningProfile] = self.csrf_tokens result end
ruby
def provisioning_profiles_via_xcode_api(mac: false) req = request(:post) do |r| r.url("https://developerservices2.apple.com/services/#{PROTOCOL_VERSION}/#{platform_slug(mac)}/listProvisioningProfiles.action") r.params = { teamId: team_id, includeInactiveProfiles: true, onlyCountLists: true } end result = parse_response(req, 'provisioningProfiles') csrf_cache[Spaceship::Portal::ProvisioningProfile] = self.csrf_tokens result end
[ "def", "provisioning_profiles_via_xcode_api", "(", "mac", ":", "false", ")", "req", "=", "request", "(", ":post", ")", "do", "|", "r", "|", "r", ".", "url", "(", "\"https://developerservices2.apple.com/services/#{PROTOCOL_VERSION}/#{platform_slug(mac)}/listProvisioningProfiles.action\"", ")", "r", ".", "params", "=", "{", "teamId", ":", "team_id", ",", "includeInactiveProfiles", ":", "true", ",", "onlyCountLists", ":", "true", "}", "end", "result", "=", "parse_response", "(", "req", ",", "'provisioningProfiles'", ")", "csrf_cache", "[", "Spaceship", "::", "Portal", "::", "ProvisioningProfile", "]", "=", "self", ".", "csrf_tokens", "result", "end" ]
this endpoint is used by Xcode to fetch provisioning profiles. The response is an xml plist but has the added benefit of containing the appId of each provisioning profile. Use this method over `provisioning_profiles` if possible because no secondary API calls are necessary to populate the ProvisioningProfile data model.
[ "this", "endpoint", "is", "used", "by", "Xcode", "to", "fetch", "provisioning", "profiles", ".", "The", "response", "is", "an", "xml", "plist", "but", "has", "the", "added", "benefit", "of", "containing", "the", "appId", "of", "each", "provisioning", "profile", "." ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/spaceship/lib/spaceship/portal/portal_client.rb#L645-L660
10,484
fastlane/fastlane
spaceship/lib/spaceship/portal/portal_client.rb
Spaceship.PortalClient.ensure_csrf
def ensure_csrf(klass) if csrf_cache[klass] self.csrf_tokens = csrf_cache[klass] return end self.csrf_tokens = nil # If we directly create a new resource (e.g. app) without querying anything before # we don't have a valid csrf token, that's why we have to do at least one request block_given? ? yield : klass.all csrf_cache[klass] = self.csrf_tokens end
ruby
def ensure_csrf(klass) if csrf_cache[klass] self.csrf_tokens = csrf_cache[klass] return end self.csrf_tokens = nil # If we directly create a new resource (e.g. app) without querying anything before # we don't have a valid csrf token, that's why we have to do at least one request block_given? ? yield : klass.all csrf_cache[klass] = self.csrf_tokens end
[ "def", "ensure_csrf", "(", "klass", ")", "if", "csrf_cache", "[", "klass", "]", "self", ".", "csrf_tokens", "=", "csrf_cache", "[", "klass", "]", "return", "end", "self", ".", "csrf_tokens", "=", "nil", "# If we directly create a new resource (e.g. app) without querying anything before", "# we don't have a valid csrf token, that's why we have to do at least one request", "block_given?", "?", "yield", ":", "klass", ".", "all", "csrf_cache", "[", "klass", "]", "=", "self", ".", "csrf_tokens", "end" ]
Ensures that there are csrf tokens for the appropriate entity type Relies on store_csrf_tokens to set csrf_tokens to the appropriate value then stores that in the correct place in cache This method also takes a block, if you want to send a custom request, instead of calling `.all` on the given klass. This is used for provisioning profiles.
[ "Ensures", "that", "there", "are", "csrf", "tokens", "for", "the", "appropriate", "entity", "type", "Relies", "on", "store_csrf_tokens", "to", "set", "csrf_tokens", "to", "the", "appropriate", "value", "then", "stores", "that", "in", "the", "correct", "place", "in", "cache", "This", "method", "also", "takes", "a", "block", "if", "you", "want", "to", "send", "a", "custom", "request", "instead", "of", "calling", ".", "all", "on", "the", "given", "klass", ".", "This", "is", "used", "for", "provisioning", "profiles", "." ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/spaceship/lib/spaceship/portal/portal_client.rb#L802-L815
10,485
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.put_into_frame
def put_into_frame # We have to rotate the screenshot, since the offset information is for portrait # only. Instead of doing the calculations ourselves, it's much easier to let # imagemagick do the hard lifting for landscape screenshots rotation = self.rotation_for_device_orientation frame.rotate(-rotation) @image.rotate(-rotation) # Debug Mode: Add filename to frame if self.debug_mode filename = File.basename(@frame_path, ".*") filename.sub!('Apple', '') # remove 'Apple' width = screenshot.size[0] font_size = width / 20 # magic number that works well offset_top = offset['offset'].split("+")[2].to_f annotate_offset = "+0+#{offset_top}" # magic number that works semi well frame.combine_options do |c| c.gravity('North') c.undercolor('#00000080') c.fill('white') c.pointsize(font_size) c.annotate(annotate_offset.to_s, filename.to_s) end end @image = frame.composite(image, "png") do |c| c.compose("DstOver") c.geometry(offset['offset']) end # Revert the rotation from above frame.rotate(rotation) @image.rotate(rotation) end
ruby
def put_into_frame # We have to rotate the screenshot, since the offset information is for portrait # only. Instead of doing the calculations ourselves, it's much easier to let # imagemagick do the hard lifting for landscape screenshots rotation = self.rotation_for_device_orientation frame.rotate(-rotation) @image.rotate(-rotation) # Debug Mode: Add filename to frame if self.debug_mode filename = File.basename(@frame_path, ".*") filename.sub!('Apple', '') # remove 'Apple' width = screenshot.size[0] font_size = width / 20 # magic number that works well offset_top = offset['offset'].split("+")[2].to_f annotate_offset = "+0+#{offset_top}" # magic number that works semi well frame.combine_options do |c| c.gravity('North') c.undercolor('#00000080') c.fill('white') c.pointsize(font_size) c.annotate(annotate_offset.to_s, filename.to_s) end end @image = frame.composite(image, "png") do |c| c.compose("DstOver") c.geometry(offset['offset']) end # Revert the rotation from above frame.rotate(rotation) @image.rotate(rotation) end
[ "def", "put_into_frame", "# We have to rotate the screenshot, since the offset information is for portrait", "# only. Instead of doing the calculations ourselves, it's much easier to let", "# imagemagick do the hard lifting for landscape screenshots", "rotation", "=", "self", ".", "rotation_for_device_orientation", "frame", ".", "rotate", "(", "-", "rotation", ")", "@image", ".", "rotate", "(", "-", "rotation", ")", "# Debug Mode: Add filename to frame", "if", "self", ".", "debug_mode", "filename", "=", "File", ".", "basename", "(", "@frame_path", ",", "\".*\"", ")", "filename", ".", "sub!", "(", "'Apple'", ",", "''", ")", "# remove 'Apple'", "width", "=", "screenshot", ".", "size", "[", "0", "]", "font_size", "=", "width", "/", "20", "# magic number that works well", "offset_top", "=", "offset", "[", "'offset'", "]", ".", "split", "(", "\"+\"", ")", "[", "2", "]", ".", "to_f", "annotate_offset", "=", "\"+0+#{offset_top}\"", "# magic number that works semi well", "frame", ".", "combine_options", "do", "|", "c", "|", "c", ".", "gravity", "(", "'North'", ")", "c", ".", "undercolor", "(", "'#00000080'", ")", "c", ".", "fill", "(", "'white'", ")", "c", ".", "pointsize", "(", "font_size", ")", "c", ".", "annotate", "(", "annotate_offset", ".", "to_s", ",", "filename", ".", "to_s", ")", "end", "end", "@image", "=", "frame", ".", "composite", "(", "image", ",", "\"png\"", ")", "do", "|", "c", "|", "c", ".", "compose", "(", "\"DstOver\"", ")", "c", ".", "geometry", "(", "offset", "[", "'offset'", "]", ")", "end", "# Revert the rotation from above", "frame", ".", "rotate", "(", "rotation", ")", "@image", ".", "rotate", "(", "rotation", ")", "end" ]
puts the screenshot into the frame
[ "puts", "the", "screenshot", "into", "the", "frame" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L83-L119
10,486
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.modify_offset
def modify_offset(multiplicator) # Format: "+133+50" hash = offset['offset'] x = hash.split("+")[1].to_f * multiplicator y = hash.split("+")[2].to_f * multiplicator new_offset = "+#{x.round}+#{y.round}" @offset_information['offset'] = new_offset end
ruby
def modify_offset(multiplicator) # Format: "+133+50" hash = offset['offset'] x = hash.split("+")[1].to_f * multiplicator y = hash.split("+")[2].to_f * multiplicator new_offset = "+#{x.round}+#{y.round}" @offset_information['offset'] = new_offset end
[ "def", "modify_offset", "(", "multiplicator", ")", "# Format: \"+133+50\"", "hash", "=", "offset", "[", "'offset'", "]", "x", "=", "hash", ".", "split", "(", "\"+\"", ")", "[", "1", "]", ".", "to_f", "*", "multiplicator", "y", "=", "hash", ".", "split", "(", "\"+\"", ")", "[", "2", "]", ".", "to_f", "*", "multiplicator", "new_offset", "=", "\"+#{x.round}+#{y.round}\"", "@offset_information", "[", "'offset'", "]", "=", "new_offset", "end" ]
Everything below is related to title, background, etc. and is not used in the easy mode this is used to correct the 1:1 offset information the offset information is stored to work for the template images since we resize the template images to have higher quality screenshots we need to modify the offset information by a certain factor
[ "Everything", "below", "is", "related", "to", "title", "background", "etc", ".", "and", "is", "not", "used", "in", "the", "easy", "mode" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L140-L147
10,487
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.horizontal_frame_padding
def horizontal_frame_padding padding = fetch_config['padding'] if padding.kind_of?(String) && padding.split('x').length == 2 padding = padding.split('x')[0] padding = padding.to_i unless padding.end_with?('%') end return scale_padding(padding) end
ruby
def horizontal_frame_padding padding = fetch_config['padding'] if padding.kind_of?(String) && padding.split('x').length == 2 padding = padding.split('x')[0] padding = padding.to_i unless padding.end_with?('%') end return scale_padding(padding) end
[ "def", "horizontal_frame_padding", "padding", "=", "fetch_config", "[", "'padding'", "]", "if", "padding", ".", "kind_of?", "(", "String", ")", "&&", "padding", ".", "split", "(", "'x'", ")", ".", "length", "==", "2", "padding", "=", "padding", ".", "split", "(", "'x'", ")", "[", "0", "]", "padding", "=", "padding", ".", "to_i", "unless", "padding", ".", "end_with?", "(", "'%'", ")", "end", "return", "scale_padding", "(", "padding", ")", "end" ]
Horizontal adding around the frames
[ "Horizontal", "adding", "around", "the", "frames" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L193-L200
10,488
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.title_min_height
def title_min_height @title_min_height ||= begin height = fetch_config['title_min_height'] || 0 if height.kind_of?(String) && height.end_with?('%') height = ([image.width, image.height].min * height.to_f * 0.01).ceil end height end end
ruby
def title_min_height @title_min_height ||= begin height = fetch_config['title_min_height'] || 0 if height.kind_of?(String) && height.end_with?('%') height = ([image.width, image.height].min * height.to_f * 0.01).ceil end height end end
[ "def", "title_min_height", "@title_min_height", "||=", "begin", "height", "=", "fetch_config", "[", "'title_min_height'", "]", "||", "0", "if", "height", ".", "kind_of?", "(", "String", ")", "&&", "height", ".", "end_with?", "(", "'%'", ")", "height", "=", "(", "[", "image", ".", "width", ",", "image", ".", "height", "]", ".", "min", "*", "height", ".", "to_f", "*", "0.01", ")", ".", "ceil", "end", "height", "end", "end" ]
Minimum height for the title
[ "Minimum", "height", "for", "the", "title" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L213-L221
10,489
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.generate_background
def generate_background background = MiniMagick::Image.open(fetch_config['background']) if background.height != screenshot.size[1] background.resize("#{screenshot.size[0]}x#{screenshot.size[1]}^") # `^` says it should fill area background.merge!(["-gravity", "center", "-crop", "#{screenshot.size[0]}x#{screenshot.size[1]}+0+0"]) # crop from center end background end
ruby
def generate_background background = MiniMagick::Image.open(fetch_config['background']) if background.height != screenshot.size[1] background.resize("#{screenshot.size[0]}x#{screenshot.size[1]}^") # `^` says it should fill area background.merge!(["-gravity", "center", "-crop", "#{screenshot.size[0]}x#{screenshot.size[1]}+0+0"]) # crop from center end background end
[ "def", "generate_background", "background", "=", "MiniMagick", "::", "Image", ".", "open", "(", "fetch_config", "[", "'background'", "]", ")", "if", "background", ".", "height", "!=", "screenshot", ".", "size", "[", "1", "]", "background", ".", "resize", "(", "\"#{screenshot.size[0]}x#{screenshot.size[1]}^\"", ")", "# `^` says it should fill area", "background", ".", "merge!", "(", "[", "\"-gravity\"", ",", "\"center\"", ",", "\"-crop\"", ",", "\"#{screenshot.size[0]}x#{screenshot.size[1]}+0+0\"", "]", ")", "# crop from center", "end", "background", "end" ]
Returns a correctly sized background image
[ "Returns", "a", "correctly", "sized", "background", "image" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L251-L259
10,490
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.resize_frame!
def resize_frame! screenshot_width = self.screenshot.portrait? ? screenshot.size[0] : screenshot.size[1] multiplicator = (screenshot_width.to_f / offset['width'].to_f) # by how much do we have to change this? new_frame_width = multiplicator * frame.width # the new width for the frame frame.resize("#{new_frame_width.round}x") # resize it to the calculated width modify_offset(multiplicator) # modify the offset to properly insert the screenshot into the frame later end
ruby
def resize_frame! screenshot_width = self.screenshot.portrait? ? screenshot.size[0] : screenshot.size[1] multiplicator = (screenshot_width.to_f / offset['width'].to_f) # by how much do we have to change this? new_frame_width = multiplicator * frame.width # the new width for the frame frame.resize("#{new_frame_width.round}x") # resize it to the calculated width modify_offset(multiplicator) # modify the offset to properly insert the screenshot into the frame later end
[ "def", "resize_frame!", "screenshot_width", "=", "self", ".", "screenshot", ".", "portrait?", "?", "screenshot", ".", "size", "[", "0", "]", ":", "screenshot", ".", "size", "[", "1", "]", "multiplicator", "=", "(", "screenshot_width", ".", "to_f", "/", "offset", "[", "'width'", "]", ".", "to_f", ")", "# by how much do we have to change this?", "new_frame_width", "=", "multiplicator", "*", "frame", ".", "width", "# the new width for the frame", "frame", ".", "resize", "(", "\"#{new_frame_width.round}x\"", ")", "# resize it to the calculated width", "modify_offset", "(", "multiplicator", ")", "# modify the offset to properly insert the screenshot into the frame later", "end" ]
Resize the frame as it's too low quality by default
[ "Resize", "the", "frame", "as", "it", "s", "too", "low", "quality", "by", "default" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L273-L280
10,491
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.put_title_into_background_stacked
def put_title_into_background_stacked(background, title, keyword) resize_text(title) resize_text(keyword) vertical_padding = vertical_frame_padding # assign padding to variable spacing_between_title_and_keyword = (actual_font_size / 2) title_left_space = (background.width / 2.0 - title.width / 2.0).round keyword_left_space = (background.width / 2.0 - keyword.width / 2.0).round self.space_to_device += title.height + keyword.height + spacing_between_title_and_keyword + vertical_padding if title_below_image keyword_top = background.height - effective_text_height / 2 - (keyword.height + spacing_between_title_and_keyword + title.height) / 2 else keyword_top = device_top(background) / 2 - spacing_between_title_and_keyword / 2 - keyword.height end title_top = keyword_top + keyword.height + spacing_between_title_and_keyword # keyword background = background.composite(keyword, "png") do |c| c.compose("Over") c.geometry("+#{keyword_left_space}+#{keyword_top}") end # Place the title below the keyword background = background.composite(title, "png") do |c| c.compose("Over") c.geometry("+#{title_left_space}+#{title_top}") end background end
ruby
def put_title_into_background_stacked(background, title, keyword) resize_text(title) resize_text(keyword) vertical_padding = vertical_frame_padding # assign padding to variable spacing_between_title_and_keyword = (actual_font_size / 2) title_left_space = (background.width / 2.0 - title.width / 2.0).round keyword_left_space = (background.width / 2.0 - keyword.width / 2.0).round self.space_to_device += title.height + keyword.height + spacing_between_title_and_keyword + vertical_padding if title_below_image keyword_top = background.height - effective_text_height / 2 - (keyword.height + spacing_between_title_and_keyword + title.height) / 2 else keyword_top = device_top(background) / 2 - spacing_between_title_and_keyword / 2 - keyword.height end title_top = keyword_top + keyword.height + spacing_between_title_and_keyword # keyword background = background.composite(keyword, "png") do |c| c.compose("Over") c.geometry("+#{keyword_left_space}+#{keyword_top}") end # Place the title below the keyword background = background.composite(title, "png") do |c| c.compose("Over") c.geometry("+#{title_left_space}+#{title_top}") end background end
[ "def", "put_title_into_background_stacked", "(", "background", ",", "title", ",", "keyword", ")", "resize_text", "(", "title", ")", "resize_text", "(", "keyword", ")", "vertical_padding", "=", "vertical_frame_padding", "# assign padding to variable", "spacing_between_title_and_keyword", "=", "(", "actual_font_size", "/", "2", ")", "title_left_space", "=", "(", "background", ".", "width", "/", "2.0", "-", "title", ".", "width", "/", "2.0", ")", ".", "round", "keyword_left_space", "=", "(", "background", ".", "width", "/", "2.0", "-", "keyword", ".", "width", "/", "2.0", ")", ".", "round", "self", ".", "space_to_device", "+=", "title", ".", "height", "+", "keyword", ".", "height", "+", "spacing_between_title_and_keyword", "+", "vertical_padding", "if", "title_below_image", "keyword_top", "=", "background", ".", "height", "-", "effective_text_height", "/", "2", "-", "(", "keyword", ".", "height", "+", "spacing_between_title_and_keyword", "+", "title", ".", "height", ")", "/", "2", "else", "keyword_top", "=", "device_top", "(", "background", ")", "/", "2", "-", "spacing_between_title_and_keyword", "/", "2", "-", "keyword", ".", "height", "end", "title_top", "=", "keyword_top", "+", "keyword", ".", "height", "+", "spacing_between_title_and_keyword", "# keyword", "background", "=", "background", ".", "composite", "(", "keyword", ",", "\"png\"", ")", "do", "|", "c", "|", "c", ".", "compose", "(", "\"Over\"", ")", "c", ".", "geometry", "(", "\"+#{keyword_left_space}+#{keyword_top}\"", ")", "end", "# Place the title below the keyword", "background", "=", "background", ".", "composite", "(", "title", ",", "\"png\"", ")", "do", "|", "c", "|", "c", ".", "compose", "(", "\"Over\"", ")", "c", ".", "geometry", "(", "\"+#{title_left_space}+#{title_top}\"", ")", "end", "background", "end" ]
Add the title above or below the device
[ "Add", "the", "title", "above", "or", "below", "the", "device" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L292-L321
10,492
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.build_text_images
def build_text_images(max_width, max_height, stack_title) words = [:keyword, :title].keep_if { |a| fetch_text(a) } # optional keyword/title results = {} trim_boxes = {} top_vertical_trim_offset = Float::INFINITY # Init at a large value, as the code will search for a minimal value. bottom_vertical_trim_offset = 0 words.each do |key| # Create empty background empty_path = File.join(Frameit::ROOT, "lib/assets/empty.png") text_image = MiniMagick::Image.open(empty_path) image_height = max_height # gets trimmed afterwards anyway, and on the iPad the `y` would get cut text_image.combine_options do |i| # Oversize as the text might be larger than the actual image. We're trimming afterwards anyway i.resize("#{max_width * 5.0}x#{image_height}!") # `!` says it should ignore the ratio end current_font = font(key) text = fetch_text(key) UI.verbose("Using #{current_font} as font the #{key} of #{screenshot.path}") if current_font UI.verbose("Adding text '#{text}'") text.gsub!('\n', "\n") text.gsub!(/(?<!\\)(')/) { |s| "\\#{s}" } # escape unescaped apostrophes with a backslash interline_spacing = fetch_config['interline_spacing'] # Add the actual title text_image.combine_options do |i| i.font(current_font) if current_font i.gravity("Center") i.pointsize(actual_font_size) i.draw("text 0,0 '#{text}'") i.interline_spacing(interline_spacing) if interline_spacing i.fill(fetch_config[key.to_s]['color']) end results[key] = text_image # Natively trimming the image with .trim will result in the loss of the common baseline between the text in all images when side-by-side (e.g. stack_title is false). # Hence retrieve the calculated trim bounding box without actually trimming: calculated_trim_box = text_image.identify do |b| b.format("%@") # CALCULATED: trim bounding box (without actually trimming), see: http://www.imagemagick.org/script/escape.php end # Create a Trimbox object from the MiniMagick .identify string with syntax "<width>x<height>+<offset_x>+<offset_y>": trim_box = Frameit::Trimbox.new(calculated_trim_box) # Get the minimum top offset of the trim box: if trim_box.offset_y < top_vertical_trim_offset top_vertical_trim_offset = trim_box.offset_y end # Get the maximum bottom offset of the trim box, this is the top offset + height: if (trim_box.offset_y + trim_box.height) > bottom_vertical_trim_offset bottom_vertical_trim_offset = trim_box.offset_y + trim_box.height end # Store for the crop action: trim_boxes[key] = trim_box end # Crop text images: words.each do |key| # Get matching trim box: trim_box = trim_boxes[key] # For side-by-side text images (e.g. stack_title is false) adjust the trim box based on top_vertical_trim_offset and bottom_vertical_trim_offset to maintain the text baseline: unless stack_title # Determine the trim area by maintaining the same vertical top offset based on the smallest value from all trim boxes (top_vertical_trim_offset). # When the vertical top offset is larger than the smallest vertical top offset, the trim box needs to be adjusted: if trim_box.offset_y > top_vertical_trim_offset # Increase the height of the trim box with the difference in vertical top offset: trim_box.height += trim_box.offset_y - top_vertical_trim_offset # Change the vertical top offset to match that of the others: trim_box.offset_y = top_vertical_trim_offset UI.verbose("Trim box for key \"#{key}\" is adjusted to align top: #{trim_box}\n") end # Check if the height needs to be adjusted to reach the bottom offset: if (trim_box.offset_y + trim_box.height) < bottom_vertical_trim_offset # Set the height of the trim box to the difference between vertical bottom and top offset: trim_box.height = bottom_vertical_trim_offset - trim_box.offset_y UI.verbose("Trim box for key \"#{key}\" is adjusted to align bottom: #{trim_box}\n") end end # Crop image with (adjusted) trim box parameters in MiniMagick string format: results[key].crop(trim_box.string_format) end results end
ruby
def build_text_images(max_width, max_height, stack_title) words = [:keyword, :title].keep_if { |a| fetch_text(a) } # optional keyword/title results = {} trim_boxes = {} top_vertical_trim_offset = Float::INFINITY # Init at a large value, as the code will search for a minimal value. bottom_vertical_trim_offset = 0 words.each do |key| # Create empty background empty_path = File.join(Frameit::ROOT, "lib/assets/empty.png") text_image = MiniMagick::Image.open(empty_path) image_height = max_height # gets trimmed afterwards anyway, and on the iPad the `y` would get cut text_image.combine_options do |i| # Oversize as the text might be larger than the actual image. We're trimming afterwards anyway i.resize("#{max_width * 5.0}x#{image_height}!") # `!` says it should ignore the ratio end current_font = font(key) text = fetch_text(key) UI.verbose("Using #{current_font} as font the #{key} of #{screenshot.path}") if current_font UI.verbose("Adding text '#{text}'") text.gsub!('\n', "\n") text.gsub!(/(?<!\\)(')/) { |s| "\\#{s}" } # escape unescaped apostrophes with a backslash interline_spacing = fetch_config['interline_spacing'] # Add the actual title text_image.combine_options do |i| i.font(current_font) if current_font i.gravity("Center") i.pointsize(actual_font_size) i.draw("text 0,0 '#{text}'") i.interline_spacing(interline_spacing) if interline_spacing i.fill(fetch_config[key.to_s]['color']) end results[key] = text_image # Natively trimming the image with .trim will result in the loss of the common baseline between the text in all images when side-by-side (e.g. stack_title is false). # Hence retrieve the calculated trim bounding box without actually trimming: calculated_trim_box = text_image.identify do |b| b.format("%@") # CALCULATED: trim bounding box (without actually trimming), see: http://www.imagemagick.org/script/escape.php end # Create a Trimbox object from the MiniMagick .identify string with syntax "<width>x<height>+<offset_x>+<offset_y>": trim_box = Frameit::Trimbox.new(calculated_trim_box) # Get the minimum top offset of the trim box: if trim_box.offset_y < top_vertical_trim_offset top_vertical_trim_offset = trim_box.offset_y end # Get the maximum bottom offset of the trim box, this is the top offset + height: if (trim_box.offset_y + trim_box.height) > bottom_vertical_trim_offset bottom_vertical_trim_offset = trim_box.offset_y + trim_box.height end # Store for the crop action: trim_boxes[key] = trim_box end # Crop text images: words.each do |key| # Get matching trim box: trim_box = trim_boxes[key] # For side-by-side text images (e.g. stack_title is false) adjust the trim box based on top_vertical_trim_offset and bottom_vertical_trim_offset to maintain the text baseline: unless stack_title # Determine the trim area by maintaining the same vertical top offset based on the smallest value from all trim boxes (top_vertical_trim_offset). # When the vertical top offset is larger than the smallest vertical top offset, the trim box needs to be adjusted: if trim_box.offset_y > top_vertical_trim_offset # Increase the height of the trim box with the difference in vertical top offset: trim_box.height += trim_box.offset_y - top_vertical_trim_offset # Change the vertical top offset to match that of the others: trim_box.offset_y = top_vertical_trim_offset UI.verbose("Trim box for key \"#{key}\" is adjusted to align top: #{trim_box}\n") end # Check if the height needs to be adjusted to reach the bottom offset: if (trim_box.offset_y + trim_box.height) < bottom_vertical_trim_offset # Set the height of the trim box to the difference between vertical bottom and top offset: trim_box.height = bottom_vertical_trim_offset - trim_box.offset_y UI.verbose("Trim box for key \"#{key}\" is adjusted to align bottom: #{trim_box}\n") end end # Crop image with (adjusted) trim box parameters in MiniMagick string format: results[key].crop(trim_box.string_format) end results end
[ "def", "build_text_images", "(", "max_width", ",", "max_height", ",", "stack_title", ")", "words", "=", "[", ":keyword", ",", ":title", "]", ".", "keep_if", "{", "|", "a", "|", "fetch_text", "(", "a", ")", "}", "# optional keyword/title", "results", "=", "{", "}", "trim_boxes", "=", "{", "}", "top_vertical_trim_offset", "=", "Float", "::", "INFINITY", "# Init at a large value, as the code will search for a minimal value.", "bottom_vertical_trim_offset", "=", "0", "words", ".", "each", "do", "|", "key", "|", "# Create empty background", "empty_path", "=", "File", ".", "join", "(", "Frameit", "::", "ROOT", ",", "\"lib/assets/empty.png\"", ")", "text_image", "=", "MiniMagick", "::", "Image", ".", "open", "(", "empty_path", ")", "image_height", "=", "max_height", "# gets trimmed afterwards anyway, and on the iPad the `y` would get cut", "text_image", ".", "combine_options", "do", "|", "i", "|", "# Oversize as the text might be larger than the actual image. We're trimming afterwards anyway", "i", ".", "resize", "(", "\"#{max_width * 5.0}x#{image_height}!\"", ")", "# `!` says it should ignore the ratio", "end", "current_font", "=", "font", "(", "key", ")", "text", "=", "fetch_text", "(", "key", ")", "UI", ".", "verbose", "(", "\"Using #{current_font} as font the #{key} of #{screenshot.path}\"", ")", "if", "current_font", "UI", ".", "verbose", "(", "\"Adding text '#{text}'\"", ")", "text", ".", "gsub!", "(", "'\\n'", ",", "\"\\n\"", ")", "text", ".", "gsub!", "(", "/", "\\\\", "/", ")", "{", "|", "s", "|", "\"\\\\#{s}\"", "}", "# escape unescaped apostrophes with a backslash", "interline_spacing", "=", "fetch_config", "[", "'interline_spacing'", "]", "# Add the actual title", "text_image", ".", "combine_options", "do", "|", "i", "|", "i", ".", "font", "(", "current_font", ")", "if", "current_font", "i", ".", "gravity", "(", "\"Center\"", ")", "i", ".", "pointsize", "(", "actual_font_size", ")", "i", ".", "draw", "(", "\"text 0,0 '#{text}'\"", ")", "i", ".", "interline_spacing", "(", "interline_spacing", ")", "if", "interline_spacing", "i", ".", "fill", "(", "fetch_config", "[", "key", ".", "to_s", "]", "[", "'color'", "]", ")", "end", "results", "[", "key", "]", "=", "text_image", "# Natively trimming the image with .trim will result in the loss of the common baseline between the text in all images when side-by-side (e.g. stack_title is false).", "# Hence retrieve the calculated trim bounding box without actually trimming:", "calculated_trim_box", "=", "text_image", ".", "identify", "do", "|", "b", "|", "b", ".", "format", "(", "\"%@\"", ")", "# CALCULATED: trim bounding box (without actually trimming), see: http://www.imagemagick.org/script/escape.php", "end", "# Create a Trimbox object from the MiniMagick .identify string with syntax \"<width>x<height>+<offset_x>+<offset_y>\":", "trim_box", "=", "Frameit", "::", "Trimbox", ".", "new", "(", "calculated_trim_box", ")", "# Get the minimum top offset of the trim box:", "if", "trim_box", ".", "offset_y", "<", "top_vertical_trim_offset", "top_vertical_trim_offset", "=", "trim_box", ".", "offset_y", "end", "# Get the maximum bottom offset of the trim box, this is the top offset + height:", "if", "(", "trim_box", ".", "offset_y", "+", "trim_box", ".", "height", ")", ">", "bottom_vertical_trim_offset", "bottom_vertical_trim_offset", "=", "trim_box", ".", "offset_y", "+", "trim_box", ".", "height", "end", "# Store for the crop action:", "trim_boxes", "[", "key", "]", "=", "trim_box", "end", "# Crop text images:", "words", ".", "each", "do", "|", "key", "|", "# Get matching trim box:", "trim_box", "=", "trim_boxes", "[", "key", "]", "# For side-by-side text images (e.g. stack_title is false) adjust the trim box based on top_vertical_trim_offset and bottom_vertical_trim_offset to maintain the text baseline:", "unless", "stack_title", "# Determine the trim area by maintaining the same vertical top offset based on the smallest value from all trim boxes (top_vertical_trim_offset).", "# When the vertical top offset is larger than the smallest vertical top offset, the trim box needs to be adjusted:", "if", "trim_box", ".", "offset_y", ">", "top_vertical_trim_offset", "# Increase the height of the trim box with the difference in vertical top offset:", "trim_box", ".", "height", "+=", "trim_box", ".", "offset_y", "-", "top_vertical_trim_offset", "# Change the vertical top offset to match that of the others:", "trim_box", ".", "offset_y", "=", "top_vertical_trim_offset", "UI", ".", "verbose", "(", "\"Trim box for key \\\"#{key}\\\" is adjusted to align top: #{trim_box}\\n\"", ")", "end", "# Check if the height needs to be adjusted to reach the bottom offset:", "if", "(", "trim_box", ".", "offset_y", "+", "trim_box", ".", "height", ")", "<", "bottom_vertical_trim_offset", "# Set the height of the trim box to the difference between vertical bottom and top offset:", "trim_box", ".", "height", "=", "bottom_vertical_trim_offset", "-", "trim_box", ".", "offset_y", "UI", ".", "verbose", "(", "\"Trim box for key \\\"#{key}\\\" is adjusted to align bottom: #{trim_box}\\n\"", ")", "end", "end", "# Crop image with (adjusted) trim box parameters in MiniMagick string format:", "results", "[", "key", "]", ".", "crop", "(", "trim_box", ".", "string_format", ")", "end", "results", "end" ]
This will build up to 2 individual images with the title and optional keyword, which will then be added to the real image
[ "This", "will", "build", "up", "to", "2", "individual", "images", "with", "the", "title", "and", "optional", "keyword", "which", "will", "then", "be", "added", "to", "the", "real", "image" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L396-L489
10,493
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.fetch_text
def fetch_text(type) UI.user_error!("Valid parameters :keyword, :title") unless [:keyword, :title].include?(type) # Try to get it from a keyword.strings or title.strings file strings_path = File.join(File.expand_path("..", screenshot.path), "#{type}.strings") if File.exist?(strings_path) parsed = StringsParser.parse(strings_path) text_array = parsed.find { |k, v| screenshot.path.upcase.include?(k.upcase) } return text_array.last if text_array && text_array.last.length > 0 # Ignore empty string end UI.verbose("Falling back to text in Framefile.json as there was nothing specified in the #{type}.strings file") # No string files, fallback to Framefile config text = fetch_config[type.to_s]['text'] if fetch_config[type.to_s] && fetch_config[type.to_s]['text'] && fetch_config[type.to_s]['text'].length > 0 # Ignore empty string return text end
ruby
def fetch_text(type) UI.user_error!("Valid parameters :keyword, :title") unless [:keyword, :title].include?(type) # Try to get it from a keyword.strings or title.strings file strings_path = File.join(File.expand_path("..", screenshot.path), "#{type}.strings") if File.exist?(strings_path) parsed = StringsParser.parse(strings_path) text_array = parsed.find { |k, v| screenshot.path.upcase.include?(k.upcase) } return text_array.last if text_array && text_array.last.length > 0 # Ignore empty string end UI.verbose("Falling back to text in Framefile.json as there was nothing specified in the #{type}.strings file") # No string files, fallback to Framefile config text = fetch_config[type.to_s]['text'] if fetch_config[type.to_s] && fetch_config[type.to_s]['text'] && fetch_config[type.to_s]['text'].length > 0 # Ignore empty string return text end
[ "def", "fetch_text", "(", "type", ")", "UI", ".", "user_error!", "(", "\"Valid parameters :keyword, :title\"", ")", "unless", "[", ":keyword", ",", ":title", "]", ".", "include?", "(", "type", ")", "# Try to get it from a keyword.strings or title.strings file", "strings_path", "=", "File", ".", "join", "(", "File", ".", "expand_path", "(", "\"..\"", ",", "screenshot", ".", "path", ")", ",", "\"#{type}.strings\"", ")", "if", "File", ".", "exist?", "(", "strings_path", ")", "parsed", "=", "StringsParser", ".", "parse", "(", "strings_path", ")", "text_array", "=", "parsed", ".", "find", "{", "|", "k", ",", "v", "|", "screenshot", ".", "path", ".", "upcase", ".", "include?", "(", "k", ".", "upcase", ")", "}", "return", "text_array", ".", "last", "if", "text_array", "&&", "text_array", ".", "last", ".", "length", ">", "0", "# Ignore empty string", "end", "UI", ".", "verbose", "(", "\"Falling back to text in Framefile.json as there was nothing specified in the #{type}.strings file\"", ")", "# No string files, fallback to Framefile config", "text", "=", "fetch_config", "[", "type", ".", "to_s", "]", "[", "'text'", "]", "if", "fetch_config", "[", "type", ".", "to_s", "]", "&&", "fetch_config", "[", "type", ".", "to_s", "]", "[", "'text'", "]", "&&", "fetch_config", "[", "type", ".", "to_s", "]", "[", "'text'", "]", ".", "length", ">", "0", "# Ignore empty string", "return", "text", "end" ]
Fetches the title + keyword for this particular screenshot
[ "Fetches", "the", "title", "+", "keyword", "for", "this", "particular", "screenshot" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L504-L520
10,494
fastlane/fastlane
frameit/lib/frameit/editor.rb
Frameit.Editor.font
def font(key) single_font = fetch_config[key.to_s]['font'] return single_font if single_font fonts = fetch_config[key.to_s]['fonts'] if fonts fonts.each do |font| if font['supported'] font['supported'].each do |language| if screenshot.path.include?(language) return font["font"] end end else # No `supported` array, this will always be true UI.verbose("Found a font with no list of supported languages, using this now") return font["font"] end end end UI.verbose("No custom font specified for #{screenshot}, using the default one") return nil end
ruby
def font(key) single_font = fetch_config[key.to_s]['font'] return single_font if single_font fonts = fetch_config[key.to_s]['fonts'] if fonts fonts.each do |font| if font['supported'] font['supported'].each do |language| if screenshot.path.include?(language) return font["font"] end end else # No `supported` array, this will always be true UI.verbose("Found a font with no list of supported languages, using this now") return font["font"] end end end UI.verbose("No custom font specified for #{screenshot}, using the default one") return nil end
[ "def", "font", "(", "key", ")", "single_font", "=", "fetch_config", "[", "key", ".", "to_s", "]", "[", "'font'", "]", "return", "single_font", "if", "single_font", "fonts", "=", "fetch_config", "[", "key", ".", "to_s", "]", "[", "'fonts'", "]", "if", "fonts", "fonts", ".", "each", "do", "|", "font", "|", "if", "font", "[", "'supported'", "]", "font", "[", "'supported'", "]", ".", "each", "do", "|", "language", "|", "if", "screenshot", ".", "path", ".", "include?", "(", "language", ")", "return", "font", "[", "\"font\"", "]", "end", "end", "else", "# No `supported` array, this will always be true", "UI", ".", "verbose", "(", "\"Found a font with no list of supported languages, using this now\"", ")", "return", "font", "[", "\"font\"", "]", "end", "end", "end", "UI", ".", "verbose", "(", "\"No custom font specified for #{screenshot}, using the default one\"", ")", "return", "nil", "end" ]
The font we want to use
[ "The", "font", "we", "want", "to", "use" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/frameit/lib/frameit/editor.rb#L538-L561
10,495
fastlane/fastlane
pilot/lib/pilot/build_manager.rb
Pilot.BuildManager.transporter_for_selected_team
def transporter_for_selected_team(options) generic_transporter = FastlaneCore::ItunesTransporter.new(options[:username], nil, false, options[:itc_provider]) return generic_transporter unless options[:itc_provider].nil? && Spaceship::Tunes.client.teams.count > 1 begin team = Spaceship::Tunes.client.teams.find { |t| t['contentProvider']['contentProviderId'].to_s == Spaceship::Tunes.client.team_id } name = team['contentProvider']['name'] provider_id = generic_transporter.provider_ids[name] UI.verbose("Inferred provider id #{provider_id} for team #{name}.") return FastlaneCore::ItunesTransporter.new(options[:username], nil, false, provider_id) rescue => ex UI.verbose("Couldn't infer a provider short name for team with id #{Spaceship::Tunes.client.team_id} automatically: #{ex}. Proceeding without provider short name.") return generic_transporter end end
ruby
def transporter_for_selected_team(options) generic_transporter = FastlaneCore::ItunesTransporter.new(options[:username], nil, false, options[:itc_provider]) return generic_transporter unless options[:itc_provider].nil? && Spaceship::Tunes.client.teams.count > 1 begin team = Spaceship::Tunes.client.teams.find { |t| t['contentProvider']['contentProviderId'].to_s == Spaceship::Tunes.client.team_id } name = team['contentProvider']['name'] provider_id = generic_transporter.provider_ids[name] UI.verbose("Inferred provider id #{provider_id} for team #{name}.") return FastlaneCore::ItunesTransporter.new(options[:username], nil, false, provider_id) rescue => ex UI.verbose("Couldn't infer a provider short name for team with id #{Spaceship::Tunes.client.team_id} automatically: #{ex}. Proceeding without provider short name.") return generic_transporter end end
[ "def", "transporter_for_selected_team", "(", "options", ")", "generic_transporter", "=", "FastlaneCore", "::", "ItunesTransporter", ".", "new", "(", "options", "[", ":username", "]", ",", "nil", ",", "false", ",", "options", "[", ":itc_provider", "]", ")", "return", "generic_transporter", "unless", "options", "[", ":itc_provider", "]", ".", "nil?", "&&", "Spaceship", "::", "Tunes", ".", "client", ".", "teams", ".", "count", ">", "1", "begin", "team", "=", "Spaceship", "::", "Tunes", ".", "client", ".", "teams", ".", "find", "{", "|", "t", "|", "t", "[", "'contentProvider'", "]", "[", "'contentProviderId'", "]", ".", "to_s", "==", "Spaceship", "::", "Tunes", ".", "client", ".", "team_id", "}", "name", "=", "team", "[", "'contentProvider'", "]", "[", "'name'", "]", "provider_id", "=", "generic_transporter", ".", "provider_ids", "[", "name", "]", "UI", ".", "verbose", "(", "\"Inferred provider id #{provider_id} for team #{name}.\"", ")", "return", "FastlaneCore", "::", "ItunesTransporter", ".", "new", "(", "options", "[", ":username", "]", ",", "nil", ",", "false", ",", "provider_id", ")", "rescue", "=>", "ex", "UI", ".", "verbose", "(", "\"Couldn't infer a provider short name for team with id #{Spaceship::Tunes.client.team_id} automatically: #{ex}. Proceeding without provider short name.\"", ")", "return", "generic_transporter", "end", "end" ]
If itc_provider was explicitly specified, use it. If there are multiple teams, infer the provider from the selected team name. If there are fewer than two teams, don't infer the provider.
[ "If", "itc_provider", "was", "explicitly", "specified", "use", "it", ".", "If", "there", "are", "multiple", "teams", "infer", "the", "provider", "from", "the", "selected", "team", "name", ".", "If", "there", "are", "fewer", "than", "two", "teams", "don", "t", "infer", "the", "provider", "." ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/pilot/lib/pilot/build_manager.rb#L221-L235
10,496
fastlane/fastlane
spaceship/lib/spaceship/two_step_or_factor_client.rb
Spaceship.Client.update_request_headers
def update_request_headers(req) req.headers["X-Apple-Id-Session-Id"] = @x_apple_id_session_id req.headers["X-Apple-Widget-Key"] = self.itc_service_key req.headers["Accept"] = "application/json" req.headers["scnt"] = @scnt end
ruby
def update_request_headers(req) req.headers["X-Apple-Id-Session-Id"] = @x_apple_id_session_id req.headers["X-Apple-Widget-Key"] = self.itc_service_key req.headers["Accept"] = "application/json" req.headers["scnt"] = @scnt end
[ "def", "update_request_headers", "(", "req", ")", "req", ".", "headers", "[", "\"X-Apple-Id-Session-Id\"", "]", "=", "@x_apple_id_session_id", "req", ".", "headers", "[", "\"X-Apple-Widget-Key\"", "]", "=", "self", ".", "itc_service_key", "req", ".", "headers", "[", "\"Accept\"", "]", "=", "\"application/json\"", "req", ".", "headers", "[", "\"scnt\"", "]", "=", "@scnt", "end" ]
Responsible for setting all required header attributes for the requests to succeed
[ "Responsible", "for", "setting", "all", "required", "header", "attributes", "for", "the", "requests", "to", "succeed" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/spaceship/lib/spaceship/two_step_or_factor_client.rb#L301-L306
10,497
fastlane/fastlane
fastlane_core/lib/fastlane_core/itunes_transporter.rb
FastlaneCore.ItunesTransporter.upload
def upload(app_id, dir) actual_dir = File.join(dir, "#{app_id}.itmsp") UI.message("Going to upload updated app to App Store Connect") UI.success("This might take a few minutes. Please don't interrupt the script.") command = @transporter_executor.build_upload_command(@user, @password, actual_dir, @provider_short_name) UI.verbose(@transporter_executor.build_upload_command(@user, 'YourPassword', actual_dir, @provider_short_name)) begin result = @transporter_executor.execute(command, ItunesTransporter.hide_transporter_output?) rescue TransporterRequiresApplicationSpecificPasswordError => ex handle_two_step_failure(ex) return upload(app_id, dir) end if result UI.header("Successfully uploaded package to App Store Connect. It might take a few minutes until it's visible online.") FileUtils.rm_rf(actual_dir) unless Helper.test? # we don't need the package any more, since the upload was successful else handle_error(@password) end result end
ruby
def upload(app_id, dir) actual_dir = File.join(dir, "#{app_id}.itmsp") UI.message("Going to upload updated app to App Store Connect") UI.success("This might take a few minutes. Please don't interrupt the script.") command = @transporter_executor.build_upload_command(@user, @password, actual_dir, @provider_short_name) UI.verbose(@transporter_executor.build_upload_command(@user, 'YourPassword', actual_dir, @provider_short_name)) begin result = @transporter_executor.execute(command, ItunesTransporter.hide_transporter_output?) rescue TransporterRequiresApplicationSpecificPasswordError => ex handle_two_step_failure(ex) return upload(app_id, dir) end if result UI.header("Successfully uploaded package to App Store Connect. It might take a few minutes until it's visible online.") FileUtils.rm_rf(actual_dir) unless Helper.test? # we don't need the package any more, since the upload was successful else handle_error(@password) end result end
[ "def", "upload", "(", "app_id", ",", "dir", ")", "actual_dir", "=", "File", ".", "join", "(", "dir", ",", "\"#{app_id}.itmsp\"", ")", "UI", ".", "message", "(", "\"Going to upload updated app to App Store Connect\"", ")", "UI", ".", "success", "(", "\"This might take a few minutes. Please don't interrupt the script.\"", ")", "command", "=", "@transporter_executor", ".", "build_upload_command", "(", "@user", ",", "@password", ",", "actual_dir", ",", "@provider_short_name", ")", "UI", ".", "verbose", "(", "@transporter_executor", ".", "build_upload_command", "(", "@user", ",", "'YourPassword'", ",", "actual_dir", ",", "@provider_short_name", ")", ")", "begin", "result", "=", "@transporter_executor", ".", "execute", "(", "command", ",", "ItunesTransporter", ".", "hide_transporter_output?", ")", "rescue", "TransporterRequiresApplicationSpecificPasswordError", "=>", "ex", "handle_two_step_failure", "(", "ex", ")", "return", "upload", "(", "app_id", ",", "dir", ")", "end", "if", "result", "UI", ".", "header", "(", "\"Successfully uploaded package to App Store Connect. It might take a few minutes until it's visible online.\"", ")", "FileUtils", ".", "rm_rf", "(", "actual_dir", ")", "unless", "Helper", ".", "test?", "# we don't need the package any more, since the upload was successful", "else", "handle_error", "(", "@password", ")", "end", "result", "end" ]
Uploads the modified package back to App Store Connect @param app_id [Integer] The unique App ID @param dir [String] the path in which the package file is located @return (Bool) True if everything worked fine @raise [Deliver::TransporterTransferError] when something went wrong when transferring
[ "Uploads", "the", "modified", "package", "back", "to", "App", "Store", "Connect" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane_core/lib/fastlane_core/itunes_transporter.rb#L410-L435
10,498
fastlane/fastlane
fastlane_core/lib/fastlane_core/itunes_transporter.rb
FastlaneCore.ItunesTransporter.load_password_for_transporter
def load_password_for_transporter # 3 different sources for the password # 1) ENV variable for application specific password if ENV[TWO_FACTOR_ENV_VARIABLE].to_s.length > 0 UI.message("Fetching password for transporter from environment variable named `#{TWO_FACTOR_ENV_VARIABLE}`") return ENV[TWO_FACTOR_ENV_VARIABLE] end # 2) TWO_STEP_HOST_PREFIX from keychain account_manager = CredentialsManager::AccountManager.new(user: @user, prefix: TWO_STEP_HOST_PREFIX, note: "application-specific") password = account_manager.password(ask_if_missing: false) return password if password.to_s.length > 0 # 3) standard iTC password account_manager = CredentialsManager::AccountManager.new(user: @user) return account_manager.password(ask_if_missing: true) end
ruby
def load_password_for_transporter # 3 different sources for the password # 1) ENV variable for application specific password if ENV[TWO_FACTOR_ENV_VARIABLE].to_s.length > 0 UI.message("Fetching password for transporter from environment variable named `#{TWO_FACTOR_ENV_VARIABLE}`") return ENV[TWO_FACTOR_ENV_VARIABLE] end # 2) TWO_STEP_HOST_PREFIX from keychain account_manager = CredentialsManager::AccountManager.new(user: @user, prefix: TWO_STEP_HOST_PREFIX, note: "application-specific") password = account_manager.password(ask_if_missing: false) return password if password.to_s.length > 0 # 3) standard iTC password account_manager = CredentialsManager::AccountManager.new(user: @user) return account_manager.password(ask_if_missing: true) end
[ "def", "load_password_for_transporter", "# 3 different sources for the password", "# 1) ENV variable for application specific password", "if", "ENV", "[", "TWO_FACTOR_ENV_VARIABLE", "]", ".", "to_s", ".", "length", ">", "0", "UI", ".", "message", "(", "\"Fetching password for transporter from environment variable named `#{TWO_FACTOR_ENV_VARIABLE}`\"", ")", "return", "ENV", "[", "TWO_FACTOR_ENV_VARIABLE", "]", "end", "# 2) TWO_STEP_HOST_PREFIX from keychain", "account_manager", "=", "CredentialsManager", "::", "AccountManager", ".", "new", "(", "user", ":", "@user", ",", "prefix", ":", "TWO_STEP_HOST_PREFIX", ",", "note", ":", "\"application-specific\"", ")", "password", "=", "account_manager", ".", "password", "(", "ask_if_missing", ":", "false", ")", "return", "password", "if", "password", ".", "to_s", ".", "length", ">", "0", "# 3) standard iTC password", "account_manager", "=", "CredentialsManager", "::", "AccountManager", ".", "new", "(", "user", ":", "@user", ")", "return", "account_manager", ".", "password", "(", "ask_if_missing", ":", "true", ")", "end" ]
Returns the password to be used with the transporter
[ "Returns", "the", "password", "to", "be", "used", "with", "the", "transporter" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane_core/lib/fastlane_core/itunes_transporter.rb#L457-L473
10,499
fastlane/fastlane
fastlane_core/lib/fastlane_core/itunes_transporter.rb
FastlaneCore.ItunesTransporter.handle_two_step_failure
def handle_two_step_failure(ex) if ENV[TWO_FACTOR_ENV_VARIABLE].to_s.length > 0 # Password provided, however we already used it UI.error("") UI.error("Application specific password you provided using") UI.error("environment variable #{TWO_FACTOR_ENV_VARIABLE}") UI.error("is invalid, please make sure it's correct") UI.error("") UI.user_error!("Invalid application specific password provided") end a = CredentialsManager::AccountManager.new(user: @user, prefix: TWO_STEP_HOST_PREFIX, note: "application-specific") if a.password(ask_if_missing: false).to_s.length > 0 # user already entered one.. delete the old one UI.error("Application specific password seems wrong") UI.error("Please make sure to follow the instructions") a.remove_from_keychain end UI.error("") UI.error("Your account has 2 step verification enabled") UI.error("Please go to https://appleid.apple.com/account/manage") UI.error("and generate an application specific password for") UI.error("the iTunes Transporter, which is used to upload builds") UI.error("") UI.error("To set the application specific password on a CI machine using") UI.error("an environment variable, you can set the") UI.error("#{TWO_FACTOR_ENV_VARIABLE} variable") @password = a.password(ask_if_missing: true) # to ask the user for the missing value return true end
ruby
def handle_two_step_failure(ex) if ENV[TWO_FACTOR_ENV_VARIABLE].to_s.length > 0 # Password provided, however we already used it UI.error("") UI.error("Application specific password you provided using") UI.error("environment variable #{TWO_FACTOR_ENV_VARIABLE}") UI.error("is invalid, please make sure it's correct") UI.error("") UI.user_error!("Invalid application specific password provided") end a = CredentialsManager::AccountManager.new(user: @user, prefix: TWO_STEP_HOST_PREFIX, note: "application-specific") if a.password(ask_if_missing: false).to_s.length > 0 # user already entered one.. delete the old one UI.error("Application specific password seems wrong") UI.error("Please make sure to follow the instructions") a.remove_from_keychain end UI.error("") UI.error("Your account has 2 step verification enabled") UI.error("Please go to https://appleid.apple.com/account/manage") UI.error("and generate an application specific password for") UI.error("the iTunes Transporter, which is used to upload builds") UI.error("") UI.error("To set the application specific password on a CI machine using") UI.error("an environment variable, you can set the") UI.error("#{TWO_FACTOR_ENV_VARIABLE} variable") @password = a.password(ask_if_missing: true) # to ask the user for the missing value return true end
[ "def", "handle_two_step_failure", "(", "ex", ")", "if", "ENV", "[", "TWO_FACTOR_ENV_VARIABLE", "]", ".", "to_s", ".", "length", ">", "0", "# Password provided, however we already used it", "UI", ".", "error", "(", "\"\"", ")", "UI", ".", "error", "(", "\"Application specific password you provided using\"", ")", "UI", ".", "error", "(", "\"environment variable #{TWO_FACTOR_ENV_VARIABLE}\"", ")", "UI", ".", "error", "(", "\"is invalid, please make sure it's correct\"", ")", "UI", ".", "error", "(", "\"\"", ")", "UI", ".", "user_error!", "(", "\"Invalid application specific password provided\"", ")", "end", "a", "=", "CredentialsManager", "::", "AccountManager", ".", "new", "(", "user", ":", "@user", ",", "prefix", ":", "TWO_STEP_HOST_PREFIX", ",", "note", ":", "\"application-specific\"", ")", "if", "a", ".", "password", "(", "ask_if_missing", ":", "false", ")", ".", "to_s", ".", "length", ">", "0", "# user already entered one.. delete the old one", "UI", ".", "error", "(", "\"Application specific password seems wrong\"", ")", "UI", ".", "error", "(", "\"Please make sure to follow the instructions\"", ")", "a", ".", "remove_from_keychain", "end", "UI", ".", "error", "(", "\"\"", ")", "UI", ".", "error", "(", "\"Your account has 2 step verification enabled\"", ")", "UI", ".", "error", "(", "\"Please go to https://appleid.apple.com/account/manage\"", ")", "UI", ".", "error", "(", "\"and generate an application specific password for\"", ")", "UI", ".", "error", "(", "\"the iTunes Transporter, which is used to upload builds\"", ")", "UI", ".", "error", "(", "\"\"", ")", "UI", ".", "error", "(", "\"To set the application specific password on a CI machine using\"", ")", "UI", ".", "error", "(", "\"an environment variable, you can set the\"", ")", "UI", ".", "error", "(", "\"#{TWO_FACTOR_ENV_VARIABLE} variable\"", ")", "@password", "=", "a", ".", "password", "(", "ask_if_missing", ":", "true", ")", "# to ask the user for the missing value", "return", "true", "end" ]
Tells the user how to get an application specific password
[ "Tells", "the", "user", "how", "to", "get", "an", "application", "specific", "password" ]
457c5d647c77f0e078dafa5129da616914e002c5
https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane_core/lib/fastlane_core/itunes_transporter.rb#L476-L508