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
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
mongodb/mongo-ruby-driver
lib/mongo/write_concern.rb
Mongo.WriteConcern.get
def get(options) return options if options.is_a?(Unacknowledged) || options.is_a?(Acknowledged) if options validate!(options) if unacknowledged?(options) Unacknowledged.new(options) else Acknowledged.new(options) end end end
ruby
def get(options) return options if options.is_a?(Unacknowledged) || options.is_a?(Acknowledged) if options validate!(options) if unacknowledged?(options) Unacknowledged.new(options) else Acknowledged.new(options) end end end
[ "def", "get", "(", "options", ")", "return", "options", "if", "options", ".", "is_a?", "(", "Unacknowledged", ")", "||", "options", ".", "is_a?", "(", "Acknowledged", ")", "if", "options", "validate!", "(", "options", ")", "if", "unacknowledged?", "(", "options", ")", "Unacknowledged", ".", "new", "(", "options", ")", "else", "Acknowledged", ".", "new", "(", "options", ")", "end", "end", "end" ]
Create a write concern object for the provided options. @example Get a write concern. Mongo::WriteConcern.get(:w => 1) @param [ Hash ] options The options to instantiate with. @option options :w [ Integer, String ] The number of servers or the custom mode to acknowledge. @option options :j [ true, false ] Whether to acknowledge a write to the journal. @option options :fsync [ true, false ] Should the write be synced to disc. @option options :wtimeout [ Integer ] The number of milliseconds to wait for acknowledgement before raising an error. @return [ Unacknowledged, Acknowledged ] The appropriate concern. @raise [ Error::InvalidWriteConcern ] If the options are invalid. @since 2.0.0
[ "Create", "a", "write", "concern", "object", "for", "the", "provided", "options", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/write_concern.rb#L78-L88
train
mongodb/mongo-ruby-driver
lib/mongo/database.rb
Mongo.Database.command
def command(operation, opts = {}) txn_read_pref = if opts[:session] && opts[:session].in_transaction? opts[:session].txn_read_preference else nil end txn_read_pref ||= opts[:read] || ServerSelector::PRIMARY Lint.validate_underscore_read_preference(txn_read_pref) preference = ServerSelector.get(txn_read_pref) client.send(:with_session, opts) do |session| read_with_retry(session, preference) do |server| Operation::Command.new({ :selector => operation.dup, :db_name => name, :read => preference, :session => session }).execute(server) end end end
ruby
def command(operation, opts = {}) txn_read_pref = if opts[:session] && opts[:session].in_transaction? opts[:session].txn_read_preference else nil end txn_read_pref ||= opts[:read] || ServerSelector::PRIMARY Lint.validate_underscore_read_preference(txn_read_pref) preference = ServerSelector.get(txn_read_pref) client.send(:with_session, opts) do |session| read_with_retry(session, preference) do |server| Operation::Command.new({ :selector => operation.dup, :db_name => name, :read => preference, :session => session }).execute(server) end end end
[ "def", "command", "(", "operation", ",", "opts", "=", "{", "}", ")", "txn_read_pref", "=", "if", "opts", "[", ":session", "]", "&&", "opts", "[", ":session", "]", ".", "in_transaction?", "opts", "[", ":session", "]", ".", "txn_read_preference", "else", "nil", "end", "txn_read_pref", "||=", "opts", "[", ":read", "]", "||", "ServerSelector", "::", "PRIMARY", "Lint", ".", "validate_underscore_read_preference", "(", "txn_read_pref", ")", "preference", "=", "ServerSelector", ".", "get", "(", "txn_read_pref", ")", "client", ".", "send", "(", ":with_session", ",", "opts", ")", "do", "|", "session", "|", "read_with_retry", "(", "session", ",", "preference", ")", "do", "|", "server", "|", "Operation", "::", "Command", ".", "new", "(", "{", ":selector", "=>", "operation", ".", "dup", ",", ":db_name", "=>", "name", ",", ":read", "=>", "preference", ",", ":session", "=>", "session", "}", ")", ".", "execute", "(", "server", ")", "end", "end", "end" ]
Execute a command on the database. @example Execute a command. database.command(:ismaster => 1) @param [ Hash ] operation The command to execute. @param [ Hash ] opts The command options. @option opts :read [ Hash ] The read preference for this command. @option opts :session [ Session ] The session to use for this command. @return [ Hash ] The result of the command execution.
[ "Execute", "a", "command", "on", "the", "database", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/database.rb#L158-L178
train
mongodb/mongo-ruby-driver
lib/mongo/database.rb
Mongo.Database.drop
def drop(options = {}) operation = { :dropDatabase => 1 } client.send(:with_session, options) do |session| Operation::DropDatabase.new({ selector: operation, db_name: name, write_concern: write_concern, session: session }).execute(next_primary) end end
ruby
def drop(options = {}) operation = { :dropDatabase => 1 } client.send(:with_session, options) do |session| Operation::DropDatabase.new({ selector: operation, db_name: name, write_concern: write_concern, session: session }).execute(next_primary) end end
[ "def", "drop", "(", "options", "=", "{", "}", ")", "operation", "=", "{", ":dropDatabase", "=>", "1", "}", "client", ".", "send", "(", ":with_session", ",", "options", ")", "do", "|", "session", "|", "Operation", "::", "DropDatabase", ".", "new", "(", "{", "selector", ":", "operation", ",", "db_name", ":", "name", ",", "write_concern", ":", "write_concern", ",", "session", ":", "session", "}", ")", ".", "execute", "(", "next_primary", ")", "end", "end" ]
Drop the database and all its associated information. @example Drop the database. database.drop @param [ Hash ] options The options for the operation. @option options [ Session ] :session The session to use for the operation. @return [ Result ] The result of the command. @since 2.0.0
[ "Drop", "the", "database", "and", "all", "its", "associated", "information", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/database.rb#L192-L202
train
mongodb/mongo-ruby-driver
lib/mongo/socket.rb
Mongo.Socket.read
def read(length) handle_errors do data = read_from_socket(length) raise IOError unless (data.length > 0 || length == 0) while data.length < length chunk = read_from_socket(length - data.length) raise IOError unless (chunk.length > 0 || length == 0) data << chunk end data end end
ruby
def read(length) handle_errors do data = read_from_socket(length) raise IOError unless (data.length > 0 || length == 0) while data.length < length chunk = read_from_socket(length - data.length) raise IOError unless (chunk.length > 0 || length == 0) data << chunk end data end end
[ "def", "read", "(", "length", ")", "handle_errors", "do", "data", "=", "read_from_socket", "(", "length", ")", "raise", "IOError", "unless", "(", "data", ".", "length", ">", "0", "||", "length", "==", "0", ")", "while", "data", ".", "length", "<", "length", "chunk", "=", "read_from_socket", "(", "length", "-", "data", ".", "length", ")", "raise", "IOError", "unless", "(", "chunk", ".", "length", ">", "0", "||", "length", "==", "0", ")", "data", "<<", "chunk", "end", "data", "end", "end" ]
Create the new socket for the provided family - ipv4, piv6, or unix. @example Create a new ipv4 socket. Socket.new(Socket::PF_INET) @param [ Integer ] family The socket domain. @since 2.0.0 Will read all data from the socket for the provided number of bytes. If no data is returned, an exception will be raised. @example Read all the requested data from the socket. socket.read(4096) @param [ Integer ] length The number of bytes to read. @raise [ Mongo::SocketError ] If not all data is returned. @return [ Object ] The data from the socket. @since 2.0.0
[ "Create", "the", "new", "socket", "for", "the", "provided", "family", "-", "ipv4", "piv6", "or", "unix", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/socket.rb#L123-L134
train
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.end_session
def end_session if !ended? && @client if within_states?(TRANSACTION_IN_PROGRESS_STATE) begin abort_transaction rescue Mongo::Error end end @client.cluster.session_pool.checkin(@server_session) end ensure @server_session = nil end
ruby
def end_session if !ended? && @client if within_states?(TRANSACTION_IN_PROGRESS_STATE) begin abort_transaction rescue Mongo::Error end end @client.cluster.session_pool.checkin(@server_session) end ensure @server_session = nil end
[ "def", "end_session", "if", "!", "ended?", "&&", "@client", "if", "within_states?", "(", "TRANSACTION_IN_PROGRESS_STATE", ")", "begin", "abort_transaction", "rescue", "Mongo", "::", "Error", "end", "end", "@client", ".", "cluster", ".", "session_pool", ".", "checkin", "(", "@server_session", ")", "end", "ensure", "@server_session", "=", "nil", "end" ]
End this session. @example session.end_session @return [ nil ] Always nil. @since 2.5.0
[ "End", "this", "session", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L168-L180
train
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.add_txn_num!
def add_txn_num!(command) command.tap do |c| c[:txnNumber] = BSON::Int64.new(@server_session.txn_num) if in_transaction? end end
ruby
def add_txn_num!(command) command.tap do |c| c[:txnNumber] = BSON::Int64.new(@server_session.txn_num) if in_transaction? end end
[ "def", "add_txn_num!", "(", "command", ")", "command", ".", "tap", "do", "|", "c", "|", "c", "[", ":txnNumber", "]", "=", "BSON", "::", "Int64", ".", "new", "(", "@server_session", ".", "txn_num", ")", "if", "in_transaction?", "end", "end" ]
Add the transaction number to a command document if applicable. @example session.add_txn_num!(cmd) @return [ Hash, BSON::Document ] The command document. @since 2.6.0 @api private
[ "Add", "the", "transaction", "number", "to", "a", "command", "document", "if", "applicable", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L248-L252
train
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.add_txn_opts!
def add_txn_opts!(command, read) command.tap do |c| # The read preference should be added for all read operations. if read && txn_read_pref = txn_read_preference Mongo::Lint.validate_underscore_read_preference(txn_read_pref) txn_read_pref = txn_read_pref.dup txn_read_pref[:mode] = txn_read_pref[:mode].to_s.gsub(/(_\w)/) { |match| match[1].upcase } Mongo::Lint.validate_camel_case_read_preference(txn_read_pref) c['$readPreference'] = txn_read_pref end # The read concern should be added to any command that starts a transaction. if starting_transaction? # https://jira.mongodb.org/browse/SPEC-1161: transaction's # read concern overrides collection/database/client read concerns, # even if transaction's read concern is not set. # Read concern here is the one sent to the server and may # include afterClusterTime. if rc = c[:readConcern] rc = rc.dup rc.delete(:level) end if txn_read_concern if rc rc.update(txn_read_concern) else rc = txn_read_concern.dup end end if rc.nil? || rc.empty? c.delete(:readConcern) else c[:readConcern ] = rc end end # We need to send the read concern level as a string rather than a symbol. if c[:readConcern] && c[:readConcern][:level] c[:readConcern][:level] = c[:readConcern][:level].to_s end # The write concern should be added to any abortTransaction or commitTransaction command. if (c[:abortTransaction] || c[:commitTransaction]) if @already_committed wc = BSON::Document.new(c[:writeConcern] || txn_write_concern || {}) wc.merge!(w: :majority) wc[:wtimeout] ||= 10000 c[:writeConcern] = wc elsif txn_write_concern c[:writeConcern] ||= txn_write_concern end end # A non-numeric write concern w value needs to be sent as a string rather than a symbol. if c[:writeConcern] && c[:writeConcern][:w] && c[:writeConcern][:w].is_a?(Symbol) c[:writeConcern][:w] = c[:writeConcern][:w].to_s end end end
ruby
def add_txn_opts!(command, read) command.tap do |c| # The read preference should be added for all read operations. if read && txn_read_pref = txn_read_preference Mongo::Lint.validate_underscore_read_preference(txn_read_pref) txn_read_pref = txn_read_pref.dup txn_read_pref[:mode] = txn_read_pref[:mode].to_s.gsub(/(_\w)/) { |match| match[1].upcase } Mongo::Lint.validate_camel_case_read_preference(txn_read_pref) c['$readPreference'] = txn_read_pref end # The read concern should be added to any command that starts a transaction. if starting_transaction? # https://jira.mongodb.org/browse/SPEC-1161: transaction's # read concern overrides collection/database/client read concerns, # even if transaction's read concern is not set. # Read concern here is the one sent to the server and may # include afterClusterTime. if rc = c[:readConcern] rc = rc.dup rc.delete(:level) end if txn_read_concern if rc rc.update(txn_read_concern) else rc = txn_read_concern.dup end end if rc.nil? || rc.empty? c.delete(:readConcern) else c[:readConcern ] = rc end end # We need to send the read concern level as a string rather than a symbol. if c[:readConcern] && c[:readConcern][:level] c[:readConcern][:level] = c[:readConcern][:level].to_s end # The write concern should be added to any abortTransaction or commitTransaction command. if (c[:abortTransaction] || c[:commitTransaction]) if @already_committed wc = BSON::Document.new(c[:writeConcern] || txn_write_concern || {}) wc.merge!(w: :majority) wc[:wtimeout] ||= 10000 c[:writeConcern] = wc elsif txn_write_concern c[:writeConcern] ||= txn_write_concern end end # A non-numeric write concern w value needs to be sent as a string rather than a symbol. if c[:writeConcern] && c[:writeConcern][:w] && c[:writeConcern][:w].is_a?(Symbol) c[:writeConcern][:w] = c[:writeConcern][:w].to_s end end end
[ "def", "add_txn_opts!", "(", "command", ",", "read", ")", "command", ".", "tap", "do", "|", "c", "|", "# The read preference should be added for all read operations.", "if", "read", "&&", "txn_read_pref", "=", "txn_read_preference", "Mongo", "::", "Lint", ".", "validate_underscore_read_preference", "(", "txn_read_pref", ")", "txn_read_pref", "=", "txn_read_pref", ".", "dup", "txn_read_pref", "[", ":mode", "]", "=", "txn_read_pref", "[", ":mode", "]", ".", "to_s", ".", "gsub", "(", "/", "\\w", "/", ")", "{", "|", "match", "|", "match", "[", "1", "]", ".", "upcase", "}", "Mongo", "::", "Lint", ".", "validate_camel_case_read_preference", "(", "txn_read_pref", ")", "c", "[", "'$readPreference'", "]", "=", "txn_read_pref", "end", "# The read concern should be added to any command that starts a transaction.", "if", "starting_transaction?", "# https://jira.mongodb.org/browse/SPEC-1161: transaction's", "# read concern overrides collection/database/client read concerns,", "# even if transaction's read concern is not set.", "# Read concern here is the one sent to the server and may", "# include afterClusterTime.", "if", "rc", "=", "c", "[", ":readConcern", "]", "rc", "=", "rc", ".", "dup", "rc", ".", "delete", "(", ":level", ")", "end", "if", "txn_read_concern", "if", "rc", "rc", ".", "update", "(", "txn_read_concern", ")", "else", "rc", "=", "txn_read_concern", ".", "dup", "end", "end", "if", "rc", ".", "nil?", "||", "rc", ".", "empty?", "c", ".", "delete", "(", ":readConcern", ")", "else", "c", "[", ":readConcern", "]", "=", "rc", "end", "end", "# We need to send the read concern level as a string rather than a symbol.", "if", "c", "[", ":readConcern", "]", "&&", "c", "[", ":readConcern", "]", "[", ":level", "]", "c", "[", ":readConcern", "]", "[", ":level", "]", "=", "c", "[", ":readConcern", "]", "[", ":level", "]", ".", "to_s", "end", "# The write concern should be added to any abortTransaction or commitTransaction command.", "if", "(", "c", "[", ":abortTransaction", "]", "||", "c", "[", ":commitTransaction", "]", ")", "if", "@already_committed", "wc", "=", "BSON", "::", "Document", ".", "new", "(", "c", "[", ":writeConcern", "]", "||", "txn_write_concern", "||", "{", "}", ")", "wc", ".", "merge!", "(", "w", ":", ":majority", ")", "wc", "[", ":wtimeout", "]", "||=", "10000", "c", "[", ":writeConcern", "]", "=", "wc", "elsif", "txn_write_concern", "c", "[", ":writeConcern", "]", "||=", "txn_write_concern", "end", "end", "# A non-numeric write concern w value needs to be sent as a string rather than a symbol.", "if", "c", "[", ":writeConcern", "]", "&&", "c", "[", ":writeConcern", "]", "[", ":w", "]", "&&", "c", "[", ":writeConcern", "]", "[", ":w", "]", ".", "is_a?", "(", "Symbol", ")", "c", "[", ":writeConcern", "]", "[", ":w", "]", "=", "c", "[", ":writeConcern", "]", "[", ":w", "]", ".", "to_s", "end", "end", "end" ]
Add the transactions options if applicable. @example session.add_txn_opts!(cmd) @return [ Hash, BSON::Document ] The command document. @since 2.6.0 @api private
[ "Add", "the", "transactions", "options", "if", "applicable", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L263-L321
train
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.validate_read_preference!
def validate_read_preference!(command) return unless in_transaction? && non_primary_read_preference_mode?(command) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::INVALID_READ_PREFERENCE) end
ruby
def validate_read_preference!(command) return unless in_transaction? && non_primary_read_preference_mode?(command) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::INVALID_READ_PREFERENCE) end
[ "def", "validate_read_preference!", "(", "command", ")", "return", "unless", "in_transaction?", "&&", "non_primary_read_preference_mode?", "(", "command", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", "::", "INVALID_READ_PREFERENCE", ")", "end" ]
Ensure that the read preference of a command primary. @example session.validate_read_preference!(command) @raise [ Mongo::Error::InvalidTransactionOperation ] If the read preference of the command is not primary. @since 2.6.0 @api private
[ "Ensure", "that", "the", "read", "preference", "of", "a", "command", "primary", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L351-L356
train
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.start_transaction
def start_transaction(options = nil) if options Lint.validate_read_concern_option(options[:read_concern]) end check_if_ended! if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::TRANSACTION_ALREADY_IN_PROGRESS) end next_txn_num @txn_options = options || @options[:default_transaction_options] || {} if txn_write_concern && WriteConcern.send(:unacknowledged?, txn_write_concern) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::UNACKNOWLEDGED_WRITE_CONCERN) end @state = STARTING_TRANSACTION_STATE @already_committed = false end
ruby
def start_transaction(options = nil) if options Lint.validate_read_concern_option(options[:read_concern]) end check_if_ended! if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::TRANSACTION_ALREADY_IN_PROGRESS) end next_txn_num @txn_options = options || @options[:default_transaction_options] || {} if txn_write_concern && WriteConcern.send(:unacknowledged?, txn_write_concern) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation::UNACKNOWLEDGED_WRITE_CONCERN) end @state = STARTING_TRANSACTION_STATE @already_committed = false end
[ "def", "start_transaction", "(", "options", "=", "nil", ")", "if", "options", "Lint", ".", "validate_read_concern_option", "(", "options", "[", ":read_concern", "]", ")", "end", "check_if_ended!", "if", "within_states?", "(", "STARTING_TRANSACTION_STATE", ",", "TRANSACTION_IN_PROGRESS_STATE", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", "::", "TRANSACTION_ALREADY_IN_PROGRESS", ")", "end", "next_txn_num", "@txn_options", "=", "options", "||", "@options", "[", ":default_transaction_options", "]", "||", "{", "}", "if", "txn_write_concern", "&&", "WriteConcern", ".", "send", "(", ":unacknowledged?", ",", "txn_write_concern", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", "::", "UNACKNOWLEDGED_WRITE_CONCERN", ")", "end", "@state", "=", "STARTING_TRANSACTION_STATE", "@already_committed", "=", "false", "end" ]
Places subsequent operations in this session into a new transaction. Note that the transaction will not be started on the server until an operation is performed after start_transaction is called. @example Start a new transaction session.start_transaction(options) @param [ Hash ] options The options for the transaction being started. @option options [ Hash ] read_concern The read concern options hash, with the following optional keys: - *:level* -- the read preference level as a symbol; valid values are *:local*, *:majority*, and *:snapshot* @option options [ Hash ] :write_concern The write concern options. Can be :w => Integer|String, :fsync => Boolean, :j => Boolean. @option options [ Hash ] :read The read preference options. The hash may have the following items: - *:mode* -- read preference specified as a symbol; the only valid value is *:primary*. @raise [ Error::InvalidTransactionOperation ] If a transaction is already in progress or if the write concern is unacknowledged. @since 2.6.0
[ "Places", "subsequent", "operations", "in", "this", "session", "into", "a", "new", "transaction", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L580-L602
train
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.commit_transaction
def commit_transaction(options=nil) check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :abortTransaction, :commitTransaction)) end options ||= {} begin # If commitTransaction is called twice, we need to run the same commit # operation again, so we revert the session to the previous state. if within_states?(TRANSACTION_COMMITTED_STATE) @state = @last_commit_skipped ? STARTING_TRANSACTION_STATE : TRANSACTION_IN_PROGRESS_STATE @already_committed = true end if starting_transaction? @last_commit_skipped = true else @last_commit_skipped = false write_concern = options[:write_concern] || txn_options[:write_concern] if write_concern && !write_concern.is_a?(WriteConcern::Base) write_concern = WriteConcern.get(write_concern) end write_with_retry(self, write_concern, true) do |server, txn_num, is_retry| if is_retry if write_concern wco = write_concern.options.merge(w: :majority) wco[:wtimeout] ||= 10000 write_concern = WriteConcern.get(wco) else write_concern = WriteConcern.get(w: :majority, wtimeout: 10000) end end Operation::Command.new( selector: { commitTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num, write_concern: write_concern, ).execute(server) end end rescue Mongo::Error::NoServerAvailable, Mongo::Error::SocketError => e e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) raise e rescue Mongo::Error::OperationFailure => e err_doc = e.instance_variable_get(:@result).send(:first_document) if e.write_retryable? || (err_doc['writeConcernError'] && !UNLABELED_WRITE_CONCERN_CODES.include?(err_doc['writeConcernError']['code'])) e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) end raise e ensure @state = TRANSACTION_COMMITTED_STATE end end
ruby
def commit_transaction(options=nil) check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :abortTransaction, :commitTransaction)) end options ||= {} begin # If commitTransaction is called twice, we need to run the same commit # operation again, so we revert the session to the previous state. if within_states?(TRANSACTION_COMMITTED_STATE) @state = @last_commit_skipped ? STARTING_TRANSACTION_STATE : TRANSACTION_IN_PROGRESS_STATE @already_committed = true end if starting_transaction? @last_commit_skipped = true else @last_commit_skipped = false write_concern = options[:write_concern] || txn_options[:write_concern] if write_concern && !write_concern.is_a?(WriteConcern::Base) write_concern = WriteConcern.get(write_concern) end write_with_retry(self, write_concern, true) do |server, txn_num, is_retry| if is_retry if write_concern wco = write_concern.options.merge(w: :majority) wco[:wtimeout] ||= 10000 write_concern = WriteConcern.get(wco) else write_concern = WriteConcern.get(w: :majority, wtimeout: 10000) end end Operation::Command.new( selector: { commitTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num, write_concern: write_concern, ).execute(server) end end rescue Mongo::Error::NoServerAvailable, Mongo::Error::SocketError => e e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) raise e rescue Mongo::Error::OperationFailure => e err_doc = e.instance_variable_get(:@result).send(:first_document) if e.write_retryable? || (err_doc['writeConcernError'] && !UNLABELED_WRITE_CONCERN_CODES.include?(err_doc['writeConcernError']['code'])) e.send(:add_label, Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) end raise e ensure @state = TRANSACTION_COMMITTED_STATE end end
[ "def", "commit_transaction", "(", "options", "=", "nil", ")", "check_if_ended!", "check_if_no_transaction!", "if", "within_states?", "(", "TRANSACTION_ABORTED_STATE", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "cannot_call_after_msg", "(", ":abortTransaction", ",", ":commitTransaction", ")", ")", "end", "options", "||=", "{", "}", "begin", "# If commitTransaction is called twice, we need to run the same commit", "# operation again, so we revert the session to the previous state.", "if", "within_states?", "(", "TRANSACTION_COMMITTED_STATE", ")", "@state", "=", "@last_commit_skipped", "?", "STARTING_TRANSACTION_STATE", ":", "TRANSACTION_IN_PROGRESS_STATE", "@already_committed", "=", "true", "end", "if", "starting_transaction?", "@last_commit_skipped", "=", "true", "else", "@last_commit_skipped", "=", "false", "write_concern", "=", "options", "[", ":write_concern", "]", "||", "txn_options", "[", ":write_concern", "]", "if", "write_concern", "&&", "!", "write_concern", ".", "is_a?", "(", "WriteConcern", "::", "Base", ")", "write_concern", "=", "WriteConcern", ".", "get", "(", "write_concern", ")", "end", "write_with_retry", "(", "self", ",", "write_concern", ",", "true", ")", "do", "|", "server", ",", "txn_num", ",", "is_retry", "|", "if", "is_retry", "if", "write_concern", "wco", "=", "write_concern", ".", "options", ".", "merge", "(", "w", ":", ":majority", ")", "wco", "[", ":wtimeout", "]", "||=", "10000", "write_concern", "=", "WriteConcern", ".", "get", "(", "wco", ")", "else", "write_concern", "=", "WriteConcern", ".", "get", "(", "w", ":", ":majority", ",", "wtimeout", ":", "10000", ")", "end", "end", "Operation", "::", "Command", ".", "new", "(", "selector", ":", "{", "commitTransaction", ":", "1", "}", ",", "db_name", ":", "'admin'", ",", "session", ":", "self", ",", "txn_num", ":", "txn_num", ",", "write_concern", ":", "write_concern", ",", ")", ".", "execute", "(", "server", ")", "end", "end", "rescue", "Mongo", "::", "Error", "::", "NoServerAvailable", ",", "Mongo", "::", "Error", "::", "SocketError", "=>", "e", "e", ".", "send", "(", ":add_label", ",", "Mongo", "::", "Error", "::", "UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL", ")", "raise", "e", "rescue", "Mongo", "::", "Error", "::", "OperationFailure", "=>", "e", "err_doc", "=", "e", ".", "instance_variable_get", "(", ":@result", ")", ".", "send", "(", ":first_document", ")", "if", "e", ".", "write_retryable?", "||", "(", "err_doc", "[", "'writeConcernError'", "]", "&&", "!", "UNLABELED_WRITE_CONCERN_CODES", ".", "include?", "(", "err_doc", "[", "'writeConcernError'", "]", "[", "'code'", "]", ")", ")", "e", ".", "send", "(", ":add_label", ",", "Mongo", "::", "Error", "::", "UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL", ")", "end", "raise", "e", "ensure", "@state", "=", "TRANSACTION_COMMITTED_STATE", "end", "end" ]
Commit the currently active transaction on the session. @example Commits the transaction. session.commit_transaction @option options :write_concern [ nil | WriteConcern::Base ] The write concern to use for this operation. @raise [ Error::InvalidTransactionOperation ] If there is no active transaction. @since 2.6.0
[ "Commit", "the", "currently", "active", "transaction", "on", "the", "session", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L615-L678
train
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.abort_transaction
def abort_transaction check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_COMMITTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :commitTransaction, :abortTransaction)) end if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_twice_msg(:abortTransaction)) end begin unless starting_transaction? write_with_retry(self, txn_options[:write_concern], true) do |server, txn_num| Operation::Command.new( selector: { abortTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num ).execute(server) end end @state = TRANSACTION_ABORTED_STATE rescue Mongo::Error::InvalidTransactionOperation raise rescue Mongo::Error @state = TRANSACTION_ABORTED_STATE rescue Exception @state = TRANSACTION_ABORTED_STATE raise end end
ruby
def abort_transaction check_if_ended! check_if_no_transaction! if within_states?(TRANSACTION_COMMITTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_after_msg( :commitTransaction, :abortTransaction)) end if within_states?(TRANSACTION_ABORTED_STATE) raise Mongo::Error::InvalidTransactionOperation.new( Mongo::Error::InvalidTransactionOperation.cannot_call_twice_msg(:abortTransaction)) end begin unless starting_transaction? write_with_retry(self, txn_options[:write_concern], true) do |server, txn_num| Operation::Command.new( selector: { abortTransaction: 1 }, db_name: 'admin', session: self, txn_num: txn_num ).execute(server) end end @state = TRANSACTION_ABORTED_STATE rescue Mongo::Error::InvalidTransactionOperation raise rescue Mongo::Error @state = TRANSACTION_ABORTED_STATE rescue Exception @state = TRANSACTION_ABORTED_STATE raise end end
[ "def", "abort_transaction", "check_if_ended!", "check_if_no_transaction!", "if", "within_states?", "(", "TRANSACTION_COMMITTED_STATE", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "cannot_call_after_msg", "(", ":commitTransaction", ",", ":abortTransaction", ")", ")", "end", "if", "within_states?", "(", "TRANSACTION_ABORTED_STATE", ")", "raise", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "new", "(", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", ".", "cannot_call_twice_msg", "(", ":abortTransaction", ")", ")", "end", "begin", "unless", "starting_transaction?", "write_with_retry", "(", "self", ",", "txn_options", "[", ":write_concern", "]", ",", "true", ")", "do", "|", "server", ",", "txn_num", "|", "Operation", "::", "Command", ".", "new", "(", "selector", ":", "{", "abortTransaction", ":", "1", "}", ",", "db_name", ":", "'admin'", ",", "session", ":", "self", ",", "txn_num", ":", "txn_num", ")", ".", "execute", "(", "server", ")", "end", "end", "@state", "=", "TRANSACTION_ABORTED_STATE", "rescue", "Mongo", "::", "Error", "::", "InvalidTransactionOperation", "raise", "rescue", "Mongo", "::", "Error", "@state", "=", "TRANSACTION_ABORTED_STATE", "rescue", "Exception", "@state", "=", "TRANSACTION_ABORTED_STATE", "raise", "end", "end" ]
Abort the currently active transaction without making any changes to the database. @example Abort the transaction. session.abort_transaction @raise [ Error::InvalidTransactionOperation ] If there is no active transaction. @since 2.6.0
[ "Abort", "the", "currently", "active", "transaction", "without", "making", "any", "changes", "to", "the", "database", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L688-L724
train
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.with_transaction
def with_transaction(options=nil) # Non-configurable 120 second timeout for the entire operation deadline = Time.now + 120 transaction_in_progress = false loop do commit_options = {} if options commit_options[:write_concern] = options[:write_concern] end start_transaction(options) transaction_in_progress = true begin rv = yield self rescue Exception => e if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) abort_transaction transaction_in_progress = false end if Time.now >= deadline transaction_in_progress = false raise end if e.is_a?(Mongo::Error) && e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) next end raise else if within_states?(TRANSACTION_ABORTED_STATE, NO_TRANSACTION_STATE, TRANSACTION_COMMITTED_STATE) transaction_in_progress = false return rv end begin commit_transaction(commit_options) transaction_in_progress = false return rv rescue Mongo::Error => e if e.label?(Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) # WriteConcernFailed if e.is_a?(Mongo::Error::OperationFailure) && e.code == 64 && e.wtimeout? transaction_in_progress = false raise end if Time.now >= deadline transaction_in_progress = false raise end wc_options = case v = commit_options[:write_concern] when WriteConcern::Base v.options when nil {} else v end commit_options[:write_concern] = wc_options.merge(w: :majority) retry elsif e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) if Time.now >= deadline transaction_in_progress = false raise end next else transaction_in_progress = false raise end end end end ensure if transaction_in_progress log_warn('with_transaction callback altered with_transaction loop, aborting transaction') begin abort_transaction rescue Error::OperationFailure, Error::InvalidTransactionOperation end end end
ruby
def with_transaction(options=nil) # Non-configurable 120 second timeout for the entire operation deadline = Time.now + 120 transaction_in_progress = false loop do commit_options = {} if options commit_options[:write_concern] = options[:write_concern] end start_transaction(options) transaction_in_progress = true begin rv = yield self rescue Exception => e if within_states?(STARTING_TRANSACTION_STATE, TRANSACTION_IN_PROGRESS_STATE) abort_transaction transaction_in_progress = false end if Time.now >= deadline transaction_in_progress = false raise end if e.is_a?(Mongo::Error) && e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) next end raise else if within_states?(TRANSACTION_ABORTED_STATE, NO_TRANSACTION_STATE, TRANSACTION_COMMITTED_STATE) transaction_in_progress = false return rv end begin commit_transaction(commit_options) transaction_in_progress = false return rv rescue Mongo::Error => e if e.label?(Mongo::Error::UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) # WriteConcernFailed if e.is_a?(Mongo::Error::OperationFailure) && e.code == 64 && e.wtimeout? transaction_in_progress = false raise end if Time.now >= deadline transaction_in_progress = false raise end wc_options = case v = commit_options[:write_concern] when WriteConcern::Base v.options when nil {} else v end commit_options[:write_concern] = wc_options.merge(w: :majority) retry elsif e.label?(Mongo::Error::TRANSIENT_TRANSACTION_ERROR_LABEL) if Time.now >= deadline transaction_in_progress = false raise end next else transaction_in_progress = false raise end end end end ensure if transaction_in_progress log_warn('with_transaction callback altered with_transaction loop, aborting transaction') begin abort_transaction rescue Error::OperationFailure, Error::InvalidTransactionOperation end end end
[ "def", "with_transaction", "(", "options", "=", "nil", ")", "# Non-configurable 120 second timeout for the entire operation", "deadline", "=", "Time", ".", "now", "+", "120", "transaction_in_progress", "=", "false", "loop", "do", "commit_options", "=", "{", "}", "if", "options", "commit_options", "[", ":write_concern", "]", "=", "options", "[", ":write_concern", "]", "end", "start_transaction", "(", "options", ")", "transaction_in_progress", "=", "true", "begin", "rv", "=", "yield", "self", "rescue", "Exception", "=>", "e", "if", "within_states?", "(", "STARTING_TRANSACTION_STATE", ",", "TRANSACTION_IN_PROGRESS_STATE", ")", "abort_transaction", "transaction_in_progress", "=", "false", "end", "if", "Time", ".", "now", ">=", "deadline", "transaction_in_progress", "=", "false", "raise", "end", "if", "e", ".", "is_a?", "(", "Mongo", "::", "Error", ")", "&&", "e", ".", "label?", "(", "Mongo", "::", "Error", "::", "TRANSIENT_TRANSACTION_ERROR_LABEL", ")", "next", "end", "raise", "else", "if", "within_states?", "(", "TRANSACTION_ABORTED_STATE", ",", "NO_TRANSACTION_STATE", ",", "TRANSACTION_COMMITTED_STATE", ")", "transaction_in_progress", "=", "false", "return", "rv", "end", "begin", "commit_transaction", "(", "commit_options", ")", "transaction_in_progress", "=", "false", "return", "rv", "rescue", "Mongo", "::", "Error", "=>", "e", "if", "e", ".", "label?", "(", "Mongo", "::", "Error", "::", "UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL", ")", "# WriteConcernFailed", "if", "e", ".", "is_a?", "(", "Mongo", "::", "Error", "::", "OperationFailure", ")", "&&", "e", ".", "code", "==", "64", "&&", "e", ".", "wtimeout?", "transaction_in_progress", "=", "false", "raise", "end", "if", "Time", ".", "now", ">=", "deadline", "transaction_in_progress", "=", "false", "raise", "end", "wc_options", "=", "case", "v", "=", "commit_options", "[", ":write_concern", "]", "when", "WriteConcern", "::", "Base", "v", ".", "options", "when", "nil", "{", "}", "else", "v", "end", "commit_options", "[", ":write_concern", "]", "=", "wc_options", ".", "merge", "(", "w", ":", ":majority", ")", "retry", "elsif", "e", ".", "label?", "(", "Mongo", "::", "Error", "::", "TRANSIENT_TRANSACTION_ERROR_LABEL", ")", "if", "Time", ".", "now", ">=", "deadline", "transaction_in_progress", "=", "false", "raise", "end", "next", "else", "transaction_in_progress", "=", "false", "raise", "end", "end", "end", "end", "ensure", "if", "transaction_in_progress", "log_warn", "(", "'with_transaction callback altered with_transaction loop, aborting transaction'", ")", "begin", "abort_transaction", "rescue", "Error", "::", "OperationFailure", ",", "Error", "::", "InvalidTransactionOperation", "end", "end", "end" ]
Executes the provided block in a transaction, retrying as necessary. Returns the return value of the block. Exact number of retries and when they are performed are implementation details of the driver; the provided block should be idempotent, and should be prepared to be called more than once. The driver may retry the commit command within an active transaction or it may repeat the transaction and invoke the block again, depending on the error encountered if any. Note also that the retries may be executed against different servers. Transactions cannot be nested - InvalidTransactionOperation will be raised if this method is called when the session already has an active transaction. Exceptions raised by the block which are not derived from Mongo::Error stop processing, abort the transaction and are propagated out of with_transaction. Exceptions derived from Mongo::Error may be handled by with_transaction, resulting in retries of the process. Currently, with_transaction will retry commits and block invocations until at least 120 seconds have passed since with_transaction started executing. This timeout is not configurable and may change in a future driver version. @note with_transaction contains a loop, therefore the if with_transaction itself is placed in a loop, its block should not call next or break to control the outer loop because this will instead affect the loop in with_transaction. The driver will warn and abort the transaction if it detects this situation. @example Execute a statement in a transaction session.with_transaction(write_concern: {w: :majority}) do collection.update_one({ id: 3 }, { '$set' => { status: 'Inactive'} }, session: session) end @example Execute a statement in a transaction, limiting total time consumed Timeout.timeout(5) do session.with_transaction(write_concern: {w: :majority}) do collection.update_one({ id: 3 }, { '$set' => { status: 'Inactive'} }, session: session) end end @param [ Hash ] options The options for the transaction being started. These are the same options that start_transaction accepts. @raise [ Error::InvalidTransactionOperation ] If a transaction is already in progress or if the write concern is unacknowledged. @since 2.7.0
[ "Executes", "the", "provided", "block", "in", "a", "transaction", "retrying", "as", "necessary", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L792-L873
train
mongodb/mongo-ruby-driver
lib/mongo/session.rb
Mongo.Session.txn_read_preference
def txn_read_preference rp = txn_options && txn_options[:read_preference] || @client.read_preference Mongo::Lint.validate_underscore_read_preference(rp) rp end
ruby
def txn_read_preference rp = txn_options && txn_options[:read_preference] || @client.read_preference Mongo::Lint.validate_underscore_read_preference(rp) rp end
[ "def", "txn_read_preference", "rp", "=", "txn_options", "&&", "txn_options", "[", ":read_preference", "]", "||", "@client", ".", "read_preference", "Mongo", "::", "Lint", ".", "validate_underscore_read_preference", "(", "rp", ")", "rp", "end" ]
Get the read preference the session will use in the currently active transaction. This is a driver style hash with underscore keys. @example Get the transaction's read preference session.txn_read_preference @return [ Hash ] The read preference of the transaction. @since 2.6.0
[ "Get", "the", "read", "preference", "the", "session", "will", "use", "in", "the", "currently", "active", "transaction", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/session.rb#L886-L891
train
mongodb/mongo-ruby-driver
lib/mongo/server_selector.rb
Mongo.ServerSelector.get
def get(preference = {}) return preference if PREFERENCES.values.include?(preference.class) Mongo::Lint.validate_underscore_read_preference(preference) PREFERENCES.fetch((preference[:mode] || :primary).to_sym).new(preference) end
ruby
def get(preference = {}) return preference if PREFERENCES.values.include?(preference.class) Mongo::Lint.validate_underscore_read_preference(preference) PREFERENCES.fetch((preference[:mode] || :primary).to_sym).new(preference) end
[ "def", "get", "(", "preference", "=", "{", "}", ")", "return", "preference", "if", "PREFERENCES", ".", "values", ".", "include?", "(", "preference", ".", "class", ")", "Mongo", "::", "Lint", ".", "validate_underscore_read_preference", "(", "preference", ")", "PREFERENCES", ".", "fetch", "(", "(", "preference", "[", ":mode", "]", "||", ":primary", ")", ".", "to_sym", ")", ".", "new", "(", "preference", ")", "end" ]
Create a server selector object. @example Get a server selector object for selecting a secondary with specific tag sets. Mongo::ServerSelector.get(:mode => :secondary, :tag_sets => [{'dc' => 'nyc'}]) @param [ Hash ] preference The server preference. @since 2.0.0
[ "Create", "a", "server", "selector", "object", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/server_selector.rb#L72-L76
train
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.read_with_retry_cursor
def read_with_retry_cursor(session, server_selector, view, &block) read_with_retry(session, server_selector) do |server| result = yield server Cursor.new(view, result, server, session: session) end end
ruby
def read_with_retry_cursor(session, server_selector, view, &block) read_with_retry(session, server_selector) do |server| result = yield server Cursor.new(view, result, server, session: session) end end
[ "def", "read_with_retry_cursor", "(", "session", ",", "server_selector", ",", "view", ",", "&", "block", ")", "read_with_retry", "(", "session", ",", "server_selector", ")", "do", "|", "server", "|", "result", "=", "yield", "server", "Cursor", ".", "new", "(", "view", ",", "result", ",", "server", ",", "session", ":", "session", ")", "end", "end" ]
Execute a read operation returning a cursor with retrying. This method performs server selection for the specified server selector and yields to the provided block, which should execute the initial query operation and return its result. The block will be passed the server selected for the operation. If the block raises an exception, and this exception corresponds to a read retryable error, and read retries are enabled for the client, this method will perform server selection again and yield to the block again (with potentially a different server). If the block returns successfully, the result of the block (which should be a Mongo::Operation::Result) is used to construct a Mongo::Cursor object for the result set. The cursor is then returned. If modern retry reads are on (which is the default), the initial read operation will be retried once. If legacy retry reads are on, the initial read operation will be retried zero or more times depending on the :max_read_retries client setting, the default for which is 1. To disable read retries, turn off modern read retries by setting retry_reads: false and set :max_read_retries to 0 on the client. @api private @example Execute a read returning a cursor. cursor = read_with_retry_cursor(session, server_selector, view) do |server| # return a Mongo::Operation::Result ... end @param [ Mongo::Session ] session The session that the operation is being run on. @param [ Mongo::ServerSelector::Selectable ] server_selector Server selector for the operation. @param [ CollectionView ] view The +CollectionView+ defining the query. @param [ Proc ] block The block to execute. @return [ Cursor ] The cursor for the result set.
[ "Execute", "a", "read", "operation", "returning", "a", "cursor", "with", "retrying", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L59-L64
train
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.read_with_retry
def read_with_retry(session = nil, server_selector = nil, &block) if session.nil? && server_selector.nil? # Older versions of Mongoid call read_with_retry without arguments. # This is already not correct in a MongoDB 3.6+ environment with # sessions. For compatibility we emulate the legacy driver behavior # here but upgrading Mongoid is strongly recommended. unless $_mongo_read_with_retry_warned $_mongo_read_with_retry_warned = true Logger.logger.warn("Legacy read_with_retry invocation - please update the application and/or its dependencies") end # Since we don't have a session, we cannot use the modern read retries. # And we need to select a server but we don't have a server selector. # Use PrimaryPreferred which will work as long as there is a data # bearing node in the cluster; the block may select a different server # which is fine. server_selector = ServerSelector.get(mode: :primary_preferred) legacy_read_with_retry(nil, server_selector, &block) elsif session && session.retry_reads? modern_read_with_retry(session, server_selector, &block) elsif client.max_read_retries > 0 legacy_read_with_retry(session, server_selector, &block) else server = select_server(cluster, server_selector) yield server end end
ruby
def read_with_retry(session = nil, server_selector = nil, &block) if session.nil? && server_selector.nil? # Older versions of Mongoid call read_with_retry without arguments. # This is already not correct in a MongoDB 3.6+ environment with # sessions. For compatibility we emulate the legacy driver behavior # here but upgrading Mongoid is strongly recommended. unless $_mongo_read_with_retry_warned $_mongo_read_with_retry_warned = true Logger.logger.warn("Legacy read_with_retry invocation - please update the application and/or its dependencies") end # Since we don't have a session, we cannot use the modern read retries. # And we need to select a server but we don't have a server selector. # Use PrimaryPreferred which will work as long as there is a data # bearing node in the cluster; the block may select a different server # which is fine. server_selector = ServerSelector.get(mode: :primary_preferred) legacy_read_with_retry(nil, server_selector, &block) elsif session && session.retry_reads? modern_read_with_retry(session, server_selector, &block) elsif client.max_read_retries > 0 legacy_read_with_retry(session, server_selector, &block) else server = select_server(cluster, server_selector) yield server end end
[ "def", "read_with_retry", "(", "session", "=", "nil", ",", "server_selector", "=", "nil", ",", "&", "block", ")", "if", "session", ".", "nil?", "&&", "server_selector", ".", "nil?", "# Older versions of Mongoid call read_with_retry without arguments.", "# This is already not correct in a MongoDB 3.6+ environment with", "# sessions. For compatibility we emulate the legacy driver behavior", "# here but upgrading Mongoid is strongly recommended.", "unless", "$_mongo_read_with_retry_warned", "$_mongo_read_with_retry_warned", "=", "true", "Logger", ".", "logger", ".", "warn", "(", "\"Legacy read_with_retry invocation - please update the application and/or its dependencies\"", ")", "end", "# Since we don't have a session, we cannot use the modern read retries.", "# And we need to select a server but we don't have a server selector.", "# Use PrimaryPreferred which will work as long as there is a data", "# bearing node in the cluster; the block may select a different server", "# which is fine.", "server_selector", "=", "ServerSelector", ".", "get", "(", "mode", ":", ":primary_preferred", ")", "legacy_read_with_retry", "(", "nil", ",", "server_selector", ",", "block", ")", "elsif", "session", "&&", "session", ".", "retry_reads?", "modern_read_with_retry", "(", "session", ",", "server_selector", ",", "block", ")", "elsif", "client", ".", "max_read_retries", ">", "0", "legacy_read_with_retry", "(", "session", ",", "server_selector", ",", "block", ")", "else", "server", "=", "select_server", "(", "cluster", ",", "server_selector", ")", "yield", "server", "end", "end" ]
Execute a read operation with retrying. This method performs server selection for the specified server selector and yields to the provided block, which should execute the initial query operation and return its result. The block will be passed the server selected for the operation. If the block raises an exception, and this exception corresponds to a read retryable error, and read retries are enabled for the client, this method will perform server selection again and yield to the block again (with potentially a different server). If the block returns successfully, the result of the block is returned. If modern retry reads are on (which is the default), the initial read operation will be retried once. If legacy retry reads are on, the initial read operation will be retried zero or more times depending on the :max_read_retries client setting, the default for which is 1. To disable read retries, turn off modern read retries by setting retry_reads: false and set :max_read_retries to 0 on the client. @api private @example Execute the read. read_with_retry(session, server_selector) do |server| ... end @param [ Mongo::Session ] session The session that the operation is being run on. @param [ Mongo::ServerSelector::Selectable ] server_selector Server selector for the operation. @param [ Proc ] block The block to execute. @return [ Result ] The result of the operation.
[ "Execute", "a", "read", "operation", "with", "retrying", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L99-L124
train
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.read_with_one_retry
def read_with_one_retry(options = nil) yield rescue Error::SocketError, Error::SocketTimeoutError => e retry_message = options && options[:retry_message] log_retry(e, message: retry_message) yield end
ruby
def read_with_one_retry(options = nil) yield rescue Error::SocketError, Error::SocketTimeoutError => e retry_message = options && options[:retry_message] log_retry(e, message: retry_message) yield end
[ "def", "read_with_one_retry", "(", "options", "=", "nil", ")", "yield", "rescue", "Error", "::", "SocketError", ",", "Error", "::", "SocketTimeoutError", "=>", "e", "retry_message", "=", "options", "&&", "options", "[", ":retry_message", "]", "log_retry", "(", "e", ",", "message", ":", "retry_message", ")", "yield", "end" ]
Execute a read operation with a single retry on network errors. This method is used by the driver for some of the internal housekeeping operations. Application-requested reads should use read_with_retry rather than this method. @api private @example Execute the read. read_with_one_retry do ... end @note This only retries read operations on socket errors. @param [ Hash ] options Options. @param [ Proc ] block The block to execute. @option options [ String ] :retry_message Message to log when retrying. @return [ Result ] The result of the operation. @since 2.2.6
[ "Execute", "a", "read", "operation", "with", "a", "single", "retry", "on", "network", "errors", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L149-L155
train
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.write_with_retry
def write_with_retry(session, write_concern, ending_transaction = false, &block) if ending_transaction && !session raise ArgumentError, 'Cannot end a transaction without a session' end unless ending_transaction || retry_write_allowed?(session, write_concern) return legacy_write_with_retry(nil, session, &block) end # If we are here, session is not nil. A session being nil would have # failed retry_write_allowed? check. server = cluster.next_primary unless ending_transaction || server.retry_writes? return legacy_write_with_retry(server, session, &block) end begin txn_num = session.in_transaction? ? session.txn_num : session.next_txn_num yield(server, txn_num, false) rescue Error::SocketError, Error::SocketTimeoutError => e if session.in_transaction? && !ending_transaction raise end retry_write(e, txn_num, &block) rescue Error::OperationFailure => e if (session.in_transaction? && !ending_transaction) || !e.write_retryable? raise end retry_write(e, txn_num, &block) end end
ruby
def write_with_retry(session, write_concern, ending_transaction = false, &block) if ending_transaction && !session raise ArgumentError, 'Cannot end a transaction without a session' end unless ending_transaction || retry_write_allowed?(session, write_concern) return legacy_write_with_retry(nil, session, &block) end # If we are here, session is not nil. A session being nil would have # failed retry_write_allowed? check. server = cluster.next_primary unless ending_transaction || server.retry_writes? return legacy_write_with_retry(server, session, &block) end begin txn_num = session.in_transaction? ? session.txn_num : session.next_txn_num yield(server, txn_num, false) rescue Error::SocketError, Error::SocketTimeoutError => e if session.in_transaction? && !ending_transaction raise end retry_write(e, txn_num, &block) rescue Error::OperationFailure => e if (session.in_transaction? && !ending_transaction) || !e.write_retryable? raise end retry_write(e, txn_num, &block) end end
[ "def", "write_with_retry", "(", "session", ",", "write_concern", ",", "ending_transaction", "=", "false", ",", "&", "block", ")", "if", "ending_transaction", "&&", "!", "session", "raise", "ArgumentError", ",", "'Cannot end a transaction without a session'", "end", "unless", "ending_transaction", "||", "retry_write_allowed?", "(", "session", ",", "write_concern", ")", "return", "legacy_write_with_retry", "(", "nil", ",", "session", ",", "block", ")", "end", "# If we are here, session is not nil. A session being nil would have", "# failed retry_write_allowed? check.", "server", "=", "cluster", ".", "next_primary", "unless", "ending_transaction", "||", "server", ".", "retry_writes?", "return", "legacy_write_with_retry", "(", "server", ",", "session", ",", "block", ")", "end", "begin", "txn_num", "=", "session", ".", "in_transaction?", "?", "session", ".", "txn_num", ":", "session", ".", "next_txn_num", "yield", "(", "server", ",", "txn_num", ",", "false", ")", "rescue", "Error", "::", "SocketError", ",", "Error", "::", "SocketTimeoutError", "=>", "e", "if", "session", ".", "in_transaction?", "&&", "!", "ending_transaction", "raise", "end", "retry_write", "(", "e", ",", "txn_num", ",", "block", ")", "rescue", "Error", "::", "OperationFailure", "=>", "e", "if", "(", "session", ".", "in_transaction?", "&&", "!", "ending_transaction", ")", "||", "!", "e", ".", "write_retryable?", "raise", "end", "retry_write", "(", "e", ",", "txn_num", ",", "block", ")", "end", "end" ]
Implements write retrying functionality by yielding to the passed block one or more times. If the session is provided (hence, the deployment supports sessions), and modern retry writes are enabled on the client, the modern retry logic is invoked. Otherwise the legacy retry logic is invoked. If ending_transaction parameter is true, indicating that a transaction is being committed or aborted, the operation is executed exactly once. Note that, since transactions require sessions, this method will raise ArgumentError if ending_transaction is true and session is nil. @api private @example Execute the write. write_with_retry do ... end @note This only retries operations on not master failures, since it is the only case we can be sure a partial write did not already occur. @param [ nil | Session ] session Optional session to use with the operation. @param [ nil | Hash | WriteConcern::Base ] write_concern The write concern. @param [ true | false ] ending_transaction True if the write operation is abortTransaction or commitTransaction, false otherwise. @param [ Proc ] block The block to execute. @yieldparam [ Server ] server The server to which the write should be sent. @yieldparam [ Integer ] txn_num Transaction number (NOT the ACID kind). @return [ Result ] The result of the operation. @since 2.1.0
[ "Implements", "write", "retrying", "functionality", "by", "yielding", "to", "the", "passed", "block", "one", "or", "more", "times", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L191-L223
train
mongodb/mongo-ruby-driver
lib/mongo/retryable.rb
Mongo.Retryable.log_retry
def log_retry(e, options = nil) message = if options && options[:message] options[:message] else "Retry" end Logger.logger.warn "#{message} due to: #{e.class.name} #{e.message}" end
ruby
def log_retry(e, options = nil) message = if options && options[:message] options[:message] else "Retry" end Logger.logger.warn "#{message} due to: #{e.class.name} #{e.message}" end
[ "def", "log_retry", "(", "e", ",", "options", "=", "nil", ")", "message", "=", "if", "options", "&&", "options", "[", ":message", "]", "options", "[", ":message", "]", "else", "\"Retry\"", "end", "Logger", ".", "logger", ".", "warn", "\"#{message} due to: #{e.class.name} #{e.message}\"", "end" ]
Log a warning so that any application slow down is immediately obvious.
[ "Log", "a", "warning", "so", "that", "any", "application", "slow", "down", "is", "immediately", "obvious", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/retryable.rb#L358-L365
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.create
def create(opts = {}) operation = { :create => name }.merge(options) operation.delete(:write) server = next_primary if (options[:collation] || options[Operation::COLLATION]) && !server.features.collation_enabled? raise Error::UnsupportedCollation.new end client.send(:with_session, opts) do |session| Operation::Create.new({ selector: operation, db_name: database.name, write_concern: write_concern, session: session }).execute(server) end end
ruby
def create(opts = {}) operation = { :create => name }.merge(options) operation.delete(:write) server = next_primary if (options[:collation] || options[Operation::COLLATION]) && !server.features.collation_enabled? raise Error::UnsupportedCollation.new end client.send(:with_session, opts) do |session| Operation::Create.new({ selector: operation, db_name: database.name, write_concern: write_concern, session: session }).execute(server) end end
[ "def", "create", "(", "opts", "=", "{", "}", ")", "operation", "=", "{", ":create", "=>", "name", "}", ".", "merge", "(", "options", ")", "operation", ".", "delete", "(", ":write", ")", "server", "=", "next_primary", "if", "(", "options", "[", ":collation", "]", "||", "options", "[", "Operation", "::", "COLLATION", "]", ")", "&&", "!", "server", ".", "features", ".", "collation_enabled?", "raise", "Error", "::", "UnsupportedCollation", ".", "new", "end", "client", ".", "send", "(", ":with_session", ",", "opts", ")", "do", "|", "session", "|", "Operation", "::", "Create", ".", "new", "(", "{", "selector", ":", "operation", ",", "db_name", ":", "database", ".", "name", ",", "write_concern", ":", "write_concern", ",", "session", ":", "session", "}", ")", ".", "execute", "(", "server", ")", "end", "end" ]
Force the collection to be created in the database. @example Force the collection to be created. collection.create @param [ Hash ] opts The options for the create operation. @option options [ Session ] :session The session to use for the operation. @return [ Result ] The result of the command. @since 2.0.0
[ "Force", "the", "collection", "to", "be", "created", "in", "the", "database", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L184-L199
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.drop
def drop(opts = {}) client.send(:with_session, opts) do |session| Operation::Drop.new({ selector: { :drop => name }, db_name: database.name, write_concern: write_concern, session: session }).execute(next_primary) end rescue Error::OperationFailure => ex raise ex unless ex.message =~ /ns not found/ false end
ruby
def drop(opts = {}) client.send(:with_session, opts) do |session| Operation::Drop.new({ selector: { :drop => name }, db_name: database.name, write_concern: write_concern, session: session }).execute(next_primary) end rescue Error::OperationFailure => ex raise ex unless ex.message =~ /ns not found/ false end
[ "def", "drop", "(", "opts", "=", "{", "}", ")", "client", ".", "send", "(", ":with_session", ",", "opts", ")", "do", "|", "session", "|", "Operation", "::", "Drop", ".", "new", "(", "{", "selector", ":", "{", ":drop", "=>", "name", "}", ",", "db_name", ":", "database", ".", "name", ",", "write_concern", ":", "write_concern", ",", "session", ":", "session", "}", ")", ".", "execute", "(", "next_primary", ")", "end", "rescue", "Error", "::", "OperationFailure", "=>", "ex", "raise", "ex", "unless", "ex", ".", "message", "=~", "/", "/", "false", "end" ]
Drop the collection. Will also drop all indexes associated with the collection. @note An error returned if the collection doesn't exist is suppressed. @example Drop the collection. collection.drop @param [ Hash ] opts The options for the drop operation. @option options [ Session ] :session The session to use for the operation. @return [ Result ] The result of the command. @since 2.0.0
[ "Drop", "the", "collection", ".", "Will", "also", "drop", "all", "indexes", "associated", "with", "the", "collection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L216-L228
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.distinct
def distinct(field_name, filter = nil, options = {}) View.new(self, filter || {}, options).distinct(field_name, options) end
ruby
def distinct(field_name, filter = nil, options = {}) View.new(self, filter || {}, options).distinct(field_name, options) end
[ "def", "distinct", "(", "field_name", ",", "filter", "=", "nil", ",", "options", "=", "{", "}", ")", "View", ".", "new", "(", "self", ",", "filter", "||", "{", "}", ",", "options", ")", ".", "distinct", "(", "field_name", ",", "options", ")", "end" ]
Get a list of distinct values for a specific field. @example Get the distinct values. collection.distinct('name') @param [ Symbol, String ] field_name The name of the field. @param [ Hash ] filter The documents from which to retrieve the distinct values. @param [ Hash ] options The distinct command options. @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command to run. @option options [ Hash ] :read The read preference options. @option options [ Hash ] :collation The collation to use. @option options [ Session ] :session The session to use. @return [ Array<Object> ] The list of distinct values. @since 2.1.0
[ "Get", "a", "list", "of", "distinct", "values", "for", "a", "specific", "field", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L430-L432
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.insert_one
def insert_one(document, opts = {}) client.send(:with_session, opts) do |session| write_with_retry(session, write_concern) do |server, txn_num| Operation::Insert.new( :documents => [ document ], :db_name => database.name, :coll_name => name, :write_concern => write_concern, :bypass_document_validation => !!opts[:bypass_document_validation], :options => opts, :id_generator => client.options[:id_generator], :session => session, :txn_num => txn_num ).execute(server) end end end
ruby
def insert_one(document, opts = {}) client.send(:with_session, opts) do |session| write_with_retry(session, write_concern) do |server, txn_num| Operation::Insert.new( :documents => [ document ], :db_name => database.name, :coll_name => name, :write_concern => write_concern, :bypass_document_validation => !!opts[:bypass_document_validation], :options => opts, :id_generator => client.options[:id_generator], :session => session, :txn_num => txn_num ).execute(server) end end end
[ "def", "insert_one", "(", "document", ",", "opts", "=", "{", "}", ")", "client", ".", "send", "(", ":with_session", ",", "opts", ")", "do", "|", "session", "|", "write_with_retry", "(", "session", ",", "write_concern", ")", "do", "|", "server", ",", "txn_num", "|", "Operation", "::", "Insert", ".", "new", "(", ":documents", "=>", "[", "document", "]", ",", ":db_name", "=>", "database", ".", "name", ",", ":coll_name", "=>", "name", ",", ":write_concern", "=>", "write_concern", ",", ":bypass_document_validation", "=>", "!", "!", "opts", "[", ":bypass_document_validation", "]", ",", ":options", "=>", "opts", ",", ":id_generator", "=>", "client", ".", "options", "[", ":id_generator", "]", ",", ":session", "=>", "session", ",", ":txn_num", "=>", "txn_num", ")", ".", "execute", "(", "server", ")", "end", "end", "end" ]
Insert a single document into the collection. @example Insert a document into the collection. collection.insert_one({ name: 'test' }) @param [ Hash ] document The document to insert. @param [ Hash ] opts The insert options. @option opts [ Session ] :session The session to use for the operation. @return [ Result ] The database response wrapper. @since 2.0.0
[ "Insert", "a", "single", "document", "into", "the", "collection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L476-L492
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.insert_many
def insert_many(documents, options = {}) inserts = documents.map{ |doc| { :insert_one => doc }} bulk_write(inserts, options) end
ruby
def insert_many(documents, options = {}) inserts = documents.map{ |doc| { :insert_one => doc }} bulk_write(inserts, options) end
[ "def", "insert_many", "(", "documents", ",", "options", "=", "{", "}", ")", "inserts", "=", "documents", ".", "map", "{", "|", "doc", "|", "{", ":insert_one", "=>", "doc", "}", "}", "bulk_write", "(", "inserts", ",", "options", ")", "end" ]
Insert the provided documents into the collection. @example Insert documents into the collection. collection.insert_many([{ name: 'test' }]) @param [ Array<Hash> ] documents The documents to insert. @param [ Hash ] options The insert options. @option options [ Session ] :session The session to use for the operation. @return [ Result ] The database response wrapper. @since 2.0.0
[ "Insert", "the", "provided", "documents", "into", "the", "collection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L507-L510
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.replace_one
def replace_one(filter, replacement, options = {}) find(filter, options).replace_one(replacement, options) end
ruby
def replace_one(filter, replacement, options = {}) find(filter, options).replace_one(replacement, options) end
[ "def", "replace_one", "(", "filter", ",", "replacement", ",", "options", "=", "{", "}", ")", "find", "(", "filter", ",", "options", ")", ".", "replace_one", "(", "replacement", ",", "options", ")", "end" ]
Replaces a single document in the collection with the new document. @example Replace a single document. collection.replace_one({ name: 'test' }, { name: 'test1' }) @param [ Hash ] filter The filter to use. @param [ Hash ] replacement The replacement document.. @param [ Hash ] options The options. @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. @option options [ true, false ] :bypass_document_validation Whether or not to skip document level validation. @option options [ Hash ] :collation The collation to use. @option options [ Session ] :session The session to use. @return [ Result ] The response from the database. @since 2.1.0
[ "Replaces", "a", "single", "document", "in", "the", "collection", "with", "the", "new", "document", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L613-L615
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.update_many
def update_many(filter, update, options = {}) find(filter, options).update_many(update, options) end
ruby
def update_many(filter, update, options = {}) find(filter, options).update_many(update, options) end
[ "def", "update_many", "(", "filter", ",", "update", ",", "options", "=", "{", "}", ")", "find", "(", "filter", ",", "options", ")", ".", "update_many", "(", "update", ",", "options", ")", "end" ]
Update documents in the collection. @example Update multiple documents in the collection. collection.update_many({ name: 'test'}, '$set' => { name: 'test1' }) @param [ Hash ] filter The filter to use. @param [ Hash ] update The update statement. @param [ Hash ] options The options. @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. @option options [ true, false ] :bypass_document_validation Whether or not to skip document level validation. @option options [ Hash ] :collation The collation to use. @option options [ Array ] :array_filters A set of filters specifying to which array elements an update should apply. @option options [ Session ] :session The session to use. @return [ Result ] The response from the database. @since 2.1.0
[ "Update", "documents", "in", "the", "collection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L638-L640
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.update_one
def update_one(filter, update, options = {}) find(filter, options).update_one(update, options) end
ruby
def update_one(filter, update, options = {}) find(filter, options).update_one(update, options) end
[ "def", "update_one", "(", "filter", ",", "update", ",", "options", "=", "{", "}", ")", "find", "(", "filter", ",", "options", ")", ".", "update_one", "(", "update", ",", "options", ")", "end" ]
Update a single document in the collection. @example Update a single document in the collection. collection.update_one({ name: 'test'}, '$set' => { name: 'test1'}) @param [ Hash ] filter The filter to use. @param [ Hash ] update The update statement. @param [ Hash ] options The options. @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. @option options [ true, false ] :bypass_document_validation Whether or not to skip document level validation. @option options [ Hash ] :collation The collation to use. @option options [ Array ] :array_filters A set of filters specifying to which array elements an update should apply. @option options [ Session ] :session The session to use. @return [ Result ] The response from the database. @since 2.1.0
[ "Update", "a", "single", "document", "in", "the", "collection", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L663-L665
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.find_one_and_update
def find_one_and_update(filter, update, options = {}) find(filter, options).find_one_and_update(update, options) end
ruby
def find_one_and_update(filter, update, options = {}) find(filter, options).find_one_and_update(update, options) end
[ "def", "find_one_and_update", "(", "filter", ",", "update", ",", "options", "=", "{", "}", ")", "find", "(", "filter", ",", "options", ")", ".", "find_one_and_update", "(", "update", ",", "options", ")", "end" ]
Finds a single document via findAndModify and updates it, returning the original doc unless otherwise specified. @example Find a document and update it, returning the original. collection.find_one_and_update({ name: 'test' }, { "$set" => { name: 'test1' }}) @example Find a document and update it, returning the updated document. collection.find_one_and_update({ name: 'test' }, { "$set" => { name: 'test1' }}, :return_document => :after) @param [ Hash ] filter The filter to use. @param [ BSON::Document ] update The update statement. @param [ Hash ] options The options. @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command to run in milliseconds. @option options [ Hash ] :projection The fields to include or exclude in the returned doc. @option options [ Hash ] :sort The key and direction pairs by which the result set will be sorted. @option options [ Symbol ] :return_document Either :before or :after. @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. @option options [ true, false ] :bypass_document_validation Whether or not to skip document level validation. @option options [ Hash ] :write_concern The write concern options. Defaults to the collection's write concern. @option options [ Hash ] :collation The collation to use. @option options [ Array ] :array_filters A set of filters specifying to which array elements an update should apply. @option options [ Session ] :session The session to use. @return [ BSON::Document ] The document. @since 2.1.0
[ "Finds", "a", "single", "document", "via", "findAndModify", "and", "updates", "it", "returning", "the", "original", "doc", "unless", "otherwise", "specified", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L725-L727
train
mongodb/mongo-ruby-driver
lib/mongo/collection.rb
Mongo.Collection.find_one_and_replace
def find_one_and_replace(filter, replacement, options = {}) find(filter, options).find_one_and_update(replacement, options) end
ruby
def find_one_and_replace(filter, replacement, options = {}) find(filter, options).find_one_and_update(replacement, options) end
[ "def", "find_one_and_replace", "(", "filter", ",", "replacement", ",", "options", "=", "{", "}", ")", "find", "(", "filter", ",", "options", ")", ".", "find_one_and_update", "(", "replacement", ",", "options", ")", "end" ]
Finds a single document and replaces it, returning the original doc unless otherwise specified. @example Find a document and replace it, returning the original. collection.find_one_and_replace({ name: 'test' }, { name: 'test1' }) @example Find a document and replace it, returning the new document. collection.find_one_and_replace({ name: 'test' }, { name: 'test1' }, :return_document => :after) @param [ Hash ] filter The filter to use. @param [ BSON::Document ] replacement The replacement document. @param [ Hash ] options The options. @option options [ Integer ] :max_time_ms The maximum amount of time to allow the command to run in milliseconds. @option options [ Hash ] :projection The fields to include or exclude in the returned doc. @option options [ Hash ] :sort The key and direction pairs by which the result set will be sorted. @option options [ Symbol ] :return_document Either :before or :after. @option options [ true, false ] :upsert Whether to upsert if the document doesn't exist. @option options [ true, false ] :bypass_document_validation Whether or not to skip document level validation. @option options [ Hash ] :write_concern The write concern options. Defaults to the collection's write concern. @option options [ Hash ] :collation The collation to use. @option options [ Session ] :session The session to use. @return [ BSON::Document ] The document. @since 2.1.0
[ "Finds", "a", "single", "document", "and", "replaces", "it", "returning", "the", "original", "doc", "unless", "otherwise", "specified", "." ]
dca26d0870cb3386fad9ccc1d17228097c1fe1c8
https://github.com/mongodb/mongo-ruby-driver/blob/dca26d0870cb3386fad9ccc1d17228097c1fe1c8/lib/mongo/collection.rb#L759-L761
train
Katello/katello
app/controllers/katello/application_controller.rb
Katello.ApplicationController.render_bad_parameters
def render_bad_parameters(*args) default_message = if request.xhr? _('Invalid parameters sent in the request for this operation. Please contact a system administrator.') else _('Invalid parameters sent. You may have mistyped the address. If you continue having trouble with this, please contact an Administrator.') end exception = args.find { |o| o.is_a? Exception } message = args.find { |o| o.is_a? String } || exception.try(:message) || default_message status = if exception && exception.respond_to?(:status_code) exception.status_code else 400 end if exception log_exception exception else Rails.logger.warn message end respond_to do |format| format.html do render :template => 'common/400', :layout => !request.xhr?, :status => status, :locals => {:message => message} end format.atom { head exception.status_code } format.xml { head exception.status_code } format.json { head exception.status_code } end User.current = nil end
ruby
def render_bad_parameters(*args) default_message = if request.xhr? _('Invalid parameters sent in the request for this operation. Please contact a system administrator.') else _('Invalid parameters sent. You may have mistyped the address. If you continue having trouble with this, please contact an Administrator.') end exception = args.find { |o| o.is_a? Exception } message = args.find { |o| o.is_a? String } || exception.try(:message) || default_message status = if exception && exception.respond_to?(:status_code) exception.status_code else 400 end if exception log_exception exception else Rails.logger.warn message end respond_to do |format| format.html do render :template => 'common/400', :layout => !request.xhr?, :status => status, :locals => {:message => message} end format.atom { head exception.status_code } format.xml { head exception.status_code } format.json { head exception.status_code } end User.current = nil end
[ "def", "render_bad_parameters", "(", "*", "args", ")", "default_message", "=", "if", "request", ".", "xhr?", "_", "(", "'Invalid parameters sent in the request for this operation. Please contact a system administrator.'", ")", "else", "_", "(", "'Invalid parameters sent. You may have mistyped the address. If you continue having trouble with this, please contact an Administrator.'", ")", "end", "exception", "=", "args", ".", "find", "{", "|", "o", "|", "o", ".", "is_a?", "Exception", "}", "message", "=", "args", ".", "find", "{", "|", "o", "|", "o", ".", "is_a?", "String", "}", "||", "exception", ".", "try", "(", ":message", ")", "||", "default_message", "status", "=", "if", "exception", "&&", "exception", ".", "respond_to?", "(", ":status_code", ")", "exception", ".", "status_code", "else", "400", "end", "if", "exception", "log_exception", "exception", "else", "Rails", ".", "logger", ".", "warn", "message", "end", "respond_to", "do", "|", "format", "|", "format", ".", "html", "do", "render", ":template", "=>", "'common/400'", ",", ":layout", "=>", "!", "request", ".", "xhr?", ",", ":status", "=>", "status", ",", ":locals", "=>", "{", ":message", "=>", "message", "}", "end", "format", ".", "atom", "{", "head", "exception", ".", "status_code", "}", "format", ".", "xml", "{", "head", "exception", ".", "status_code", "}", "format", ".", "json", "{", "head", "exception", ".", "status_code", "}", "end", "User", ".", "current", "=", "nil", "end" ]
render bad params to user @overload render_bad_parameters() render bad_parameters with `default_message` and status `400` @overload render_bad_parameters(message) render bad_parameters with `message` and status `400` @param [String] message @overload render_bad_parameters(error) render bad_parameters with `error.message` and `error.status_code` if present @param [Exception] error @overload render_bad_parameters(error, message) add `message` to overload `exception.message` @param [String] message @param [Exception] error
[ "render", "bad", "params", "to", "user" ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/controllers/katello/application_controller.rb#L100-L132
train
Katello/katello
app/controllers/katello/api/v2/sync_controller.rb
Katello.Api::V2::SyncController.find_object
def find_object if params.key?(:product_id) @obj = find_product elsif params.key?(:repository_id) @obj = find_repository else fail HttpErrors::NotFound, N_("Couldn't find subject of synchronization") if @obj.nil? end @obj end
ruby
def find_object if params.key?(:product_id) @obj = find_product elsif params.key?(:repository_id) @obj = find_repository else fail HttpErrors::NotFound, N_("Couldn't find subject of synchronization") if @obj.nil? end @obj end
[ "def", "find_object", "if", "params", ".", "key?", "(", ":product_id", ")", "@obj", "=", "find_product", "elsif", "params", ".", "key?", "(", ":repository_id", ")", "@obj", "=", "find_repository", "else", "fail", "HttpErrors", "::", "NotFound", ",", "N_", "(", "\"Couldn't find subject of synchronization\"", ")", "if", "@obj", ".", "nil?", "end", "@obj", "end" ]
used in unit tests
[ "used", "in", "unit", "tests" ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/controllers/katello/api/v2/sync_controller.rb#L16-L25
train
Katello/katello
app/models/katello/kt_environment.rb
Katello.KTEnvironment.insert_successor
def insert_successor(create_params, path) self.class.transaction do new_successor = self.class.create!(create_params) if library? if path old_successor = path.first old_successor.prior = new_successor end save_successor new_successor elsif successor.nil? save_successor new_successor else old_successor = successor old_successor.prior = new_successor save_successor new_successor end fail HttpErrors::UnprocessableEntity, _('An environment is missing a prior') unless all_have_prior? new_successor end end
ruby
def insert_successor(create_params, path) self.class.transaction do new_successor = self.class.create!(create_params) if library? if path old_successor = path.first old_successor.prior = new_successor end save_successor new_successor elsif successor.nil? save_successor new_successor else old_successor = successor old_successor.prior = new_successor save_successor new_successor end fail HttpErrors::UnprocessableEntity, _('An environment is missing a prior') unless all_have_prior? new_successor end end
[ "def", "insert_successor", "(", "create_params", ",", "path", ")", "self", ".", "class", ".", "transaction", "do", "new_successor", "=", "self", ".", "class", ".", "create!", "(", "create_params", ")", "if", "library?", "if", "path", "old_successor", "=", "path", ".", "first", "old_successor", ".", "prior", "=", "new_successor", "end", "save_successor", "new_successor", "elsif", "successor", ".", "nil?", "save_successor", "new_successor", "else", "old_successor", "=", "successor", "old_successor", ".", "prior", "=", "new_successor", "save_successor", "new_successor", "end", "fail", "HttpErrors", "::", "UnprocessableEntity", ",", "_", "(", "'An environment is missing a prior'", ")", "unless", "all_have_prior?", "new_successor", "end", "end" ]
creates new env from create_params with self as a prior
[ "creates", "new", "env", "from", "create_params", "with", "self", "as", "a", "prior" ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/models/katello/kt_environment.rb#L104-L123
train
Katello/katello
app/models/katello/kt_environment.rb
Katello.KTEnvironment.full_path
def full_path p = self until p.prior.nil? || p.prior.library p = p.prior end p.prior.nil? ? p.path : [p.prior] + p.path end
ruby
def full_path p = self until p.prior.nil? || p.prior.library p = p.prior end p.prior.nil? ? p.path : [p.prior] + p.path end
[ "def", "full_path", "p", "=", "self", "until", "p", ".", "prior", ".", "nil?", "||", "p", ".", "prior", ".", "library", "p", "=", "p", ".", "prior", "end", "p", ".", "prior", ".", "nil?", "?", "p", ".", "path", ":", "[", "p", ".", "prior", "]", "+", "p", ".", "path", "end" ]
Unlike path which only gives the path from this environment going forward Get the full path, that is go to the HEAD of the path this environment is on and then give me that entire path
[ "Unlike", "path", "which", "only", "gives", "the", "path", "from", "this", "environment", "going", "forward", "Get", "the", "full", "path", "that", "is", "go", "to", "the", "HEAD", "of", "the", "path", "this", "environment", "is", "on", "and", "then", "give", "me", "that", "entire", "path" ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/models/katello/kt_environment.rb#L196-L202
train
Katello/katello
app/helpers/katello/hosts_and_hostgroups_helper.rb
Katello.HostsAndHostgroupsHelper.content_options
def content_options(host, selected_id, object_type, options = {}) include_blank = options.fetch(:include_blank, nil) include_blank = '<option></option>' if include_blank == true #check for true specifically orgs = relevant_organizations(host) all_options = [] orgs.each do |org| content_object_options = "" accessible_content_objects = if object_type == :lifecycle_environment accessible_lifecycle_environments(org, host) elsif object_type == :content_source accessible_content_proxies(host) end accessible_content_objects.each do |content_object| selected = selected_id == content_object.id ? 'selected' : '' content_object_options << %(<option value="#{content_object.id}" class="kt-env" #{selected}>#{h(content_object.name)}</option>) end if orgs.count > 1 all_options << %(<optgroup label="#{org.name}">#{content_object_options}</optgroup>) else all_options << content_object_options end end all_options = all_options.join all_options.insert(0, include_blank) if include_blank all_options.html_safe end
ruby
def content_options(host, selected_id, object_type, options = {}) include_blank = options.fetch(:include_blank, nil) include_blank = '<option></option>' if include_blank == true #check for true specifically orgs = relevant_organizations(host) all_options = [] orgs.each do |org| content_object_options = "" accessible_content_objects = if object_type == :lifecycle_environment accessible_lifecycle_environments(org, host) elsif object_type == :content_source accessible_content_proxies(host) end accessible_content_objects.each do |content_object| selected = selected_id == content_object.id ? 'selected' : '' content_object_options << %(<option value="#{content_object.id}" class="kt-env" #{selected}>#{h(content_object.name)}</option>) end if orgs.count > 1 all_options << %(<optgroup label="#{org.name}">#{content_object_options}</optgroup>) else all_options << content_object_options end end all_options = all_options.join all_options.insert(0, include_blank) if include_blank all_options.html_safe end
[ "def", "content_options", "(", "host", ",", "selected_id", ",", "object_type", ",", "options", "=", "{", "}", ")", "include_blank", "=", "options", ".", "fetch", "(", ":include_blank", ",", "nil", ")", "include_blank", "=", "'<option></option>'", "if", "include_blank", "==", "true", "#check for true specifically", "orgs", "=", "relevant_organizations", "(", "host", ")", "all_options", "=", "[", "]", "orgs", ".", "each", "do", "|", "org", "|", "content_object_options", "=", "\"\"", "accessible_content_objects", "=", "if", "object_type", "==", ":lifecycle_environment", "accessible_lifecycle_environments", "(", "org", ",", "host", ")", "elsif", "object_type", "==", ":content_source", "accessible_content_proxies", "(", "host", ")", "end", "accessible_content_objects", ".", "each", "do", "|", "content_object", "|", "selected", "=", "selected_id", "==", "content_object", ".", "id", "?", "'selected'", ":", "''", "content_object_options", "<<", "%(<option value=\"#{content_object.id}\" class=\"kt-env\" #{selected}>#{h(content_object.name)}</option>)", "end", "if", "orgs", ".", "count", ">", "1", "all_options", "<<", "%(<optgroup label=\"#{org.name}\">#{content_object_options}</optgroup>)", "else", "all_options", "<<", "content_object_options", "end", "end", "all_options", "=", "all_options", ".", "join", "all_options", ".", "insert", "(", "0", ",", "include_blank", ")", "if", "include_blank", "all_options", ".", "html_safe", "end" ]
Generic method to provide a list of options in the UI
[ "Generic", "method", "to", "provide", "a", "list", "of", "options", "in", "the", "UI" ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/helpers/katello/hosts_and_hostgroups_helper.rb#L105-L132
train
Katello/katello
app/controllers/katello/sync_management_controller.rb
Katello.SyncManagementController.sync_repos
def sync_repos(repo_ids) collected = [] repos = Repository.where(:id => repo_ids).syncable repos.each do |repo| if latest_task(repo).try(:state) != 'running' ForemanTasks.async_task(::Actions::Katello::Repository::Sync, repo) end collected << format_sync_progress(repo) end collected end
ruby
def sync_repos(repo_ids) collected = [] repos = Repository.where(:id => repo_ids).syncable repos.each do |repo| if latest_task(repo).try(:state) != 'running' ForemanTasks.async_task(::Actions::Katello::Repository::Sync, repo) end collected << format_sync_progress(repo) end collected end
[ "def", "sync_repos", "(", "repo_ids", ")", "collected", "=", "[", "]", "repos", "=", "Repository", ".", "where", "(", ":id", "=>", "repo_ids", ")", ".", "syncable", "repos", ".", "each", "do", "|", "repo", "|", "if", "latest_task", "(", "repo", ")", ".", "try", "(", ":state", ")", "!=", "'running'", "ForemanTasks", ".", "async_task", "(", "::", "Actions", "::", "Katello", "::", "Repository", "::", "Sync", ",", "repo", ")", "end", "collected", "<<", "format_sync_progress", "(", "repo", ")", "end", "collected", "end" ]
loop through checkbox list of products and sync
[ "loop", "through", "checkbox", "list", "of", "products", "and", "sync" ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/controllers/katello/sync_management_controller.rb#L62-L72
train
Katello/katello
app/models/katello/repository.rb
Katello.Repository.dynflow_handled_last_sync?
def dynflow_handled_last_sync?(pulp_task_id) task = ForemanTasks::Task::DynflowTask.for_action(::Actions::Katello::Repository::Sync). for_resource(self).order(:started_at).last return task && task.main_action.pulp_task_id == pulp_task_id end
ruby
def dynflow_handled_last_sync?(pulp_task_id) task = ForemanTasks::Task::DynflowTask.for_action(::Actions::Katello::Repository::Sync). for_resource(self).order(:started_at).last return task && task.main_action.pulp_task_id == pulp_task_id end
[ "def", "dynflow_handled_last_sync?", "(", "pulp_task_id", ")", "task", "=", "ForemanTasks", "::", "Task", "::", "DynflowTask", ".", "for_action", "(", "::", "Actions", "::", "Katello", "::", "Repository", "::", "Sync", ")", ".", "for_resource", "(", "self", ")", ".", "order", "(", ":started_at", ")", ".", "last", "return", "task", "&&", "task", ".", "main_action", ".", "pulp_task_id", "==", "pulp_task_id", "end" ]
Returns true if the pulp_task_id was triggered by the last synchronization action for the repository. Dynflow action handles the synchronization by it's own so no need to synchronize it again in this callback. Since the callbacks are run just after synchronization is finished, it should be enough to check for the last synchronization task.
[ "Returns", "true", "if", "the", "pulp_task_id", "was", "triggered", "by", "the", "last", "synchronization", "action", "for", "the", "repository", ".", "Dynflow", "action", "handles", "the", "synchronization", "by", "it", "s", "own", "so", "no", "need", "to", "synchronize", "it", "again", "in", "this", "callback", ".", "Since", "the", "callbacks", "are", "run", "just", "after", "synchronization", "is", "finished", "it", "should", "be", "enough", "to", "check", "for", "the", "last", "synchronization", "task", "." ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/models/katello/repository.rb#L342-L346
train
Katello/katello
app/models/katello/repository.rb
Katello.Repository.destroyable?
def destroyable? if self.environment.try(:library?) && self.content_view.default? if self.environment.organization.being_deleted? return true elsif self.custom? && self.deletable? return true elsif !self.custom? && self.redhat_deletable? return true else errors.add(:base, _("Repository cannot be deleted since it has already been included in a published Content View. " \ "Please delete all Content View versions containing this repository before attempting to delete it.")) return false end end return true end
ruby
def destroyable? if self.environment.try(:library?) && self.content_view.default? if self.environment.organization.being_deleted? return true elsif self.custom? && self.deletable? return true elsif !self.custom? && self.redhat_deletable? return true else errors.add(:base, _("Repository cannot be deleted since it has already been included in a published Content View. " \ "Please delete all Content View versions containing this repository before attempting to delete it.")) return false end end return true end
[ "def", "destroyable?", "if", "self", ".", "environment", ".", "try", "(", ":library?", ")", "&&", "self", ".", "content_view", ".", "default?", "if", "self", ".", "environment", ".", "organization", ".", "being_deleted?", "return", "true", "elsif", "self", ".", "custom?", "&&", "self", ".", "deletable?", "return", "true", "elsif", "!", "self", ".", "custom?", "&&", "self", ".", "redhat_deletable?", "return", "true", "else", "errors", ".", "add", "(", ":base", ",", "_", "(", "\"Repository cannot be deleted since it has already been included in a published Content View. \"", "\"Please delete all Content View versions containing this repository before attempting to delete it.\"", ")", ")", "return", "false", "end", "end", "return", "true", "end" ]
deleteable? is already taken by the authorization mixin
[ "deleteable?", "is", "already", "taken", "by", "the", "authorization", "mixin" ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/models/katello/repository.rb#L575-L591
train
Katello/katello
app/models/katello/content_view.rb
Katello.ContentView.component_ids=
def component_ids=(component_version_ids_to_set) content_view_components.destroy_all component_version_ids_to_set.each do |content_view_version_id| cvv = ContentViewVersion.find(content_view_version_id) content_view_components.build(:content_view_version => cvv, :latest => false, :composite_content_view => self) end end
ruby
def component_ids=(component_version_ids_to_set) content_view_components.destroy_all component_version_ids_to_set.each do |content_view_version_id| cvv = ContentViewVersion.find(content_view_version_id) content_view_components.build(:content_view_version => cvv, :latest => false, :composite_content_view => self) end end
[ "def", "component_ids", "=", "(", "component_version_ids_to_set", ")", "content_view_components", ".", "destroy_all", "component_version_ids_to_set", ".", "each", "do", "|", "content_view_version_id", "|", "cvv", "=", "ContentViewVersion", ".", "find", "(", "content_view_version_id", ")", "content_view_components", ".", "build", "(", ":content_view_version", "=>", "cvv", ",", ":latest", "=>", "false", ",", ":composite_content_view", "=>", "self", ")", "end", "end" ]
Warning this call wipes out existing associations And replaces them with the component version ids passed in.
[ "Warning", "this", "call", "wipes", "out", "existing", "associations", "And", "replaces", "them", "with", "the", "component", "version", "ids", "passed", "in", "." ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/models/katello/content_view.rb#L119-L127
train
Katello/katello
app/models/katello/content_view.rb
Katello.ContentView.all_version_library_instances
def all_version_library_instances all_repos = all_version_repos.where(:library_instance_id => nil).pluck("#{Katello::Repository.table_name}.id") all_repos += all_version_repos.pluck(:library_instance_id) Repository.where(:id => all_repos) end
ruby
def all_version_library_instances all_repos = all_version_repos.where(:library_instance_id => nil).pluck("#{Katello::Repository.table_name}.id") all_repos += all_version_repos.pluck(:library_instance_id) Repository.where(:id => all_repos) end
[ "def", "all_version_library_instances", "all_repos", "=", "all_version_repos", ".", "where", "(", ":library_instance_id", "=>", "nil", ")", ".", "pluck", "(", "\"#{Katello::Repository.table_name}.id\"", ")", "all_repos", "+=", "all_version_repos", ".", "pluck", "(", ":library_instance_id", ")", "Repository", ".", "where", "(", ":id", "=>", "all_repos", ")", "end" ]
get the library instances of all repos within this view
[ "get", "the", "library", "instances", "of", "all", "repos", "within", "this", "view" ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/models/katello/content_view.rb#L367-L371
train
Katello/katello
app/models/katello/content_view.rb
Katello.ContentView.add_environment
def add_environment(env, version) if self.content_view_environments.where(:environment_id => env.id).empty? label = generate_cp_environment_label(env) ContentViewEnvironment.create!(:name => label, :label => label, :cp_id => generate_cp_environment_id(env), :environment_id => env.id, :content_view => self, :content_view_version => version ) end end
ruby
def add_environment(env, version) if self.content_view_environments.where(:environment_id => env.id).empty? label = generate_cp_environment_label(env) ContentViewEnvironment.create!(:name => label, :label => label, :cp_id => generate_cp_environment_id(env), :environment_id => env.id, :content_view => self, :content_view_version => version ) end end
[ "def", "add_environment", "(", "env", ",", "version", ")", "if", "self", ".", "content_view_environments", ".", "where", "(", ":environment_id", "=>", "env", ".", "id", ")", ".", "empty?", "label", "=", "generate_cp_environment_label", "(", "env", ")", "ContentViewEnvironment", ".", "create!", "(", ":name", "=>", "label", ",", ":label", "=>", "label", ",", ":cp_id", "=>", "generate_cp_environment_id", "(", "env", ")", ",", ":environment_id", "=>", "env", ".", "id", ",", ":content_view", "=>", "self", ",", ":content_view_version", "=>", "version", ")", "end", "end" ]
Associate an environment with this content view. This can occur whenever a version of the view is promoted to an environment. It is necessary for candlepin to become aware that the view is available for consumers.
[ "Associate", "an", "environment", "with", "this", "content", "view", ".", "This", "can", "occur", "whenever", "a", "version", "of", "the", "view", "is", "promoted", "to", "an", "environment", ".", "It", "is", "necessary", "for", "candlepin", "to", "become", "aware", "that", "the", "view", "is", "available", "for", "consumers", "." ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/models/katello/content_view.rb#L463-L474
train
Katello/katello
app/models/katello/content_view.rb
Katello.ContentView.remove_environment
def remove_environment(env) # Do not remove the content view environment, if there is still a view # version in the environment. if self.versions.in_environment(env).blank? view_env = self.content_view_environments.where(:environment_id => env.id) view_env.first.destroy unless view_env.blank? end end
ruby
def remove_environment(env) # Do not remove the content view environment, if there is still a view # version in the environment. if self.versions.in_environment(env).blank? view_env = self.content_view_environments.where(:environment_id => env.id) view_env.first.destroy unless view_env.blank? end end
[ "def", "remove_environment", "(", "env", ")", "# Do not remove the content view environment, if there is still a view", "# version in the environment.", "if", "self", ".", "versions", ".", "in_environment", "(", "env", ")", ".", "blank?", "view_env", "=", "self", ".", "content_view_environments", ".", "where", "(", ":environment_id", "=>", "env", ".", "id", ")", "view_env", ".", "first", ".", "destroy", "unless", "view_env", ".", "blank?", "end", "end" ]
Unassociate an environment from this content view. This can occur whenever a view is deleted from an environment. It is necessary to make candlepin aware that the view is no longer available for consumers.
[ "Unassociate", "an", "environment", "from", "this", "content", "view", ".", "This", "can", "occur", "whenever", "a", "view", "is", "deleted", "from", "an", "environment", ".", "It", "is", "necessary", "to", "make", "candlepin", "aware", "that", "the", "view", "is", "no", "longer", "available", "for", "consumers", "." ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/models/katello/content_view.rb#L479-L486
train
Katello/katello
app/models/katello/pulp_sync_status.rb
Katello.PulpSyncProgress.format_errors
def format_errors(details) errors = {messages: [], details: []} if details && !details.key?(:finished_count) details.each do |step, report| if step == "content" parse_content(report, errors) else parse_generic(report, errors) end end end errors end
ruby
def format_errors(details) errors = {messages: [], details: []} if details && !details.key?(:finished_count) details.each do |step, report| if step == "content" parse_content(report, errors) else parse_generic(report, errors) end end end errors end
[ "def", "format_errors", "(", "details", ")", "errors", "=", "{", "messages", ":", "[", "]", ",", "details", ":", "[", "]", "}", "if", "details", "&&", "!", "details", ".", "key?", "(", ":finished_count", ")", "details", ".", "each", "do", "|", "step", ",", "report", "|", "if", "step", "==", "\"content\"", "parse_content", "(", "report", ",", "errors", ")", "else", "parse_generic", "(", "report", ",", "errors", ")", "end", "end", "end", "errors", "end" ]
Possible formats coming from pulp We ignore this case: {'finished_count' => {}} We extract from this case: {'content' => {'error' => ''}, 'errata' => {'error' => ''}, 'packages' => {'error' => ''}, 'metadata' => {'error_details => ''} }
[ "Possible", "formats", "coming", "from", "pulp" ]
a1c9280067607999cae43bab89b53ba870856b76
https://github.com/Katello/katello/blob/a1c9280067607999cae43bab89b53ba870856b76/app/models/katello/pulp_sync_status.rb#L68-L82
train
3scale/3scale_toolbox
lib/3scale_toolbox/configuration.rb
ThreeScaleToolbox.Configuration.read
def read @store.transaction(true) do @store.roots.each_with_object({}) do |key, obj| obj[key] = @store[key] end end end
ruby
def read @store.transaction(true) do @store.roots.each_with_object({}) do |key, obj| obj[key] = @store[key] end end end
[ "def", "read", "@store", ".", "transaction", "(", "true", ")", "do", "@store", ".", "roots", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "key", ",", "obj", "|", "obj", "[", "key", "]", "=", "@store", "[", "key", "]", "end", "end", "end" ]
returns copy of data stored
[ "returns", "copy", "of", "data", "stored" ]
aeb19add0ae2348788b0b21f641bf88bf7003ea3
https://github.com/3scale/3scale_toolbox/blob/aeb19add0ae2348788b0b21f641bf88bf7003ea3/lib/3scale_toolbox/configuration.rb#L27-L33
train
3scale/3scale_toolbox
lib/3scale_toolbox/remotes.rb
ThreeScaleToolbox.Remotes.update
def update config.update(:remotes) do |rmts| yield(rmts || {}).tap do |new_rmts| raise_invalid unless validate(new_rmts) end end end
ruby
def update config.update(:remotes) do |rmts| yield(rmts || {}).tap do |new_rmts| raise_invalid unless validate(new_rmts) end end end
[ "def", "update", "config", ".", "update", "(", ":remotes", ")", "do", "|", "rmts", "|", "yield", "(", "rmts", "||", "{", "}", ")", ".", "tap", "do", "|", "new_rmts", "|", "raise_invalid", "unless", "validate", "(", "new_rmts", ")", "end", "end", "end" ]
Update remotes Perform validation
[ "Update", "remotes", "Perform", "validation" ]
aeb19add0ae2348788b0b21f641bf88bf7003ea3
https://github.com/3scale/3scale_toolbox/blob/aeb19add0ae2348788b0b21f641bf88bf7003ea3/lib/3scale_toolbox/remotes.rb#L66-L72
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.subscribe
def subscribe(*topics) # Create topic partition list with topics and no partition set tpl = TopicPartitionList.new_native_tpl(topics.length) topics.each do |topic| Rdkafka::Bindings.rd_kafka_topic_partition_list_add( tpl, topic, -1 ) end # Subscribe to topic partition list and check this was successful response = Rdkafka::Bindings.rd_kafka_subscribe(@native_kafka, tpl) if response != 0 raise Rdkafka::RdkafkaError.new(response, "Error subscribing to '#{topics.join(', ')}'") end end
ruby
def subscribe(*topics) # Create topic partition list with topics and no partition set tpl = TopicPartitionList.new_native_tpl(topics.length) topics.each do |topic| Rdkafka::Bindings.rd_kafka_topic_partition_list_add( tpl, topic, -1 ) end # Subscribe to topic partition list and check this was successful response = Rdkafka::Bindings.rd_kafka_subscribe(@native_kafka, tpl) if response != 0 raise Rdkafka::RdkafkaError.new(response, "Error subscribing to '#{topics.join(', ')}'") end end
[ "def", "subscribe", "(", "*", "topics", ")", "# Create topic partition list with topics and no partition set", "tpl", "=", "TopicPartitionList", ".", "new_native_tpl", "(", "topics", ".", "length", ")", "topics", ".", "each", "do", "|", "topic", "|", "Rdkafka", "::", "Bindings", ".", "rd_kafka_topic_partition_list_add", "(", "tpl", ",", "topic", ",", "-", "1", ")", "end", "# Subscribe to topic partition list and check this was successful", "response", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_subscribe", "(", "@native_kafka", ",", "tpl", ")", "if", "response", "!=", "0", "raise", "Rdkafka", "::", "RdkafkaError", ".", "new", "(", "response", ",", "\"Error subscribing to '#{topics.join(', ')}'\"", ")", "end", "end" ]
Subscribe to one or more topics letting Kafka handle partition assignments. @param topics [Array<String>] One or more topic names @raise [RdkafkaError] When subscribing fails @return [nil]
[ "Subscribe", "to", "one", "or", "more", "topics", "letting", "Kafka", "handle", "partition", "assignments", "." ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L31-L47
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.unsubscribe
def unsubscribe response = Rdkafka::Bindings.rd_kafka_unsubscribe(@native_kafka) if response != 0 raise Rdkafka::RdkafkaError.new(response) end end
ruby
def unsubscribe response = Rdkafka::Bindings.rd_kafka_unsubscribe(@native_kafka) if response != 0 raise Rdkafka::RdkafkaError.new(response) end end
[ "def", "unsubscribe", "response", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_unsubscribe", "(", "@native_kafka", ")", "if", "response", "!=", "0", "raise", "Rdkafka", "::", "RdkafkaError", ".", "new", "(", "response", ")", "end", "end" ]
Unsubscribe from all subscribed topics. @raise [RdkafkaError] When unsubscribing fails @return [nil]
[ "Unsubscribe", "from", "all", "subscribed", "topics", "." ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L54-L59
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.pause
def pause(list) unless list.is_a?(TopicPartitionList) raise TypeError.new("list has to be a TopicPartitionList") end tpl = list.to_native_tpl response = Rdkafka::Bindings.rd_kafka_pause_partitions(@native_kafka, tpl) if response != 0 list = TopicPartitionList.from_native_tpl(tpl) raise Rdkafka::RdkafkaTopicPartitionListError.new(response, list, "Error pausing '#{list.to_h}'") end end
ruby
def pause(list) unless list.is_a?(TopicPartitionList) raise TypeError.new("list has to be a TopicPartitionList") end tpl = list.to_native_tpl response = Rdkafka::Bindings.rd_kafka_pause_partitions(@native_kafka, tpl) if response != 0 list = TopicPartitionList.from_native_tpl(tpl) raise Rdkafka::RdkafkaTopicPartitionListError.new(response, list, "Error pausing '#{list.to_h}'") end end
[ "def", "pause", "(", "list", ")", "unless", "list", ".", "is_a?", "(", "TopicPartitionList", ")", "raise", "TypeError", ".", "new", "(", "\"list has to be a TopicPartitionList\"", ")", "end", "tpl", "=", "list", ".", "to_native_tpl", "response", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_pause_partitions", "(", "@native_kafka", ",", "tpl", ")", "if", "response", "!=", "0", "list", "=", "TopicPartitionList", ".", "from_native_tpl", "(", "tpl", ")", "raise", "Rdkafka", "::", "RdkafkaTopicPartitionListError", ".", "new", "(", "response", ",", "list", ",", "\"Error pausing '#{list.to_h}'\"", ")", "end", "end" ]
Pause producing or consumption for the provided list of partitions @param list [TopicPartitionList] The topic with partitions to pause @raise [RdkafkaTopicPartitionListError] When pausing subscription fails. @return [nil]
[ "Pause", "producing", "or", "consumption", "for", "the", "provided", "list", "of", "partitions" ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L68-L79
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.resume
def resume(list) unless list.is_a?(TopicPartitionList) raise TypeError.new("list has to be a TopicPartitionList") end tpl = list.to_native_tpl response = Rdkafka::Bindings.rd_kafka_resume_partitions(@native_kafka, tpl) if response != 0 raise Rdkafka::RdkafkaError.new(response, "Error resume '#{list.to_h}'") end end
ruby
def resume(list) unless list.is_a?(TopicPartitionList) raise TypeError.new("list has to be a TopicPartitionList") end tpl = list.to_native_tpl response = Rdkafka::Bindings.rd_kafka_resume_partitions(@native_kafka, tpl) if response != 0 raise Rdkafka::RdkafkaError.new(response, "Error resume '#{list.to_h}'") end end
[ "def", "resume", "(", "list", ")", "unless", "list", ".", "is_a?", "(", "TopicPartitionList", ")", "raise", "TypeError", ".", "new", "(", "\"list has to be a TopicPartitionList\"", ")", "end", "tpl", "=", "list", ".", "to_native_tpl", "response", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_resume_partitions", "(", "@native_kafka", ",", "tpl", ")", "if", "response", "!=", "0", "raise", "Rdkafka", "::", "RdkafkaError", ".", "new", "(", "response", ",", "\"Error resume '#{list.to_h}'\"", ")", "end", "end" ]
Resume producing consumption for the provided list of partitions @param list [TopicPartitionList] The topic with partitions to pause @raise [RdkafkaError] When resume subscription fails. @return [nil]
[ "Resume", "producing", "consumption", "for", "the", "provided", "list", "of", "partitions" ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L88-L97
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.subscription
def subscription tpl = FFI::MemoryPointer.new(:pointer) response = Rdkafka::Bindings.rd_kafka_subscription(@native_kafka, tpl) if response != 0 raise Rdkafka::RdkafkaError.new(response) end tpl = tpl.read(:pointer).tap { |it| it.autorelease = false } begin Rdkafka::Consumer::TopicPartitionList.from_native_tpl(tpl) ensure Rdkafka::Bindings.rd_kafka_topic_partition_list_destroy(tpl) end end
ruby
def subscription tpl = FFI::MemoryPointer.new(:pointer) response = Rdkafka::Bindings.rd_kafka_subscription(@native_kafka, tpl) if response != 0 raise Rdkafka::RdkafkaError.new(response) end tpl = tpl.read(:pointer).tap { |it| it.autorelease = false } begin Rdkafka::Consumer::TopicPartitionList.from_native_tpl(tpl) ensure Rdkafka::Bindings.rd_kafka_topic_partition_list_destroy(tpl) end end
[ "def", "subscription", "tpl", "=", "FFI", "::", "MemoryPointer", ".", "new", "(", ":pointer", ")", "response", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_subscription", "(", "@native_kafka", ",", "tpl", ")", "if", "response", "!=", "0", "raise", "Rdkafka", "::", "RdkafkaError", ".", "new", "(", "response", ")", "end", "tpl", "=", "tpl", ".", "read", "(", ":pointer", ")", ".", "tap", "{", "|", "it", "|", "it", ".", "autorelease", "=", "false", "}", "begin", "Rdkafka", "::", "Consumer", "::", "TopicPartitionList", ".", "from_native_tpl", "(", "tpl", ")", "ensure", "Rdkafka", "::", "Bindings", ".", "rd_kafka_topic_partition_list_destroy", "(", "tpl", ")", "end", "end" ]
Return the current subscription to topics and partitions @raise [RdkafkaError] When getting the subscription fails. @return [TopicPartitionList]
[ "Return", "the", "current", "subscription", "to", "topics", "and", "partitions" ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L104-L117
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.assign
def assign(list) unless list.is_a?(TopicPartitionList) raise TypeError.new("list has to be a TopicPartitionList") end tpl = list.to_native_tpl response = Rdkafka::Bindings.rd_kafka_assign(@native_kafka, tpl) if response != 0 raise Rdkafka::RdkafkaError.new(response, "Error assigning '#{list.to_h}'") end end
ruby
def assign(list) unless list.is_a?(TopicPartitionList) raise TypeError.new("list has to be a TopicPartitionList") end tpl = list.to_native_tpl response = Rdkafka::Bindings.rd_kafka_assign(@native_kafka, tpl) if response != 0 raise Rdkafka::RdkafkaError.new(response, "Error assigning '#{list.to_h}'") end end
[ "def", "assign", "(", "list", ")", "unless", "list", ".", "is_a?", "(", "TopicPartitionList", ")", "raise", "TypeError", ".", "new", "(", "\"list has to be a TopicPartitionList\"", ")", "end", "tpl", "=", "list", ".", "to_native_tpl", "response", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_assign", "(", "@native_kafka", ",", "tpl", ")", "if", "response", "!=", "0", "raise", "Rdkafka", "::", "RdkafkaError", ".", "new", "(", "response", ",", "\"Error assigning '#{list.to_h}'\"", ")", "end", "end" ]
Atomic assignment of partitions to consume @param list [TopicPartitionList] The topic with partitions to assign @raise [RdkafkaError] When assigning fails
[ "Atomic", "assignment", "of", "partitions", "to", "consume" ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L124-L133
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.committed
def committed(list=nil, timeout_ms=1200) if list.nil? list = assignment elsif !list.is_a?(TopicPartitionList) raise TypeError.new("list has to be nil or a TopicPartitionList") end tpl = list.to_native_tpl response = Rdkafka::Bindings.rd_kafka_committed(@native_kafka, tpl, timeout_ms) if response != 0 raise Rdkafka::RdkafkaError.new(response) end TopicPartitionList.from_native_tpl(tpl) end
ruby
def committed(list=nil, timeout_ms=1200) if list.nil? list = assignment elsif !list.is_a?(TopicPartitionList) raise TypeError.new("list has to be nil or a TopicPartitionList") end tpl = list.to_native_tpl response = Rdkafka::Bindings.rd_kafka_committed(@native_kafka, tpl, timeout_ms) if response != 0 raise Rdkafka::RdkafkaError.new(response) end TopicPartitionList.from_native_tpl(tpl) end
[ "def", "committed", "(", "list", "=", "nil", ",", "timeout_ms", "=", "1200", ")", "if", "list", ".", "nil?", "list", "=", "assignment", "elsif", "!", "list", ".", "is_a?", "(", "TopicPartitionList", ")", "raise", "TypeError", ".", "new", "(", "\"list has to be nil or a TopicPartitionList\"", ")", "end", "tpl", "=", "list", ".", "to_native_tpl", "response", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_committed", "(", "@native_kafka", ",", "tpl", ",", "timeout_ms", ")", "if", "response", "!=", "0", "raise", "Rdkafka", "::", "RdkafkaError", ".", "new", "(", "response", ")", "end", "TopicPartitionList", ".", "from_native_tpl", "(", "tpl", ")", "end" ]
Return the current committed offset per partition for this consumer group. The offset field of each requested partition will either be set to stored offset or to -1001 in case there was no stored offset for that partition. @param list [TopicPartitionList, nil] The topic with partitions to get the offsets for or nil to use the current subscription. @param timeout_ms [Integer] The timeout for fetching this information. @raise [RdkafkaError] When getting the committed positions fails. @return [TopicPartitionList]
[ "Return", "the", "current", "committed", "offset", "per", "partition", "for", "this", "consumer", "group", ".", "The", "offset", "field", "of", "each", "requested", "partition", "will", "either", "be", "set", "to", "stored", "offset", "or", "to", "-", "1001", "in", "case", "there", "was", "no", "stored", "offset", "for", "that", "partition", "." ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L165-L177
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.store_offset
def store_offset(message) # rd_kafka_offset_store is one of the few calls that does not support # a string as the topic, so create a native topic for it. native_topic = Rdkafka::Bindings.rd_kafka_topic_new( @native_kafka, message.topic, nil ) response = Rdkafka::Bindings.rd_kafka_offset_store( native_topic, message.partition, message.offset ) if response != 0 raise Rdkafka::RdkafkaError.new(response) end ensure if native_topic && !native_topic.null? Rdkafka::Bindings.rd_kafka_topic_destroy(native_topic) end end
ruby
def store_offset(message) # rd_kafka_offset_store is one of the few calls that does not support # a string as the topic, so create a native topic for it. native_topic = Rdkafka::Bindings.rd_kafka_topic_new( @native_kafka, message.topic, nil ) response = Rdkafka::Bindings.rd_kafka_offset_store( native_topic, message.partition, message.offset ) if response != 0 raise Rdkafka::RdkafkaError.new(response) end ensure if native_topic && !native_topic.null? Rdkafka::Bindings.rd_kafka_topic_destroy(native_topic) end end
[ "def", "store_offset", "(", "message", ")", "# rd_kafka_offset_store is one of the few calls that does not support", "# a string as the topic, so create a native topic for it.", "native_topic", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_topic_new", "(", "@native_kafka", ",", "message", ".", "topic", ",", "nil", ")", "response", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_offset_store", "(", "native_topic", ",", "message", ".", "partition", ",", "message", ".", "offset", ")", "if", "response", "!=", "0", "raise", "Rdkafka", "::", "RdkafkaError", ".", "new", "(", "response", ")", "end", "ensure", "if", "native_topic", "&&", "!", "native_topic", ".", "null?", "Rdkafka", "::", "Bindings", ".", "rd_kafka_topic_destroy", "(", "native_topic", ")", "end", "end" ]
Store offset of a message to be used in the next commit of this consumer When using this `enable.auto.offset.store` should be set to `false` in the config. @param message [Rdkafka::Consumer::Message] The message which offset will be stored @raise [RdkafkaError] When storing the offset fails @return [nil]
[ "Store", "offset", "of", "a", "message", "to", "be", "used", "in", "the", "next", "commit", "of", "this", "consumer" ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L263-L283
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.commit
def commit(list=nil, async=false) if !list.nil? && !list.is_a?(TopicPartitionList) raise TypeError.new("list has to be nil or a TopicPartitionList") end tpl = if list list.to_native_tpl else nil end response = Rdkafka::Bindings.rd_kafka_commit(@native_kafka, tpl, async) if response != 0 raise Rdkafka::RdkafkaError.new(response) end end
ruby
def commit(list=nil, async=false) if !list.nil? && !list.is_a?(TopicPartitionList) raise TypeError.new("list has to be nil or a TopicPartitionList") end tpl = if list list.to_native_tpl else nil end response = Rdkafka::Bindings.rd_kafka_commit(@native_kafka, tpl, async) if response != 0 raise Rdkafka::RdkafkaError.new(response) end end
[ "def", "commit", "(", "list", "=", "nil", ",", "async", "=", "false", ")", "if", "!", "list", ".", "nil?", "&&", "!", "list", ".", "is_a?", "(", "TopicPartitionList", ")", "raise", "TypeError", ".", "new", "(", "\"list has to be nil or a TopicPartitionList\"", ")", "end", "tpl", "=", "if", "list", "list", ".", "to_native_tpl", "else", "nil", "end", "response", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_commit", "(", "@native_kafka", ",", "tpl", ",", "async", ")", "if", "response", "!=", "0", "raise", "Rdkafka", "::", "RdkafkaError", ".", "new", "(", "response", ")", "end", "end" ]
Commit the current offsets of this consumer @param list [TopicPartitionList,nil] The topic with partitions to commit @param async [Boolean] Whether to commit async or wait for the commit to finish @raise [RdkafkaError] When comitting fails @return [nil]
[ "Commit", "the", "current", "offsets", "of", "this", "consumer" ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L293-L306
train
appsignal/rdkafka-ruby
lib/rdkafka/consumer.rb
Rdkafka.Consumer.poll
def poll(timeout_ms) message_ptr = Rdkafka::Bindings.rd_kafka_consumer_poll(@native_kafka, timeout_ms) if message_ptr.null? nil else # Create struct wrapper native_message = Rdkafka::Bindings::Message.new(message_ptr) # Raise error if needed if native_message[:err] != 0 raise Rdkafka::RdkafkaError.new(native_message[:err]) end # Create a message to pass out Rdkafka::Consumer::Message.new(native_message) end ensure # Clean up rdkafka message if there is one if !message_ptr.nil? && !message_ptr.null? Rdkafka::Bindings.rd_kafka_message_destroy(message_ptr) end end
ruby
def poll(timeout_ms) message_ptr = Rdkafka::Bindings.rd_kafka_consumer_poll(@native_kafka, timeout_ms) if message_ptr.null? nil else # Create struct wrapper native_message = Rdkafka::Bindings::Message.new(message_ptr) # Raise error if needed if native_message[:err] != 0 raise Rdkafka::RdkafkaError.new(native_message[:err]) end # Create a message to pass out Rdkafka::Consumer::Message.new(native_message) end ensure # Clean up rdkafka message if there is one if !message_ptr.nil? && !message_ptr.null? Rdkafka::Bindings.rd_kafka_message_destroy(message_ptr) end end
[ "def", "poll", "(", "timeout_ms", ")", "message_ptr", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_consumer_poll", "(", "@native_kafka", ",", "timeout_ms", ")", "if", "message_ptr", ".", "null?", "nil", "else", "# Create struct wrapper", "native_message", "=", "Rdkafka", "::", "Bindings", "::", "Message", ".", "new", "(", "message_ptr", ")", "# Raise error if needed", "if", "native_message", "[", ":err", "]", "!=", "0", "raise", "Rdkafka", "::", "RdkafkaError", ".", "new", "(", "native_message", "[", ":err", "]", ")", "end", "# Create a message to pass out", "Rdkafka", "::", "Consumer", "::", "Message", ".", "new", "(", "native_message", ")", "end", "ensure", "# Clean up rdkafka message if there is one", "if", "!", "message_ptr", ".", "nil?", "&&", "!", "message_ptr", ".", "null?", "Rdkafka", "::", "Bindings", ".", "rd_kafka_message_destroy", "(", "message_ptr", ")", "end", "end" ]
Poll for the next message on one of the subscribed topics @param timeout_ms [Integer] Timeout of this poll @raise [RdkafkaError] When polling fails @return [Message, nil] A message or nil if there was no new message within the timeout
[ "Poll", "for", "the", "next", "message", "on", "one", "of", "the", "subscribed", "topics" ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/consumer.rb#L315-L334
train
appsignal/rdkafka-ruby
lib/rdkafka/config.rb
Rdkafka.Config.consumer
def consumer opaque = Opaque.new config = native_config(opaque) if @consumer_rebalance_listener opaque.consumer_rebalance_listener = @consumer_rebalance_listener Rdkafka::Bindings.rd_kafka_conf_set_rebalance_cb(config, Rdkafka::Bindings::RebalanceCallback) end kafka = native_kafka(config, :rd_kafka_consumer) # Redirect the main queue to the consumer Rdkafka::Bindings.rd_kafka_poll_set_consumer(kafka) # Return consumer with Kafka client Rdkafka::Consumer.new(kafka) end
ruby
def consumer opaque = Opaque.new config = native_config(opaque) if @consumer_rebalance_listener opaque.consumer_rebalance_listener = @consumer_rebalance_listener Rdkafka::Bindings.rd_kafka_conf_set_rebalance_cb(config, Rdkafka::Bindings::RebalanceCallback) end kafka = native_kafka(config, :rd_kafka_consumer) # Redirect the main queue to the consumer Rdkafka::Bindings.rd_kafka_poll_set_consumer(kafka) # Return consumer with Kafka client Rdkafka::Consumer.new(kafka) end
[ "def", "consumer", "opaque", "=", "Opaque", ".", "new", "config", "=", "native_config", "(", "opaque", ")", "if", "@consumer_rebalance_listener", "opaque", ".", "consumer_rebalance_listener", "=", "@consumer_rebalance_listener", "Rdkafka", "::", "Bindings", ".", "rd_kafka_conf_set_rebalance_cb", "(", "config", ",", "Rdkafka", "::", "Bindings", "::", "RebalanceCallback", ")", "end", "kafka", "=", "native_kafka", "(", "config", ",", ":rd_kafka_consumer", ")", "# Redirect the main queue to the consumer", "Rdkafka", "::", "Bindings", ".", "rd_kafka_poll_set_consumer", "(", "kafka", ")", "# Return consumer with Kafka client", "Rdkafka", "::", "Consumer", ".", "new", "(", "kafka", ")", "end" ]
Create a consumer with this configuration. @raise [ConfigError] When the configuration contains invalid options @raise [ClientCreationError] When the native client cannot be created @return [Consumer] The created consumer
[ "Create", "a", "consumer", "with", "this", "configuration", "." ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/config.rb#L110-L126
train
appsignal/rdkafka-ruby
lib/rdkafka/config.rb
Rdkafka.Config.producer
def producer # Create opaque opaque = Opaque.new # Create Kafka config config = native_config(opaque) # Set callback to receive delivery reports on config Rdkafka::Bindings.rd_kafka_conf_set_dr_msg_cb(config, Rdkafka::Bindings::DeliveryCallback) # Return producer with Kafka client Rdkafka::Producer.new(native_kafka(config, :rd_kafka_producer)).tap do |producer| opaque.producer = producer end end
ruby
def producer # Create opaque opaque = Opaque.new # Create Kafka config config = native_config(opaque) # Set callback to receive delivery reports on config Rdkafka::Bindings.rd_kafka_conf_set_dr_msg_cb(config, Rdkafka::Bindings::DeliveryCallback) # Return producer with Kafka client Rdkafka::Producer.new(native_kafka(config, :rd_kafka_producer)).tap do |producer| opaque.producer = producer end end
[ "def", "producer", "# Create opaque", "opaque", "=", "Opaque", ".", "new", "# Create Kafka config", "config", "=", "native_config", "(", "opaque", ")", "# Set callback to receive delivery reports on config", "Rdkafka", "::", "Bindings", ".", "rd_kafka_conf_set_dr_msg_cb", "(", "config", ",", "Rdkafka", "::", "Bindings", "::", "DeliveryCallback", ")", "# Return producer with Kafka client", "Rdkafka", "::", "Producer", ".", "new", "(", "native_kafka", "(", "config", ",", ":rd_kafka_producer", ")", ")", ".", "tap", "do", "|", "producer", "|", "opaque", ".", "producer", "=", "producer", "end", "end" ]
Create a producer with this configuration. @raise [ConfigError] When the configuration contains invalid options @raise [ClientCreationError] When the native client cannot be created @return [Producer] The created producer
[ "Create", "a", "producer", "with", "this", "configuration", "." ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/config.rb#L134-L145
train
appsignal/rdkafka-ruby
lib/rdkafka/config.rb
Rdkafka.Config.native_config
def native_config(opaque=nil) Rdkafka::Bindings.rd_kafka_conf_new.tap do |config| # Create config @config_hash.merge(REQUIRED_CONFIG).each do |key, value| error_buffer = FFI::MemoryPointer.from_string(" " * 256) result = Rdkafka::Bindings.rd_kafka_conf_set( config, key.to_s, value.to_s, error_buffer, 256 ) unless result == :config_ok raise ConfigError.new(error_buffer.read_string) end end # Set opaque pointer that's used as a proxy for callbacks if opaque pointer = ::FFI::Pointer.new(:pointer, opaque.object_id) Rdkafka::Bindings.rd_kafka_conf_set_opaque(config, pointer) # Store opaque with the pointer as key. We use this approach instead # of trying to convert the pointer to a Ruby object because there is # no risk of a segfault this way. Rdkafka::Config.opaques[pointer.to_i] = opaque end # Set log callback Rdkafka::Bindings.rd_kafka_conf_set_log_cb(config, Rdkafka::Bindings::LogCallback) # Set stats callback Rdkafka::Bindings.rd_kafka_conf_set_stats_cb(config, Rdkafka::Bindings::StatsCallback) end end
ruby
def native_config(opaque=nil) Rdkafka::Bindings.rd_kafka_conf_new.tap do |config| # Create config @config_hash.merge(REQUIRED_CONFIG).each do |key, value| error_buffer = FFI::MemoryPointer.from_string(" " * 256) result = Rdkafka::Bindings.rd_kafka_conf_set( config, key.to_s, value.to_s, error_buffer, 256 ) unless result == :config_ok raise ConfigError.new(error_buffer.read_string) end end # Set opaque pointer that's used as a proxy for callbacks if opaque pointer = ::FFI::Pointer.new(:pointer, opaque.object_id) Rdkafka::Bindings.rd_kafka_conf_set_opaque(config, pointer) # Store opaque with the pointer as key. We use this approach instead # of trying to convert the pointer to a Ruby object because there is # no risk of a segfault this way. Rdkafka::Config.opaques[pointer.to_i] = opaque end # Set log callback Rdkafka::Bindings.rd_kafka_conf_set_log_cb(config, Rdkafka::Bindings::LogCallback) # Set stats callback Rdkafka::Bindings.rd_kafka_conf_set_stats_cb(config, Rdkafka::Bindings::StatsCallback) end end
[ "def", "native_config", "(", "opaque", "=", "nil", ")", "Rdkafka", "::", "Bindings", ".", "rd_kafka_conf_new", ".", "tap", "do", "|", "config", "|", "# Create config", "@config_hash", ".", "merge", "(", "REQUIRED_CONFIG", ")", ".", "each", "do", "|", "key", ",", "value", "|", "error_buffer", "=", "FFI", "::", "MemoryPointer", ".", "from_string", "(", "\" \"", "*", "256", ")", "result", "=", "Rdkafka", "::", "Bindings", ".", "rd_kafka_conf_set", "(", "config", ",", "key", ".", "to_s", ",", "value", ".", "to_s", ",", "error_buffer", ",", "256", ")", "unless", "result", "==", ":config_ok", "raise", "ConfigError", ".", "new", "(", "error_buffer", ".", "read_string", ")", "end", "end", "# Set opaque pointer that's used as a proxy for callbacks", "if", "opaque", "pointer", "=", "::", "FFI", "::", "Pointer", ".", "new", "(", ":pointer", ",", "opaque", ".", "object_id", ")", "Rdkafka", "::", "Bindings", ".", "rd_kafka_conf_set_opaque", "(", "config", ",", "pointer", ")", "# Store opaque with the pointer as key. We use this approach instead", "# of trying to convert the pointer to a Ruby object because there is", "# no risk of a segfault this way.", "Rdkafka", "::", "Config", ".", "opaques", "[", "pointer", ".", "to_i", "]", "=", "opaque", "end", "# Set log callback", "Rdkafka", "::", "Bindings", ".", "rd_kafka_conf_set_log_cb", "(", "config", ",", "Rdkafka", "::", "Bindings", "::", "LogCallback", ")", "# Set stats callback", "Rdkafka", "::", "Bindings", ".", "rd_kafka_conf_set_stats_cb", "(", "config", ",", "Rdkafka", "::", "Bindings", "::", "StatsCallback", ")", "end", "end" ]
This method is only intented to be used to create a client, using it in another way will leak memory.
[ "This", "method", "is", "only", "intented", "to", "be", "used", "to", "create", "a", "client", "using", "it", "in", "another", "way", "will", "leak", "memory", "." ]
87b3e0ddae5ea576847cb67228fcea06ec2a24d6
https://github.com/appsignal/rdkafka-ruby/blob/87b3e0ddae5ea576847cb67228fcea06ec2a24d6/lib/rdkafka/config.rb#L160-L194
train
puppetlabs/pdk
lib/pdk/util.rb
PDK.Util.find_upwards
def find_upwards(target, start_dir = nil) previous = nil current = File.expand_path(start_dir || Dir.pwd) until !File.directory?(current) || current == previous filename = File.join(current, target) return filename if File.file?(filename) previous = current current = File.expand_path('..', current) end end
ruby
def find_upwards(target, start_dir = nil) previous = nil current = File.expand_path(start_dir || Dir.pwd) until !File.directory?(current) || current == previous filename = File.join(current, target) return filename if File.file?(filename) previous = current current = File.expand_path('..', current) end end
[ "def", "find_upwards", "(", "target", ",", "start_dir", "=", "nil", ")", "previous", "=", "nil", "current", "=", "File", ".", "expand_path", "(", "start_dir", "||", "Dir", ".", "pwd", ")", "until", "!", "File", ".", "directory?", "(", "current", ")", "||", "current", "==", "previous", "filename", "=", "File", ".", "join", "(", "current", ",", "target", ")", "return", "filename", "if", "File", ".", "file?", "(", "filename", ")", "previous", "=", "current", "current", "=", "File", ".", "expand_path", "(", "'..'", ",", "current", ")", "end", "end" ]
Searches upwards from current working directory for the given target file. @param target [String] Name of file to search for. @param start_dir [String] Directory to start searching from, defaults to Dir.pwd @return [String, nil] Fully qualified path to the given target file if found, nil if the target file could not be found.
[ "Searches", "upwards", "from", "current", "working", "directory", "for", "the", "given", "target", "file", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/util.rb#L28-L38
train
puppetlabs/pdk
lib/pdk/util.rb
PDK.Util.make_tmpdir_name
def make_tmpdir_name(base) t = Time.now.strftime('%Y%m%d') name = "#{base}#{t}-#{Process.pid}-#{rand(0x100000000).to_s(36)}" File.join(Dir.tmpdir, name) end
ruby
def make_tmpdir_name(base) t = Time.now.strftime('%Y%m%d') name = "#{base}#{t}-#{Process.pid}-#{rand(0x100000000).to_s(36)}" File.join(Dir.tmpdir, name) end
[ "def", "make_tmpdir_name", "(", "base", ")", "t", "=", "Time", ".", "now", ".", "strftime", "(", "'%Y%m%d'", ")", "name", "=", "\"#{base}#{t}-#{Process.pid}-#{rand(0x100000000).to_s(36)}\"", "File", ".", "join", "(", "Dir", ".", "tmpdir", ",", "name", ")", "end" ]
Generate a name for a temporary directory. @param base [String] A string to base the name generation off. @return [String] The temporary directory path.
[ "Generate", "a", "name", "for", "a", "temporary", "directory", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/util.rb#L46-L50
train
puppetlabs/pdk
lib/pdk/util.rb
PDK.Util.canonical_path
def canonical_path(path) if Gem.win_platform? unless File.exist?(path) raise PDK::CLI::FatalError, _("Cannot resolve a full path to '%{path}', as it does not currently exist.") % { path: path } end PDK::Util::Windows::File.get_long_pathname(path) else File.expand_path(path) end end
ruby
def canonical_path(path) if Gem.win_platform? unless File.exist?(path) raise PDK::CLI::FatalError, _("Cannot resolve a full path to '%{path}', as it does not currently exist.") % { path: path } end PDK::Util::Windows::File.get_long_pathname(path) else File.expand_path(path) end end
[ "def", "canonical_path", "(", "path", ")", "if", "Gem", ".", "win_platform?", "unless", "File", ".", "exist?", "(", "path", ")", "raise", "PDK", "::", "CLI", "::", "FatalError", ",", "_", "(", "\"Cannot resolve a full path to '%{path}', as it does not currently exist.\"", ")", "%", "{", "path", ":", "path", "}", "end", "PDK", "::", "Util", "::", "Windows", "::", "File", ".", "get_long_pathname", "(", "path", ")", "else", "File", ".", "expand_path", "(", "path", ")", "end", "end" ]
Return an expanded, absolute path @param path [String] Existing path that may not be canonical @return [String] Canonical path
[ "Return", "an", "expanded", "absolute", "path" ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/util.rb#L58-L67
train
puppetlabs/pdk
lib/pdk/util.rb
PDK.Util.cachedir
def cachedir if Gem.win_platform? File.join(ENV['LOCALAPPDATA'], 'PDK', 'cache') else File.join(Dir.home, '.pdk', 'cache') end end
ruby
def cachedir if Gem.win_platform? File.join(ENV['LOCALAPPDATA'], 'PDK', 'cache') else File.join(Dir.home, '.pdk', 'cache') end end
[ "def", "cachedir", "if", "Gem", ".", "win_platform?", "File", ".", "join", "(", "ENV", "[", "'LOCALAPPDATA'", "]", ",", "'PDK'", ",", "'cache'", ")", "else", "File", ".", "join", "(", "Dir", ".", "home", ",", "'.pdk'", ",", "'cache'", ")", "end", "end" ]
Returns the fully qualified path to a per-user PDK cachedir. @return [String] Fully qualified path to per-user PDK cachedir.
[ "Returns", "the", "fully", "qualified", "path", "to", "a", "per", "-", "user", "PDK", "cachedir", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/util.rb#L100-L106
train
puppetlabs/pdk
lib/pdk/util.rb
PDK.Util.module_root
def module_root metadata_path = find_upwards('metadata.json') if metadata_path File.dirname(metadata_path) elsif in_module_root? Dir.pwd else nil end end
ruby
def module_root metadata_path = find_upwards('metadata.json') if metadata_path File.dirname(metadata_path) elsif in_module_root? Dir.pwd else nil end end
[ "def", "module_root", "metadata_path", "=", "find_upwards", "(", "'metadata.json'", ")", "if", "metadata_path", "File", ".", "dirname", "(", "metadata_path", ")", "elsif", "in_module_root?", "Dir", ".", "pwd", "else", "nil", "end", "end" ]
Returns path to the root of the module being worked on. @return [String, nil] Fully qualified base path to module, or nil if the current working dir does not appear to be within a module.
[ "Returns", "path", "to", "the", "root", "of", "the", "module", "being", "worked", "on", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/util.rb#L113-L122
train
puppetlabs/pdk
lib/pdk/util.rb
PDK.Util.find_valid_json_in
def find_valid_json_in(text, opts = {}) break_on_first = opts.key?(:break_on_first) ? opts[:break_on_first] : true json_result = break_on_first ? nil : [] text.scan(%r{\{(?:[^{}]|(?:\g<0>))*\}}x) do |str| begin if break_on_first json_result = JSON.parse(str) break else json_result.push(JSON.parse(str)) end rescue JSON::ParserError next end end json_result end
ruby
def find_valid_json_in(text, opts = {}) break_on_first = opts.key?(:break_on_first) ? opts[:break_on_first] : true json_result = break_on_first ? nil : [] text.scan(%r{\{(?:[^{}]|(?:\g<0>))*\}}x) do |str| begin if break_on_first json_result = JSON.parse(str) break else json_result.push(JSON.parse(str)) end rescue JSON::ParserError next end end json_result end
[ "def", "find_valid_json_in", "(", "text", ",", "opts", "=", "{", "}", ")", "break_on_first", "=", "opts", ".", "key?", "(", ":break_on_first", ")", "?", "opts", "[", ":break_on_first", "]", ":", "true", "json_result", "=", "break_on_first", "?", "nil", ":", "[", "]", "text", ".", "scan", "(", "%r{", "\\{", "\\g", "\\}", "}x", ")", "do", "|", "str", "|", "begin", "if", "break_on_first", "json_result", "=", "JSON", ".", "parse", "(", "str", ")", "break", "else", "json_result", ".", "push", "(", "JSON", ".", "parse", "(", "str", ")", ")", "end", "rescue", "JSON", "::", "ParserError", "next", "end", "end", "json_result", "end" ]
Iterate through possible JSON documents until we find one that is valid. @param [String] text the text in which to find a JSON document @param [Hash] opts options @option opts [Boolean] :break_on_first Whether or not to break after valid JSON is found, defaults to true @return [Hash, Array<Hash>, nil] subset of text as Hash of first valid JSON found, array of all valid JSON found, or nil if no valid JSON found in the text @private
[ "Iterate", "through", "possible", "JSON", "documents", "until", "we", "find", "one", "that", "is", "valid", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/util.rb#L165-L184
train
puppetlabs/pdk
lib/pdk/util.rb
PDK.Util.targets_relative_to_pwd
def targets_relative_to_pwd(targets) targets.map do |t| if Pathname.new(t).absolute? Pathname.new(t).relative_path_from(Pathname.pwd) else t end end end
ruby
def targets_relative_to_pwd(targets) targets.map do |t| if Pathname.new(t).absolute? Pathname.new(t).relative_path_from(Pathname.pwd) else t end end end
[ "def", "targets_relative_to_pwd", "(", "targets", ")", "targets", ".", "map", "do", "|", "t", "|", "if", "Pathname", ".", "new", "(", "t", ")", ".", "absolute?", "Pathname", ".", "new", "(", "t", ")", ".", "relative_path_from", "(", "Pathname", ".", "pwd", ")", "else", "t", "end", "end", "end" ]
Returns the targets' paths relative to the working directory @return [Array<String>] The absolute or path to the target
[ "Returns", "the", "targets", "paths", "relative", "to", "the", "working", "directory" ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/util.rb#L190-L198
train
puppetlabs/pdk
lib/pdk/report.rb
PDK.Report.write_junit
def write_junit(target = self.class.default_target) # Open a File Object for IO if target is a string containing a filename or path target = File.open(target, 'w') if target.is_a? String document = REXML::Document.new document << REXML::XMLDecl.new testsuites = REXML::Element.new('testsuites') id = 0 events.each do |testsuite_name, testcases| testsuite = REXML::Element.new('testsuite') testsuite.attributes['name'] = testsuite_name testsuite.attributes['tests'] = testcases.length testsuite.attributes['errors'] = testcases.select(&:error?).length testsuite.attributes['failures'] = testcases.select(&:failure?).length testsuite.attributes['skipped'] = testcases.select(&:skipped?).length testsuite.attributes['time'] = 0 testsuite.attributes['timestamp'] = Time.now.strftime('%Y-%m-%dT%H:%M:%S') testsuite.attributes['hostname'] = Socket.gethostname testsuite.attributes['id'] = id testsuite.attributes['package'] = testsuite_name testsuite.add_element('properties') testcases.each { |r| testsuite.elements << r.to_junit } testsuite.add_element('system-out') testsuite.add_element('system-err') testsuites.elements << testsuite id += 1 end document.elements << testsuites document.write(target, 2) ensure target.close if target.is_a? File end
ruby
def write_junit(target = self.class.default_target) # Open a File Object for IO if target is a string containing a filename or path target = File.open(target, 'w') if target.is_a? String document = REXML::Document.new document << REXML::XMLDecl.new testsuites = REXML::Element.new('testsuites') id = 0 events.each do |testsuite_name, testcases| testsuite = REXML::Element.new('testsuite') testsuite.attributes['name'] = testsuite_name testsuite.attributes['tests'] = testcases.length testsuite.attributes['errors'] = testcases.select(&:error?).length testsuite.attributes['failures'] = testcases.select(&:failure?).length testsuite.attributes['skipped'] = testcases.select(&:skipped?).length testsuite.attributes['time'] = 0 testsuite.attributes['timestamp'] = Time.now.strftime('%Y-%m-%dT%H:%M:%S') testsuite.attributes['hostname'] = Socket.gethostname testsuite.attributes['id'] = id testsuite.attributes['package'] = testsuite_name testsuite.add_element('properties') testcases.each { |r| testsuite.elements << r.to_junit } testsuite.add_element('system-out') testsuite.add_element('system-err') testsuites.elements << testsuite id += 1 end document.elements << testsuites document.write(target, 2) ensure target.close if target.is_a? File end
[ "def", "write_junit", "(", "target", "=", "self", ".", "class", ".", "default_target", ")", "# Open a File Object for IO if target is a string containing a filename or path", "target", "=", "File", ".", "open", "(", "target", ",", "'w'", ")", "if", "target", ".", "is_a?", "String", "document", "=", "REXML", "::", "Document", ".", "new", "document", "<<", "REXML", "::", "XMLDecl", ".", "new", "testsuites", "=", "REXML", "::", "Element", ".", "new", "(", "'testsuites'", ")", "id", "=", "0", "events", ".", "each", "do", "|", "testsuite_name", ",", "testcases", "|", "testsuite", "=", "REXML", "::", "Element", ".", "new", "(", "'testsuite'", ")", "testsuite", ".", "attributes", "[", "'name'", "]", "=", "testsuite_name", "testsuite", ".", "attributes", "[", "'tests'", "]", "=", "testcases", ".", "length", "testsuite", ".", "attributes", "[", "'errors'", "]", "=", "testcases", ".", "select", "(", ":error?", ")", ".", "length", "testsuite", ".", "attributes", "[", "'failures'", "]", "=", "testcases", ".", "select", "(", ":failure?", ")", ".", "length", "testsuite", ".", "attributes", "[", "'skipped'", "]", "=", "testcases", ".", "select", "(", ":skipped?", ")", ".", "length", "testsuite", ".", "attributes", "[", "'time'", "]", "=", "0", "testsuite", ".", "attributes", "[", "'timestamp'", "]", "=", "Time", ".", "now", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S'", ")", "testsuite", ".", "attributes", "[", "'hostname'", "]", "=", "Socket", ".", "gethostname", "testsuite", ".", "attributes", "[", "'id'", "]", "=", "id", "testsuite", ".", "attributes", "[", "'package'", "]", "=", "testsuite_name", "testsuite", ".", "add_element", "(", "'properties'", ")", "testcases", ".", "each", "{", "|", "r", "|", "testsuite", ".", "elements", "<<", "r", ".", "to_junit", "}", "testsuite", ".", "add_element", "(", "'system-out'", ")", "testsuite", ".", "add_element", "(", "'system-err'", ")", "testsuites", ".", "elements", "<<", "testsuite", "id", "+=", "1", "end", "document", ".", "elements", "<<", "testsuites", "document", ".", "write", "(", "target", ",", "2", ")", "ensure", "target", ".", "close", "if", "target", ".", "is_a?", "File", "end" ]
Renders the report as a JUnit XML document. @param target [#write] an IO object that the report will be written to. Defaults to PDK::Report.default_target.
[ "Renders", "the", "report", "as", "a", "JUnit", "XML", "document", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/report.rb#L50-L84
train
puppetlabs/pdk
lib/pdk/report.rb
PDK.Report.write_text
def write_text(target = self.class.default_target) # Open a File Object for IO if target is a string containing a filename or path target = File.open(target, 'w') if target.is_a? String coverage_report = nil events.each do |_tool, tool_events| tool_events.each do |event| if event.rspec_puppet_coverage? coverage_report = event.to_text else target.puts(event.to_text) unless event.pass? end end end ensure target.puts "\n#{coverage_report}" if coverage_report target.close if target.is_a? File end
ruby
def write_text(target = self.class.default_target) # Open a File Object for IO if target is a string containing a filename or path target = File.open(target, 'w') if target.is_a? String coverage_report = nil events.each do |_tool, tool_events| tool_events.each do |event| if event.rspec_puppet_coverage? coverage_report = event.to_text else target.puts(event.to_text) unless event.pass? end end end ensure target.puts "\n#{coverage_report}" if coverage_report target.close if target.is_a? File end
[ "def", "write_text", "(", "target", "=", "self", ".", "class", ".", "default_target", ")", "# Open a File Object for IO if target is a string containing a filename or path", "target", "=", "File", ".", "open", "(", "target", ",", "'w'", ")", "if", "target", ".", "is_a?", "String", "coverage_report", "=", "nil", "events", ".", "each", "do", "|", "_tool", ",", "tool_events", "|", "tool_events", ".", "each", "do", "|", "event", "|", "if", "event", ".", "rspec_puppet_coverage?", "coverage_report", "=", "event", ".", "to_text", "else", "target", ".", "puts", "(", "event", ".", "to_text", ")", "unless", "event", ".", "pass?", "end", "end", "end", "ensure", "target", ".", "puts", "\"\\n#{coverage_report}\"", "if", "coverage_report", "target", ".", "close", "if", "target", ".", "is_a?", "File", "end" ]
Renders the report as plain text. This report is designed for interactive use by a human and so excludes all passing events in order to be consise. @param target [#write] an IO object that the report will be written to. Defaults to PDK::Report.default_target.
[ "Renders", "the", "report", "as", "plain", "text", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/report.rb#L93-L110
train
puppetlabs/pdk
lib/pdk/answer_file.rb
PDK.AnswerFile.update!
def update!(new_answers = {}) unless new_answers.is_a?(Hash) raise PDK::CLI::FatalError, _('Answer file can be updated only with a Hash') end answers.merge!(new_answers) save_to_disk end
ruby
def update!(new_answers = {}) unless new_answers.is_a?(Hash) raise PDK::CLI::FatalError, _('Answer file can be updated only with a Hash') end answers.merge!(new_answers) save_to_disk end
[ "def", "update!", "(", "new_answers", "=", "{", "}", ")", "unless", "new_answers", ".", "is_a?", "(", "Hash", ")", "raise", "PDK", "::", "CLI", "::", "FatalError", ",", "_", "(", "'Answer file can be updated only with a Hash'", ")", "end", "answers", ".", "merge!", "(", "new_answers", ")", "save_to_disk", "end" ]
Update the stored answers in memory and then save them to disk. @param new_answers [Hash{String => Object}] The new questions and answers to be merged into the existing answers. @raise [PDK::CLI::FatalError] if the new answers are not provided as a Hash. @raise (see #save_to_disk)
[ "Update", "the", "stored", "answers", "in", "memory", "and", "then", "save", "them", "to", "disk", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/answer_file.rb#L57-L65
train
puppetlabs/pdk
lib/pdk/answer_file.rb
PDK.AnswerFile.read_from_disk
def read_from_disk return {} if !File.file?(answer_file_path) || File.zero?(answer_file_path) unless File.readable?(answer_file_path) raise PDK::CLI::FatalError, _("Unable to open '%{file}' for reading") % { file: answer_file_path, } end answers = JSON.parse(File.read(answer_file_path)) if answers.is_a?(Hash) answers else PDK.logger.warn _("Answer file '%{path}' did not contain a valid set of answers, recreating it") % { path: answer_file_path, } {} end rescue JSON::JSONError PDK.logger.warn _("Answer file '%{path}' did not contain valid JSON, recreating it") % { path: answer_file_path, } {} end
ruby
def read_from_disk return {} if !File.file?(answer_file_path) || File.zero?(answer_file_path) unless File.readable?(answer_file_path) raise PDK::CLI::FatalError, _("Unable to open '%{file}' for reading") % { file: answer_file_path, } end answers = JSON.parse(File.read(answer_file_path)) if answers.is_a?(Hash) answers else PDK.logger.warn _("Answer file '%{path}' did not contain a valid set of answers, recreating it") % { path: answer_file_path, } {} end rescue JSON::JSONError PDK.logger.warn _("Answer file '%{path}' did not contain valid JSON, recreating it") % { path: answer_file_path, } {} end
[ "def", "read_from_disk", "return", "{", "}", "if", "!", "File", ".", "file?", "(", "answer_file_path", ")", "||", "File", ".", "zero?", "(", "answer_file_path", ")", "unless", "File", ".", "readable?", "(", "answer_file_path", ")", "raise", "PDK", "::", "CLI", "::", "FatalError", ",", "_", "(", "\"Unable to open '%{file}' for reading\"", ")", "%", "{", "file", ":", "answer_file_path", ",", "}", "end", "answers", "=", "JSON", ".", "parse", "(", "File", ".", "read", "(", "answer_file_path", ")", ")", "if", "answers", ".", "is_a?", "(", "Hash", ")", "answers", "else", "PDK", ".", "logger", ".", "warn", "_", "(", "\"Answer file '%{path}' did not contain a valid set of answers, recreating it\"", ")", "%", "{", "path", ":", "answer_file_path", ",", "}", "{", "}", "end", "rescue", "JSON", "::", "JSONError", "PDK", ".", "logger", ".", "warn", "_", "(", "\"Answer file '%{path}' did not contain valid JSON, recreating it\"", ")", "%", "{", "path", ":", "answer_file_path", ",", "}", "{", "}", "end" ]
Read existing answers into memory from the answer file on disk. @raise [PDK::CLI::FatalError] If the answer file exists but can not be read. @return [Hash{String => Object}] The existing questions and answers.
[ "Read", "existing", "answers", "into", "memory", "from", "the", "answer", "file", "on", "disk", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/answer_file.rb#L82-L105
train
puppetlabs/pdk
lib/pdk/answer_file.rb
PDK.AnswerFile.save_to_disk
def save_to_disk FileUtils.mkdir_p(File.dirname(answer_file_path)) write_file(answer_file_path, JSON.pretty_generate(answers)) rescue SystemCallError, IOError => e raise PDK::CLI::FatalError, _("Unable to write '%{file}': %{msg}") % { file: answer_file_path, msg: e.message, } end
ruby
def save_to_disk FileUtils.mkdir_p(File.dirname(answer_file_path)) write_file(answer_file_path, JSON.pretty_generate(answers)) rescue SystemCallError, IOError => e raise PDK::CLI::FatalError, _("Unable to write '%{file}': %{msg}") % { file: answer_file_path, msg: e.message, } end
[ "def", "save_to_disk", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "answer_file_path", ")", ")", "write_file", "(", "answer_file_path", ",", "JSON", ".", "pretty_generate", "(", "answers", ")", ")", "rescue", "SystemCallError", ",", "IOError", "=>", "e", "raise", "PDK", "::", "CLI", "::", "FatalError", ",", "_", "(", "\"Unable to write '%{file}': %{msg}\"", ")", "%", "{", "file", ":", "answer_file_path", ",", "msg", ":", "e", ".", "message", ",", "}", "end" ]
Save the in memory answer set to the answer file on disk. @raise [PDK::CLI::FatalError] if the answer file can not be written to.
[ "Save", "the", "in", "memory", "answer", "set", "to", "the", "answer", "file", "on", "disk", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/answer_file.rb#L110-L119
train
puppetlabs/pdk
lib/pdk/template_file.rb
PDK.TemplateFile.template_content
def template_content if File.file?(@template_file) && File.readable?(@template_file) return File.read(@template_file) end raise ArgumentError, _("'%{template}' is not a readable file") % { template: @template_file } end
ruby
def template_content if File.file?(@template_file) && File.readable?(@template_file) return File.read(@template_file) end raise ArgumentError, _("'%{template}' is not a readable file") % { template: @template_file } end
[ "def", "template_content", "if", "File", ".", "file?", "(", "@template_file", ")", "&&", "File", ".", "readable?", "(", "@template_file", ")", "return", "File", ".", "read", "(", "@template_file", ")", "end", "raise", "ArgumentError", ",", "_", "(", "\"'%{template}' is not a readable file\"", ")", "%", "{", "template", ":", "@template_file", "}", "end" ]
Reads the content of the template file into memory. @return [String] The content of the template file. @raise [ArgumentError] If the template file does not exist or can not be read. @api private
[ "Reads", "the", "content", "of", "the", "template", "file", "into", "memory", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/template_file.rb#L63-L69
train
puppetlabs/pdk
lib/pdk/template_file.rb
PDK.TemplateFile.render_erb
def render_erb renderer = ERB.new(template_content, nil, '-') renderer.filename = @template_file renderer.result(binding) end
ruby
def render_erb renderer = ERB.new(template_content, nil, '-') renderer.filename = @template_file renderer.result(binding) end
[ "def", "render_erb", "renderer", "=", "ERB", ".", "new", "(", "template_content", ",", "nil", ",", "'-'", ")", "renderer", ".", "filename", "=", "@template_file", "renderer", ".", "result", "(", "binding", ")", "end" ]
Renders the content of the template file as an ERB template. @return [String] The rendered template. @raise (see #template_content) @api private
[ "Renders", "the", "content", "of", "the", "template", "file", "as", "an", "ERB", "template", "." ]
0d864aff62ffef04b5104addf399d0476afd71e7
https://github.com/puppetlabs/pdk/blob/0d864aff62ffef04b5104addf399d0476afd71e7/lib/pdk/template_file.rb#L78-L82
train
flavorjones/loofah
lib/loofah/scrubber.rb
Loofah.Scrubber.append_attribute
def append_attribute(node, attribute, value) current_value = node.get_attribute(attribute) || '' current_values = current_value.split(/\s+/) updated_value = current_values | [value] node.set_attribute(attribute, updated_value.join(' ')) end
ruby
def append_attribute(node, attribute, value) current_value = node.get_attribute(attribute) || '' current_values = current_value.split(/\s+/) updated_value = current_values | [value] node.set_attribute(attribute, updated_value.join(' ')) end
[ "def", "append_attribute", "(", "node", ",", "attribute", ",", "value", ")", "current_value", "=", "node", ".", "get_attribute", "(", "attribute", ")", "||", "''", "current_values", "=", "current_value", ".", "split", "(", "/", "\\s", "/", ")", "updated_value", "=", "current_values", "|", "[", "value", "]", "node", ".", "set_attribute", "(", "attribute", ",", "updated_value", ".", "join", "(", "' '", ")", ")", "end" ]
If the attribute is not set, add it If the attribute is set, don't overwrite the existing value
[ "If", "the", "attribute", "is", "not", "set", "add", "it", "If", "the", "attribute", "is", "set", "don", "t", "overwrite", "the", "existing", "value" ]
49f178941f10a97aa6441e71fae704a81cc3a731
https://github.com/flavorjones/loofah/blob/49f178941f10a97aa6441e71fae704a81cc3a731/lib/loofah/scrubber.rb#L93-L98
train
flavorjones/loofah
lib/loofah/instance_methods.rb
Loofah.TextBehavior.text
def text(options={}) result = serialize_root.children.inner_text rescue "" if options[:encode_special_chars] == false result # possibly dangerous if rendered in a browser else encode_special_chars result end end
ruby
def text(options={}) result = serialize_root.children.inner_text rescue "" if options[:encode_special_chars] == false result # possibly dangerous if rendered in a browser else encode_special_chars result end end
[ "def", "text", "(", "options", "=", "{", "}", ")", "result", "=", "serialize_root", ".", "children", ".", "inner_text", "rescue", "\"\"", "if", "options", "[", ":encode_special_chars", "]", "==", "false", "result", "# possibly dangerous if rendered in a browser", "else", "encode_special_chars", "result", "end", "end" ]
Returns a plain-text version of the markup contained by the document, with HTML entities encoded. This method is significantly faster than #to_text, but isn't clever about whitespace around block elements. Loofah.document("<h1>Title</h1><div>Content</div>").text # => "TitleContent" By default, the returned text will have HTML entities escaped. If you want unescaped entities, and you understand that the result is unsafe to render in a browser, then you can pass an argument as shown: frag = Loofah.fragment("&lt;script&gt;alert('EVIL');&lt;/script&gt;") # ok for browser: frag.text # => "&lt;script&gt;alert('EVIL');&lt;/script&gt;" # decidedly not ok for browser: frag.text(:encode_special_chars => false) # => "<script>alert('EVIL');</script>"
[ "Returns", "a", "plain", "-", "text", "version", "of", "the", "markup", "contained", "by", "the", "document", "with", "HTML", "entities", "encoded", "." ]
49f178941f10a97aa6441e71fae704a81cc3a731
https://github.com/flavorjones/loofah/blob/49f178941f10a97aa6441e71fae704a81cc3a731/lib/loofah/instance_methods.rb#L94-L101
train
commander-rb/commander
lib/commander/command.rb
Commander.Command.option
def option(*args, &block) switches, description = Runner.separate_switches_from_description(*args) proc = block || option_proc(switches) @options << { args: args, proc: proc, switches: switches, description: description, } end
ruby
def option(*args, &block) switches, description = Runner.separate_switches_from_description(*args) proc = block || option_proc(switches) @options << { args: args, proc: proc, switches: switches, description: description, } end
[ "def", "option", "(", "*", "args", ",", "&", "block", ")", "switches", ",", "description", "=", "Runner", ".", "separate_switches_from_description", "(", "args", ")", "proc", "=", "block", "||", "option_proc", "(", "switches", ")", "@options", "<<", "{", "args", ":", "args", ",", "proc", ":", "proc", ",", "switches", ":", "switches", ",", "description", ":", "description", ",", "}", "end" ]
Add an option. Options are parsed via OptionParser so view it for additional usage documentation. A block may optionally be passed to handle the option, otherwise the _options_ struct seen below contains the results of this option. This handles common formats such as: -h, --help options.help # => bool --[no-]feature options.feature # => bool --large-switch options.large_switch # => bool --file FILE options.file # => file passed --list WORDS options.list # => array --date [DATE] options.date # => date or nil when optional argument not set === Examples command :something do |c| c.option '--recursive', 'Do something recursively' c.option '--file FILE', 'Specify a file' c.option('--info', 'Display info') { puts "handle with block" } c.option '--[no-]feature', 'With or without feature' c.option '--list FILES', Array, 'List the files specified' c.when_called do |args, options| do_something_recursively if options.recursive do_something_with_file options.file if options.file end end === Help Formatters This method also parses the arguments passed in order to determine which were switches, and which were descriptions for the option which can later be used within help formatters using option[:switches] and option[:description]. === Input Parsing Since Commander utilizes OptionParser you can pre-parse and evaluate option arguments. Simply require 'optparse/time', or 'optparse/date', as these objects must respond to #parse. c.option '--time TIME', Time c.option '--date [DATE]', Date
[ "Add", "an", "option", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/command.rb#L107-L116
train
commander-rb/commander
lib/commander/command.rb
Commander.Command.call
def call(args = []) object, meth = @when_called[0, 2] meth ||= :call options = proxy_option_struct case object when Proc then object.call(args, options) when Class then meth != :call ? object.new.send(meth, args, options) : object.new(args, options) else object.send(meth, args, options) if object end end
ruby
def call(args = []) object, meth = @when_called[0, 2] meth ||= :call options = proxy_option_struct case object when Proc then object.call(args, options) when Class then meth != :call ? object.new.send(meth, args, options) : object.new(args, options) else object.send(meth, args, options) if object end end
[ "def", "call", "(", "args", "=", "[", "]", ")", "object", ",", "meth", "=", "@when_called", "[", "0", ",", "2", "]", "meth", "||=", ":call", "options", "=", "proxy_option_struct", "case", "object", "when", "Proc", "then", "object", ".", "call", "(", "args", ",", "options", ")", "when", "Class", "then", "meth", "!=", ":call", "?", "object", ".", "new", ".", "send", "(", "meth", ",", "args", ",", "options", ")", ":", "object", ".", "new", "(", "args", ",", "options", ")", "else", "object", ".", "send", "(", "meth", ",", "args", ",", "options", ")", "if", "object", "end", "end" ]
Call the commands when_called block with _args_.
[ "Call", "the", "commands", "when_called", "block", "with", "_args_", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/command.rb#L176-L186
train
commander-rb/commander
lib/commander/runner.rb
Commander.Runner.run!
def run! trace = @always_trace || false require_program :version, :description trap('INT') { abort program(:int_message) } if program(:int_message) trap('INT') { program(:int_block).call } if program(:int_block) global_option('-h', '--help', 'Display help documentation') do args = @args - %w(-h --help) command(:help).run(*args) return end global_option('-v', '--version', 'Display version information') do say version return end global_option('-t', '--trace', 'Display backtrace when an error occurs') { trace = true } unless @never_trace || @always_trace parse_global_options remove_global_options options, @args if trace run_active_command else begin run_active_command rescue InvalidCommandError => e abort "#{e}. Use --help for more information" rescue \ OptionParser::InvalidOption, OptionParser::InvalidArgument, OptionParser::MissingArgument => e abort e.to_s rescue => e if @never_trace abort "error: #{e}." else abort "error: #{e}. Use --trace to view backtrace" end end end end
ruby
def run! trace = @always_trace || false require_program :version, :description trap('INT') { abort program(:int_message) } if program(:int_message) trap('INT') { program(:int_block).call } if program(:int_block) global_option('-h', '--help', 'Display help documentation') do args = @args - %w(-h --help) command(:help).run(*args) return end global_option('-v', '--version', 'Display version information') do say version return end global_option('-t', '--trace', 'Display backtrace when an error occurs') { trace = true } unless @never_trace || @always_trace parse_global_options remove_global_options options, @args if trace run_active_command else begin run_active_command rescue InvalidCommandError => e abort "#{e}. Use --help for more information" rescue \ OptionParser::InvalidOption, OptionParser::InvalidArgument, OptionParser::MissingArgument => e abort e.to_s rescue => e if @never_trace abort "error: #{e}." else abort "error: #{e}. Use --trace to view backtrace" end end end end
[ "def", "run!", "trace", "=", "@always_trace", "||", "false", "require_program", ":version", ",", ":description", "trap", "(", "'INT'", ")", "{", "abort", "program", "(", ":int_message", ")", "}", "if", "program", "(", ":int_message", ")", "trap", "(", "'INT'", ")", "{", "program", "(", ":int_block", ")", ".", "call", "}", "if", "program", "(", ":int_block", ")", "global_option", "(", "'-h'", ",", "'--help'", ",", "'Display help documentation'", ")", "do", "args", "=", "@args", "-", "%w(", "-h", "--help", ")", "command", "(", ":help", ")", ".", "run", "(", "args", ")", "return", "end", "global_option", "(", "'-v'", ",", "'--version'", ",", "'Display version information'", ")", "do", "say", "version", "return", "end", "global_option", "(", "'-t'", ",", "'--trace'", ",", "'Display backtrace when an error occurs'", ")", "{", "trace", "=", "true", "}", "unless", "@never_trace", "||", "@always_trace", "parse_global_options", "remove_global_options", "options", ",", "@args", "if", "trace", "run_active_command", "else", "begin", "run_active_command", "rescue", "InvalidCommandError", "=>", "e", "abort", "\"#{e}. Use --help for more information\"", "rescue", "OptionParser", "::", "InvalidOption", ",", "OptionParser", "::", "InvalidArgument", ",", "OptionParser", "::", "MissingArgument", "=>", "e", "abort", "e", ".", "to_s", "rescue", "=>", "e", "if", "@never_trace", "abort", "\"error: #{e}.\"", "else", "abort", "\"error: #{e}. Use --trace to view backtrace\"", "end", "end", "end", "end" ]
Run command parsing and execution process.
[ "Run", "command", "parsing", "and", "execution", "process", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/runner.rb#L50-L87
train
commander-rb/commander
lib/commander/runner.rb
Commander.Runner.program
def program(key, *args, &block) if key == :help && !args.empty? @program[:help] ||= {} @program[:help][args.first] = args.at(1) elsif key == :help_formatter && !args.empty? @program[key] = (@help_formatter_aliases[args.first] || args.first) elsif block @program[key] = block else unless args.empty? @program[key] = args.count == 1 ? args[0] : args end @program[key] end end
ruby
def program(key, *args, &block) if key == :help && !args.empty? @program[:help] ||= {} @program[:help][args.first] = args.at(1) elsif key == :help_formatter && !args.empty? @program[key] = (@help_formatter_aliases[args.first] || args.first) elsif block @program[key] = block else unless args.empty? @program[key] = args.count == 1 ? args[0] : args end @program[key] end end
[ "def", "program", "(", "key", ",", "*", "args", ",", "&", "block", ")", "if", "key", "==", ":help", "&&", "!", "args", ".", "empty?", "@program", "[", ":help", "]", "||=", "{", "}", "@program", "[", ":help", "]", "[", "args", ".", "first", "]", "=", "args", ".", "at", "(", "1", ")", "elsif", "key", "==", ":help_formatter", "&&", "!", "args", ".", "empty?", "@program", "[", "key", "]", "=", "(", "@help_formatter_aliases", "[", "args", ".", "first", "]", "||", "args", ".", "first", ")", "elsif", "block", "@program", "[", "key", "]", "=", "block", "else", "unless", "args", ".", "empty?", "@program", "[", "key", "]", "=", "args", ".", "count", "==", "1", "?", "args", "[", "0", "]", ":", "args", "end", "@program", "[", "key", "]", "end", "end" ]
Assign program information. === Examples # Set data program :name, 'Commander' program :version, Commander::VERSION program :description, 'Commander utility program.' program :help, 'Copyright', '2008 TJ Holowaychuk' program :help, 'Anything', 'You want' program :int_message 'Bye bye!' program :help_formatter, :compact program :help_formatter, Commander::HelpFormatter::TerminalCompact # Get data program :name # => 'Commander' === Keys :version (required) Program version triple, ex: '0.0.1' :description (required) Program description :name Program name, defaults to basename of executable :help_formatter Defaults to Commander::HelpFormatter::Terminal :help Allows addition of arbitrary global help blocks :help_paging Flag for toggling help paging :int_message Message to display when interrupted (CTRL + C)
[ "Assign", "program", "information", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/runner.rb#L141-L155
train
commander-rb/commander
lib/commander/runner.rb
Commander.Runner.alias_command
def alias_command(alias_name, name, *args) @commands[alias_name.to_s] = command name @aliases[alias_name.to_s] = args end
ruby
def alias_command(alias_name, name, *args) @commands[alias_name.to_s] = command name @aliases[alias_name.to_s] = args end
[ "def", "alias_command", "(", "alias_name", ",", "name", ",", "*", "args", ")", "@commands", "[", "alias_name", ".", "to_s", "]", "=", "command", "name", "@aliases", "[", "alias_name", ".", "to_s", "]", "=", "args", "end" ]
Alias command _name_ with _alias_name_. Optionally _args_ may be passed as if they were being passed straight to the original command via the command-line.
[ "Alias", "command", "_name_", "with", "_alias_name_", ".", "Optionally", "_args_", "may", "be", "passed", "as", "if", "they", "were", "being", "passed", "straight", "to", "the", "original", "command", "via", "the", "command", "-", "line", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/runner.rb#L194-L197
train
commander-rb/commander
lib/commander/runner.rb
Commander.Runner.args_without_command_name
def args_without_command_name removed = [] parts = command_name_from_args.split rescue [] @args.dup.delete_if do |arg| removed << arg if parts.include?(arg) && !removed.include?(arg) end end
ruby
def args_without_command_name removed = [] parts = command_name_from_args.split rescue [] @args.dup.delete_if do |arg| removed << arg if parts.include?(arg) && !removed.include?(arg) end end
[ "def", "args_without_command_name", "removed", "=", "[", "]", "parts", "=", "command_name_from_args", ".", "split", "rescue", "[", "]", "@args", ".", "dup", ".", "delete_if", "do", "|", "arg", "|", "removed", "<<", "arg", "if", "parts", ".", "include?", "(", "arg", ")", "&&", "!", "removed", ".", "include?", "(", "arg", ")", "end", "end" ]
Return arguments without the command name.
[ "Return", "arguments", "without", "the", "command", "name", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/runner.rb#L263-L269
train
commander-rb/commander
lib/commander/runner.rb
Commander.Runner.remove_global_options
def remove_global_options(options, args) # TODO: refactor with flipflop, please TJ ! have time to refactor me ! options.each do |option| switches = option[:switches].dup next if switches.empty? if (switch_has_arg = switches.any? { |s| s =~ /[ =]/ }) switches.map! { |s| s[0, s.index('=') || s.index(' ') || s.length] } end switches = expand_optionally_negative_switches(switches) past_switch, arg_removed = false, false args.delete_if do |arg| if switches.any? { |s| s[0, arg.length] == arg } arg_removed = !switch_has_arg past_switch = true elsif past_switch && !arg_removed && arg !~ /^-/ arg_removed = true else arg_removed = true false end end end end
ruby
def remove_global_options(options, args) # TODO: refactor with flipflop, please TJ ! have time to refactor me ! options.each do |option| switches = option[:switches].dup next if switches.empty? if (switch_has_arg = switches.any? { |s| s =~ /[ =]/ }) switches.map! { |s| s[0, s.index('=') || s.index(' ') || s.length] } end switches = expand_optionally_negative_switches(switches) past_switch, arg_removed = false, false args.delete_if do |arg| if switches.any? { |s| s[0, arg.length] == arg } arg_removed = !switch_has_arg past_switch = true elsif past_switch && !arg_removed && arg !~ /^-/ arg_removed = true else arg_removed = true false end end end end
[ "def", "remove_global_options", "(", "options", ",", "args", ")", "# TODO: refactor with flipflop, please TJ ! have time to refactor me !", "options", ".", "each", "do", "|", "option", "|", "switches", "=", "option", "[", ":switches", "]", ".", "dup", "next", "if", "switches", ".", "empty?", "if", "(", "switch_has_arg", "=", "switches", ".", "any?", "{", "|", "s", "|", "s", "=~", "/", "/", "}", ")", "switches", ".", "map!", "{", "|", "s", "|", "s", "[", "0", ",", "s", ".", "index", "(", "'='", ")", "||", "s", ".", "index", "(", "' '", ")", "||", "s", ".", "length", "]", "}", "end", "switches", "=", "expand_optionally_negative_switches", "(", "switches", ")", "past_switch", ",", "arg_removed", "=", "false", ",", "false", "args", ".", "delete_if", "do", "|", "arg", "|", "if", "switches", ".", "any?", "{", "|", "s", "|", "s", "[", "0", ",", "arg", ".", "length", "]", "==", "arg", "}", "arg_removed", "=", "!", "switch_has_arg", "past_switch", "=", "true", "elsif", "past_switch", "&&", "!", "arg_removed", "&&", "arg", "!~", "/", "/", "arg_removed", "=", "true", "else", "arg_removed", "=", "true", "false", "end", "end", "end", "end" ]
Removes global _options_ from _args_. This prevents an invalid option error from occurring when options are parsed again for the command.
[ "Removes", "global", "_options_", "from", "_args_", ".", "This", "prevents", "an", "invalid", "option", "error", "from", "occurring", "when", "options", "are", "parsed", "again", "for", "the", "command", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/runner.rb#L330-L355
train
commander-rb/commander
lib/commander/runner.rb
Commander.Runner.parse_global_options
def parse_global_options parser = options.inject(OptionParser.new) do |options, option| options.on(*option[:args], &global_option_proc(option[:switches], &option[:proc])) end options = @args.dup begin parser.parse!(options) rescue OptionParser::InvalidOption => e # Remove the offending args and retry. options = options.reject { |o| e.args.include?(o) } retry end end
ruby
def parse_global_options parser = options.inject(OptionParser.new) do |options, option| options.on(*option[:args], &global_option_proc(option[:switches], &option[:proc])) end options = @args.dup begin parser.parse!(options) rescue OptionParser::InvalidOption => e # Remove the offending args and retry. options = options.reject { |o| e.args.include?(o) } retry end end
[ "def", "parse_global_options", "parser", "=", "options", ".", "inject", "(", "OptionParser", ".", "new", ")", "do", "|", "options", ",", "option", "|", "options", ".", "on", "(", "option", "[", ":args", "]", ",", "global_option_proc", "(", "option", "[", ":switches", "]", ",", "option", "[", ":proc", "]", ")", ")", "end", "options", "=", "@args", ".", "dup", "begin", "parser", ".", "parse!", "(", "options", ")", "rescue", "OptionParser", "::", "InvalidOption", "=>", "e", "# Remove the offending args and retry.", "options", "=", "options", ".", "reject", "{", "|", "o", "|", "e", ".", "args", ".", "include?", "(", "o", ")", "}", "retry", "end", "end" ]
Parse global command options.
[ "Parse", "global", "command", "options", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/runner.rb#L374-L387
train
commander-rb/commander
lib/commander/runner.rb
Commander.Runner.require_program
def require_program(*keys) keys.each do |key| fail CommandError, "program #{key} required" if program(key).nil? || program(key).empty? end end
ruby
def require_program(*keys) keys.each do |key| fail CommandError, "program #{key} required" if program(key).nil? || program(key).empty? end end
[ "def", "require_program", "(", "*", "keys", ")", "keys", ".", "each", "do", "|", "key", "|", "fail", "CommandError", ",", "\"program #{key} required\"", "if", "program", "(", "key", ")", ".", "nil?", "||", "program", "(", "key", ")", ".", "empty?", "end", "end" ]
Raises a CommandError when the program any of the _keys_ are not present, or empty.
[ "Raises", "a", "CommandError", "when", "the", "program", "any", "of", "the", "_keys_", "are", "not", "present", "or", "empty", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/runner.rb#L407-L411
train
commander-rb/commander
lib/commander/runner.rb
Commander.Runner.run_active_command
def run_active_command require_valid_command if alias? command_name_from_args active_command.run(*(@aliases[command_name_from_args.to_s] + args_without_command_name)) else active_command.run(*args_without_command_name) end end
ruby
def run_active_command require_valid_command if alias? command_name_from_args active_command.run(*(@aliases[command_name_from_args.to_s] + args_without_command_name)) else active_command.run(*args_without_command_name) end end
[ "def", "run_active_command", "require_valid_command", "if", "alias?", "command_name_from_args", "active_command", ".", "run", "(", "(", "@aliases", "[", "command_name_from_args", ".", "to_s", "]", "+", "args_without_command_name", ")", ")", "else", "active_command", ".", "run", "(", "args_without_command_name", ")", "end", "end" ]
Run the active command.
[ "Run", "the", "active", "command", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/runner.rb#L441-L448
train
commander-rb/commander
lib/commander/user_interaction.rb
Commander.UI.ask_editor
def ask_editor(input = nil, preferred_editor = nil) editor = available_editor preferred_editor program = Commander::Runner.instance.program(:name).downcase rescue 'commander' tmpfile = Tempfile.new program begin tmpfile.write input if input tmpfile.close system("#{editor} #{tmpfile.path.shellescape}") ? IO.read(tmpfile.path) : nil ensure tmpfile.unlink end end
ruby
def ask_editor(input = nil, preferred_editor = nil) editor = available_editor preferred_editor program = Commander::Runner.instance.program(:name).downcase rescue 'commander' tmpfile = Tempfile.new program begin tmpfile.write input if input tmpfile.close system("#{editor} #{tmpfile.path.shellescape}") ? IO.read(tmpfile.path) : nil ensure tmpfile.unlink end end
[ "def", "ask_editor", "(", "input", "=", "nil", ",", "preferred_editor", "=", "nil", ")", "editor", "=", "available_editor", "preferred_editor", "program", "=", "Commander", "::", "Runner", ".", "instance", ".", "program", "(", ":name", ")", ".", "downcase", "rescue", "'commander'", "tmpfile", "=", "Tempfile", ".", "new", "program", "begin", "tmpfile", ".", "write", "input", "if", "input", "tmpfile", ".", "close", "system", "(", "\"#{editor} #{tmpfile.path.shellescape}\"", ")", "?", "IO", ".", "read", "(", "tmpfile", ".", "path", ")", ":", "nil", "ensure", "tmpfile", ".", "unlink", "end", "end" ]
Prompt an editor for input. Optionally supply initial _input_ which is written to the editor. _preferred_editor_ can be hinted. === Examples ask_editor # => prompts EDITOR with no input ask_editor('foo') # => prompts EDITOR with default text of 'foo' ask_editor('foo', 'mate -w') # => prompts TextMate with default text of 'foo'
[ "Prompt", "an", "editor", "for", "input", ".", "Optionally", "supply", "initial", "_input_", "which", "is", "written", "to", "the", "editor", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/user_interaction.rb#L258-L269
train
commander-rb/commander
lib/commander/user_interaction.rb
Commander.UI.enable_paging
def enable_paging return unless $stdout.tty? return unless Process.respond_to? :fork read, write = IO.pipe # Kernel.fork is not supported on all platforms and configurations. # As of Ruby 1.9, `Process.respond_to? :fork` should return false on # configurations that don't support it, but versions before 1.9 don't # seem to do this reliably and instead raise a NotImplementedError # (which is rescued below). if Kernel.fork $stdin.reopen read write.close read.close Kernel.select [$stdin] ENV['LESS'] = 'FSRX' unless ENV.key? 'LESS' pager = ENV['PAGER'] || 'less' exec pager rescue exec '/bin/sh', '-c', pager else # subprocess $stdout.reopen write $stderr.reopen write if $stderr.tty? write.close read.close end rescue NotImplementedError ensure write.close if write && !write.closed? read.close if read && !read.closed? end
ruby
def enable_paging return unless $stdout.tty? return unless Process.respond_to? :fork read, write = IO.pipe # Kernel.fork is not supported on all platforms and configurations. # As of Ruby 1.9, `Process.respond_to? :fork` should return false on # configurations that don't support it, but versions before 1.9 don't # seem to do this reliably and instead raise a NotImplementedError # (which is rescued below). if Kernel.fork $stdin.reopen read write.close read.close Kernel.select [$stdin] ENV['LESS'] = 'FSRX' unless ENV.key? 'LESS' pager = ENV['PAGER'] || 'less' exec pager rescue exec '/bin/sh', '-c', pager else # subprocess $stdout.reopen write $stderr.reopen write if $stderr.tty? write.close read.close end rescue NotImplementedError ensure write.close if write && !write.closed? read.close if read && !read.closed? end
[ "def", "enable_paging", "return", "unless", "$stdout", ".", "tty?", "return", "unless", "Process", ".", "respond_to?", ":fork", "read", ",", "write", "=", "IO", ".", "pipe", "# Kernel.fork is not supported on all platforms and configurations.", "# As of Ruby 1.9, `Process.respond_to? :fork` should return false on", "# configurations that don't support it, but versions before 1.9 don't", "# seem to do this reliably and instead raise a NotImplementedError", "# (which is rescued below).", "if", "Kernel", ".", "fork", "$stdin", ".", "reopen", "read", "write", ".", "close", "read", ".", "close", "Kernel", ".", "select", "[", "$stdin", "]", "ENV", "[", "'LESS'", "]", "=", "'FSRX'", "unless", "ENV", ".", "key?", "'LESS'", "pager", "=", "ENV", "[", "'PAGER'", "]", "||", "'less'", "exec", "pager", "rescue", "exec", "'/bin/sh'", ",", "'-c'", ",", "pager", "else", "# subprocess", "$stdout", ".", "reopen", "write", "$stderr", ".", "reopen", "write", "if", "$stderr", ".", "tty?", "write", ".", "close", "read", ".", "close", "end", "rescue", "NotImplementedError", "ensure", "write", ".", "close", "if", "write", "&&", "!", "write", ".", "closed?", "read", ".", "close", "if", "read", "&&", "!", "read", ".", "closed?", "end" ]
Enable paging of output after called.
[ "Enable", "paging", "of", "output", "after", "called", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/user_interaction.rb#L274-L304
train
commander-rb/commander
lib/commander/user_interaction.rb
Commander.UI.progress
def progress(arr, options = {}) bar = ProgressBar.new arr.length, options bar.show arr.each { |v| bar.increment yield(v) } end
ruby
def progress(arr, options = {}) bar = ProgressBar.new arr.length, options bar.show arr.each { |v| bar.increment yield(v) } end
[ "def", "progress", "(", "arr", ",", "options", "=", "{", "}", ")", "bar", "=", "ProgressBar", ".", "new", "arr", ".", "length", ",", "options", "bar", ".", "show", "arr", ".", "each", "{", "|", "v", "|", "bar", ".", "increment", "yield", "(", "v", ")", "}", "end" ]
Output progress while iterating _arr_. === Examples uris = %w( http://vision-media.ca http://google.com ) progress uris, :format => "Remaining: :time_remaining" do |uri| res = open uri end
[ "Output", "progress", "while", "iterating", "_arr_", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/user_interaction.rb#L317-L321
train
commander-rb/commander
lib/commander/user_interaction.rb
Commander.UI.replace_tokens
def replace_tokens(str, hash) #:nodoc: hash.inject(str) do |string, (key, value)| string.gsub ":#{key}", value.to_s end end
ruby
def replace_tokens(str, hash) #:nodoc: hash.inject(str) do |string, (key, value)| string.gsub ":#{key}", value.to_s end end
[ "def", "replace_tokens", "(", "str", ",", "hash", ")", "#:nodoc:", "hash", ".", "inject", "(", "str", ")", "do", "|", "string", ",", "(", "key", ",", "value", ")", "|", "string", ".", "gsub", "\":#{key}\"", ",", "value", ".", "to_s", "end", "end" ]
Substitute _hash_'s keys with their associated values in _str_.
[ "Substitute", "_hash_", "s", "keys", "with", "their", "associated", "values", "in", "_str_", "." ]
332047c14948225462fe60042eed23adfb996d68
https://github.com/commander-rb/commander/blob/332047c14948225462fe60042eed23adfb996d68/lib/commander/user_interaction.rb#L371-L375
train
tongueroo/ufo
lib/ufo/tasks/register.rb
Ufo.Tasks::Register.rubyize_format
def rubyize_format(original_data) data = original_data.to_snake_keys.deep_symbolize_keys definitions = data[:container_definitions] definitions.each_with_index do |definition, i| next unless definition[:log_configuration] options = definition[:log_configuration][:options] next unless options # LogConfiguration options do not get transformed and keep their original # structure: # https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/ECS/Types/ContainerDefinition.html original_definition = original_data["containerDefinitions"][i] definition[:log_configuration][:options] = original_definition["logConfiguration"]["options"] end data end
ruby
def rubyize_format(original_data) data = original_data.to_snake_keys.deep_symbolize_keys definitions = data[:container_definitions] definitions.each_with_index do |definition, i| next unless definition[:log_configuration] options = definition[:log_configuration][:options] next unless options # LogConfiguration options do not get transformed and keep their original # structure: # https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/ECS/Types/ContainerDefinition.html original_definition = original_data["containerDefinitions"][i] definition[:log_configuration][:options] = original_definition["logConfiguration"]["options"] end data end
[ "def", "rubyize_format", "(", "original_data", ")", "data", "=", "original_data", ".", "to_snake_keys", ".", "deep_symbolize_keys", "definitions", "=", "data", "[", ":container_definitions", "]", "definitions", ".", "each_with_index", "do", "|", "definition", ",", "i", "|", "next", "unless", "definition", "[", ":log_configuration", "]", "options", "=", "definition", "[", ":log_configuration", "]", "[", ":options", "]", "next", "unless", "options", "# LogConfiguration options do not get transformed and keep their original", "# structure:", "# https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/ECS/Types/ContainerDefinition.html", "original_definition", "=", "original_data", "[", "\"containerDefinitions\"", "]", "[", "i", "]", "definition", "[", ":log_configuration", "]", "[", ":options", "]", "=", "original_definition", "[", "\"logConfiguration\"", "]", "[", "\"options\"", "]", "end", "data", "end" ]
The ruby aws-sdk expects symbols for keys and AWS docs for the task definition uses json camelCase for the keys. This method transforms the keys to the expected ruby aws-sdk format. One quirk is that the logConfiguration options casing should not be transformed.
[ "The", "ruby", "aws", "-", "sdk", "expects", "symbols", "for", "keys", "and", "AWS", "docs", "for", "the", "task", "definition", "uses", "json", "camelCase", "for", "the", "keys", ".", "This", "method", "transforms", "the", "keys", "to", "the", "expected", "ruby", "aws", "-", "sdk", "format", "." ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/tasks/register.rb#L68-L85
train
tongueroo/ufo
lib/ufo/ps.rb
Ufo.Ps.display_scale_help
def display_scale_help return if service.running_count >= service.desired_count events = service["events"][0..3] # only check most recent 4 messages error_event = events.find do |e| e.message =~ /was unable to place a task/ end return unless error_event puts "There is an issue scaling the #{@service.color(:green)} service to #{service.desired_count}. Here's the error:" puts error_event.message.color(:red) if service.launch_type == "EC2" puts "If AutoScaling is set up for the container instances, it can take a little time to add additional instances. You'll see this message until the capacity is added." end end
ruby
def display_scale_help return if service.running_count >= service.desired_count events = service["events"][0..3] # only check most recent 4 messages error_event = events.find do |e| e.message =~ /was unable to place a task/ end return unless error_event puts "There is an issue scaling the #{@service.color(:green)} service to #{service.desired_count}. Here's the error:" puts error_event.message.color(:red) if service.launch_type == "EC2" puts "If AutoScaling is set up for the container instances, it can take a little time to add additional instances. You'll see this message until the capacity is added." end end
[ "def", "display_scale_help", "return", "if", "service", ".", "running_count", ">=", "service", ".", "desired_count", "events", "=", "service", "[", "\"events\"", "]", "[", "0", "..", "3", "]", "# only check most recent 4 messages", "error_event", "=", "events", ".", "find", "do", "|", "e", "|", "e", ".", "message", "=~", "/", "/", "end", "return", "unless", "error_event", "puts", "\"There is an issue scaling the #{@service.color(:green)} service to #{service.desired_count}. Here's the error:\"", "puts", "error_event", ".", "message", ".", "color", "(", ":red", ")", "if", "service", ".", "launch_type", "==", "\"EC2\"", "puts", "\"If AutoScaling is set up for the container instances, it can take a little time to add additional instances. You'll see this message until the capacity is added.\"", "end", "end" ]
If the running count less than the desired account yet, check the events and show a message with helpful debugging information.
[ "If", "the", "running", "count", "less", "than", "the", "desired", "account", "yet", "check", "the", "events", "and", "show", "a", "message", "with", "helpful", "debugging", "information", "." ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/ps.rb#L70-L84
train
tongueroo/ufo
lib/ufo/setting.rb
Ufo.Setting.ufo_env
def ufo_env settings = YAML.load_file("#{Ufo.root}/.ufo/settings.yml") env = settings.find do |_env, section| section ||= {} ENV['AWS_PROFILE'] && ENV['AWS_PROFILE'] == section['aws_profile'] end ufo_env = env.first if env ufo_env = ENV['UFO_ENV'] if ENV['UFO_ENV'] # highest precedence ufo_env || 'development' end
ruby
def ufo_env settings = YAML.load_file("#{Ufo.root}/.ufo/settings.yml") env = settings.find do |_env, section| section ||= {} ENV['AWS_PROFILE'] && ENV['AWS_PROFILE'] == section['aws_profile'] end ufo_env = env.first if env ufo_env = ENV['UFO_ENV'] if ENV['UFO_ENV'] # highest precedence ufo_env || 'development' end
[ "def", "ufo_env", "settings", "=", "YAML", ".", "load_file", "(", "\"#{Ufo.root}/.ufo/settings.yml\"", ")", "env", "=", "settings", ".", "find", "do", "|", "_env", ",", "section", "|", "section", "||=", "{", "}", "ENV", "[", "'AWS_PROFILE'", "]", "&&", "ENV", "[", "'AWS_PROFILE'", "]", "==", "section", "[", "'aws_profile'", "]", "end", "ufo_env", "=", "env", ".", "first", "if", "env", "ufo_env", "=", "ENV", "[", "'UFO_ENV'", "]", "if", "ENV", "[", "'UFO_ENV'", "]", "# highest precedence", "ufo_env", "||", "'development'", "end" ]
Resovles infinite problem since Ufo.env can be determined from UFO_ENV or settings.yml files. When ufo is determined from settings it should not called Ufo.env since that in turn calls Settings.new.data which can then cause an infinite loop.
[ "Resovles", "infinite", "problem", "since", "Ufo", ".", "env", "can", "be", "determined", "from", "UFO_ENV", "or", "settings", ".", "yml", "files", ".", "When", "ufo", "is", "determined", "from", "settings", "it", "should", "not", "called", "Ufo", ".", "env", "since", "that", "in", "turn", "calls", "Settings", ".", "new", ".", "data", "which", "can", "then", "cause", "an", "infinite", "loop", "." ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/setting.rb#L38-L48
train
tongueroo/ufo
lib/ufo/dsl.rb
Ufo.DSL.evaluate_template_definitions
def evaluate_template_definitions source_code = IO.read(@template_definitions_path) begin instance_eval(source_code, @template_definitions_path) rescue Exception => e if e.class == SystemExit # allow exit to happen normally raise else task_definition_error(e) puts "\nFull error:" raise end end end
ruby
def evaluate_template_definitions source_code = IO.read(@template_definitions_path) begin instance_eval(source_code, @template_definitions_path) rescue Exception => e if e.class == SystemExit # allow exit to happen normally raise else task_definition_error(e) puts "\nFull error:" raise end end end
[ "def", "evaluate_template_definitions", "source_code", "=", "IO", ".", "read", "(", "@template_definitions_path", ")", "begin", "instance_eval", "(", "source_code", ",", "@template_definitions_path", ")", "rescue", "Exception", "=>", "e", "if", "e", ".", "class", "==", "SystemExit", "# allow exit to happen normally", "raise", "else", "task_definition_error", "(", "e", ")", "puts", "\"\\nFull error:\"", "raise", "end", "end", "end" ]
All we're doing at this point is saving blocks of code into memory The instance_eval provides the task_definition and helper methods as they are part of this class.
[ "All", "we", "re", "doing", "at", "this", "point", "is", "saving", "blocks", "of", "code", "into", "memory", "The", "instance_eval", "provides", "the", "task_definition", "and", "helper", "methods", "as", "they", "are", "part", "of", "this", "class", "." ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/dsl.rb#L25-L38
train
tongueroo/ufo
lib/ufo/dsl.rb
Ufo.DSL.task_definition_error
def task_definition_error(e) error_info = e.backtrace.first path, line_no, _ = error_info.split(':') line_no = line_no.to_i puts "Error evaluating #{path}:".color(:red) puts e.message puts "Here's the line in #{path} with the error:\n\n" contents = IO.read(path) content_lines = contents.split("\n") context = 5 # lines of context top, bottom = [line_no-context-1, 0].max, line_no+context-1 spacing = content_lines.size.to_s.size content_lines[top..bottom].each_with_index do |line_content, index| line_number = top+index+1 if line_number == line_no printf("%#{spacing}d %s\n".color(:red), line_number, line_content) else printf("%#{spacing}d %s\n", line_number, line_content) end end end
ruby
def task_definition_error(e) error_info = e.backtrace.first path, line_no, _ = error_info.split(':') line_no = line_no.to_i puts "Error evaluating #{path}:".color(:red) puts e.message puts "Here's the line in #{path} with the error:\n\n" contents = IO.read(path) content_lines = contents.split("\n") context = 5 # lines of context top, bottom = [line_no-context-1, 0].max, line_no+context-1 spacing = content_lines.size.to_s.size content_lines[top..bottom].each_with_index do |line_content, index| line_number = top+index+1 if line_number == line_no printf("%#{spacing}d %s\n".color(:red), line_number, line_content) else printf("%#{spacing}d %s\n", line_number, line_content) end end end
[ "def", "task_definition_error", "(", "e", ")", "error_info", "=", "e", ".", "backtrace", ".", "first", "path", ",", "line_no", ",", "_", "=", "error_info", ".", "split", "(", "':'", ")", "line_no", "=", "line_no", ".", "to_i", "puts", "\"Error evaluating #{path}:\"", ".", "color", "(", ":red", ")", "puts", "e", ".", "message", "puts", "\"Here's the line in #{path} with the error:\\n\\n\"", "contents", "=", "IO", ".", "read", "(", "path", ")", "content_lines", "=", "contents", ".", "split", "(", "\"\\n\"", ")", "context", "=", "5", "# lines of context", "top", ",", "bottom", "=", "[", "line_no", "-", "context", "-", "1", ",", "0", "]", ".", "max", ",", "line_no", "+", "context", "-", "1", "spacing", "=", "content_lines", ".", "size", ".", "to_s", ".", "size", "content_lines", "[", "top", "..", "bottom", "]", ".", "each_with_index", "do", "|", "line_content", ",", "index", "|", "line_number", "=", "top", "+", "index", "+", "1", "if", "line_number", "==", "line_no", "printf", "(", "\"%#{spacing}d %s\\n\"", ".", "color", "(", ":red", ")", ",", "line_number", ",", "line_content", ")", "else", "printf", "(", "\"%#{spacing}d %s\\n\"", ",", "line_number", ",", "line_content", ")", "end", "end", "end" ]
Prints out a user friendly task_definition error message
[ "Prints", "out", "a", "user", "friendly", "task_definition", "error", "message" ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/dsl.rb#L41-L62
train
tongueroo/ufo
lib/ufo/stack.rb
Ufo.Stack.template_body
def template_body custom_template = "#{Ufo.root}/.ufo/settings/cfn/stack.yml" path = if File.exist?(custom_template) custom_template else # built-in default File.expand_path("../cfn/stack.yml", File.dirname(__FILE__)) end RenderMePretty.result(path, context: context.scope) end
ruby
def template_body custom_template = "#{Ufo.root}/.ufo/settings/cfn/stack.yml" path = if File.exist?(custom_template) custom_template else # built-in default File.expand_path("../cfn/stack.yml", File.dirname(__FILE__)) end RenderMePretty.result(path, context: context.scope) end
[ "def", "template_body", "custom_template", "=", "\"#{Ufo.root}/.ufo/settings/cfn/stack.yml\"", "path", "=", "if", "File", ".", "exist?", "(", "custom_template", ")", "custom_template", "else", "# built-in default", "File", ".", "expand_path", "(", "\"../cfn/stack.yml\"", ",", "File", ".", "dirname", "(", "__FILE__", ")", ")", "end", "RenderMePretty", ".", "result", "(", "path", ",", "context", ":", "context", ".", "scope", ")", "end" ]
do not memoize template_body it can change for a rename retry
[ "do", "not", "memoize", "template_body", "it", "can", "change", "for", "a", "rename", "retry" ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/stack.rb#L73-L82
train
tongueroo/ufo
lib/ufo/stack.rb
Ufo.Stack.save_template
def save_template path = "/tmp/ufo/#{@stack_name}/stack.yml" FileUtils.mkdir_p(File.dirname(path)) IO.write(path, template_body) puts "Generated template saved at: #{path}" path = "/tmp/ufo/#{@stack_name}/parameters.yml" IO.write(path, JSON.pretty_generate(parameters)) puts "Generated parameters saved at: #{path}" end
ruby
def save_template path = "/tmp/ufo/#{@stack_name}/stack.yml" FileUtils.mkdir_p(File.dirname(path)) IO.write(path, template_body) puts "Generated template saved at: #{path}" path = "/tmp/ufo/#{@stack_name}/parameters.yml" IO.write(path, JSON.pretty_generate(parameters)) puts "Generated parameters saved at: #{path}" end
[ "def", "save_template", "path", "=", "\"/tmp/ufo/#{@stack_name}/stack.yml\"", "FileUtils", ".", "mkdir_p", "(", "File", ".", "dirname", "(", "path", ")", ")", "IO", ".", "write", "(", "path", ",", "template_body", ")", "puts", "\"Generated template saved at: #{path}\"", "path", "=", "\"/tmp/ufo/#{@stack_name}/parameters.yml\"", "IO", ".", "write", "(", "path", ",", "JSON", ".", "pretty_generate", "(", "parameters", ")", ")", "puts", "\"Generated parameters saved at: #{path}\"", "end" ]
Store template in tmp in case for debugging
[ "Store", "template", "in", "tmp", "in", "case", "for", "debugging" ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/stack.rb#L167-L176
train
tongueroo/ufo
lib/ufo/ship.rb
Ufo.Ship.stop_old_tasks
def stop_old_tasks # only works when deployment is blocking return unless @options[:wait] Thread.new do stop = Ufo::Stop.new(@service, @options.merge(mute: true)) while true stop.log "checking for old tasks and waiting for 10 seconds" stop.run sleep 10 end end end
ruby
def stop_old_tasks # only works when deployment is blocking return unless @options[:wait] Thread.new do stop = Ufo::Stop.new(@service, @options.merge(mute: true)) while true stop.log "checking for old tasks and waiting for 10 seconds" stop.run sleep 10 end end end
[ "def", "stop_old_tasks", "# only works when deployment is blocking", "return", "unless", "@options", "[", ":wait", "]", "Thread", ".", "new", "do", "stop", "=", "Ufo", "::", "Stop", ".", "new", "(", "@service", ",", "@options", ".", "merge", "(", "mute", ":", "true", ")", ")", "while", "true", "stop", ".", "log", "\"checking for old tasks and waiting for 10 seconds\"", "stop", ".", "run", "sleep", "10", "end", "end", "end" ]
Start a thread that will poll for ecs deployments and kill of tasks in old deployments. This must be done in a thread because the stack update process is blocking.
[ "Start", "a", "thread", "that", "will", "poll", "for", "ecs", "deployments", "and", "kill", "of", "tasks", "in", "old", "deployments", ".", "This", "must", "be", "done", "in", "a", "thread", "because", "the", "stack", "update", "process", "is", "blocking", "." ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/ship.rb#L40-L52
train
tongueroo/ufo
lib/ufo/info.rb
Ufo.Info.load_balancer
def load_balancer(service) load_balancer = service.load_balancers.first return unless load_balancer resp = elb.describe_target_groups( target_group_arns: [load_balancer.target_group_arn] ) target_group = resp.target_groups.first load_balancer_arn = target_group.load_balancer_arns.first # assume first only resp = elb.describe_load_balancers(load_balancer_arns: [load_balancer_arn]) resp.load_balancers.first end
ruby
def load_balancer(service) load_balancer = service.load_balancers.first return unless load_balancer resp = elb.describe_target_groups( target_group_arns: [load_balancer.target_group_arn] ) target_group = resp.target_groups.first load_balancer_arn = target_group.load_balancer_arns.first # assume first only resp = elb.describe_load_balancers(load_balancer_arns: [load_balancer_arn]) resp.load_balancers.first end
[ "def", "load_balancer", "(", "service", ")", "load_balancer", "=", "service", ".", "load_balancers", ".", "first", "return", "unless", "load_balancer", "resp", "=", "elb", ".", "describe_target_groups", "(", "target_group_arns", ":", "[", "load_balancer", ".", "target_group_arn", "]", ")", "target_group", "=", "resp", ".", "target_groups", ".", "first", "load_balancer_arn", "=", "target_group", ".", "load_balancer_arns", ".", "first", "# assume first only", "resp", "=", "elb", ".", "describe_load_balancers", "(", "load_balancer_arns", ":", "[", "load_balancer_arn", "]", ")", "resp", ".", "load_balancers", ".", "first", "end" ]
Passing in service so method can be used else where.
[ "Passing", "in", "service", "so", "method", "can", "be", "used", "else", "where", "." ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/info.rb#L17-L29
train
tongueroo/ufo
lib/ufo/completer.rb
Ufo.Completer.all_commands
def all_commands commands = @command_class.all_commands.reject do |k,v| v.is_a?(Thor::HiddenCommand) end commands.keys end
ruby
def all_commands commands = @command_class.all_commands.reject do |k,v| v.is_a?(Thor::HiddenCommand) end commands.keys end
[ "def", "all_commands", "commands", "=", "@command_class", ".", "all_commands", ".", "reject", "do", "|", "k", ",", "v", "|", "v", ".", "is_a?", "(", "Thor", "::", "HiddenCommand", ")", "end", "commands", ".", "keys", "end" ]
all top-level commands
[ "all", "top", "-", "level", "commands" ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/completer.rb#L119-L124
train
tongueroo/ufo
lib/ufo/status.rb
Ufo.Status.run
def run unless stack_exists?(@stack_name) puts "The stack #{@stack_name.color(:green)} does not exist." return end resp = cloudformation.describe_stacks(stack_name: @stack_name) stack = resp.stacks.first puts "The current status for the stack #{@stack_name.color(:green)} is #{stack.stack_status.color(:green)}" status_poller = Stack::Status.new(@stack_name) if stack.stack_status =~ /_IN_PROGRESS$/ puts "Stack events (tailing):" # tail all events until done status_poller.hide_time_took = true status_poller.wait else puts "Stack events:" # show the last events that was user initiated status_poller.refresh_events status_poller.show_events(true) end end
ruby
def run unless stack_exists?(@stack_name) puts "The stack #{@stack_name.color(:green)} does not exist." return end resp = cloudformation.describe_stacks(stack_name: @stack_name) stack = resp.stacks.first puts "The current status for the stack #{@stack_name.color(:green)} is #{stack.stack_status.color(:green)}" status_poller = Stack::Status.new(@stack_name) if stack.stack_status =~ /_IN_PROGRESS$/ puts "Stack events (tailing):" # tail all events until done status_poller.hide_time_took = true status_poller.wait else puts "Stack events:" # show the last events that was user initiated status_poller.refresh_events status_poller.show_events(true) end end
[ "def", "run", "unless", "stack_exists?", "(", "@stack_name", ")", "puts", "\"The stack #{@stack_name.color(:green)} does not exist.\"", "return", "end", "resp", "=", "cloudformation", ".", "describe_stacks", "(", "stack_name", ":", "@stack_name", ")", "stack", "=", "resp", ".", "stacks", ".", "first", "puts", "\"The current status for the stack #{@stack_name.color(:green)} is #{stack.stack_status.color(:green)}\"", "status_poller", "=", "Stack", "::", "Status", ".", "new", "(", "@stack_name", ")", "if", "stack", ".", "stack_status", "=~", "/", "/", "puts", "\"Stack events (tailing):\"", "# tail all events until done", "status_poller", ".", "hide_time_took", "=", "true", "status_poller", ".", "wait", "else", "puts", "\"Stack events:\"", "# show the last events that was user initiated", "status_poller", ".", "refresh_events", "status_poller", ".", "show_events", "(", "true", ")", "end", "end" ]
used for the ufo status command
[ "used", "for", "the", "ufo", "status", "command" ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/status.rb#L4-L28
train
tongueroo/ufo
lib/ufo/task.rb
Ufo.Task.adjust_fargate_options
def adjust_fargate_options(options) task_def = recent_task_definition return options unless task_def[:network_mode] == "awsvpc" awsvpc_conf = { subnets: network[:ecs_subnets] } if task_def[:requires_compatibilities] == ["FARGATE"] awsvpc_conf[:assign_public_ip] = "ENABLED" options[:launch_type] = "FARGATE" end options[:network_configuration] = { awsvpc_configuration: awsvpc_conf } options end
ruby
def adjust_fargate_options(options) task_def = recent_task_definition return options unless task_def[:network_mode] == "awsvpc" awsvpc_conf = { subnets: network[:ecs_subnets] } if task_def[:requires_compatibilities] == ["FARGATE"] awsvpc_conf[:assign_public_ip] = "ENABLED" options[:launch_type] = "FARGATE" end options[:network_configuration] = { awsvpc_configuration: awsvpc_conf } options end
[ "def", "adjust_fargate_options", "(", "options", ")", "task_def", "=", "recent_task_definition", "return", "options", "unless", "task_def", "[", ":network_mode", "]", "==", "\"awsvpc\"", "awsvpc_conf", "=", "{", "subnets", ":", "network", "[", ":ecs_subnets", "]", "}", "if", "task_def", "[", ":requires_compatibilities", "]", "==", "[", "\"FARGATE\"", "]", "awsvpc_conf", "[", ":assign_public_ip", "]", "=", "\"ENABLED\"", "options", "[", ":launch_type", "]", "=", "\"FARGATE\"", "end", "options", "[", ":network_configuration", "]", "=", "{", "awsvpc_configuration", ":", "awsvpc_conf", "}", "options", "end" ]
adjust network_configuration based on fargate and network mode of awsvpc
[ "adjust", "network_configuration", "based", "on", "fargate", "and", "network", "mode", "of", "awsvpc" ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/task.rb#L103-L115
train
tongueroo/ufo
lib/ufo/task.rb
Ufo.Task.adjust_security_groups
def adjust_security_groups(options) return options unless options[:network_configuration] && options[:network_configuration][:awsvpc_configuration] awsvpc_conf = options[:network_configuration][:awsvpc_configuration] security_groups = awsvpc_conf[:security_groups] if [nil, '', 'nil'].include?(security_groups) security_groups = [] end if security_groups.empty? fetch = Network::Fetch.new(network[:vpc]) sg = fetch.security_group_id security_groups << sg security_groups.uniq! end # override security groups options[:network_configuration][:awsvpc_configuration][:security_groups] = security_groups options end
ruby
def adjust_security_groups(options) return options unless options[:network_configuration] && options[:network_configuration][:awsvpc_configuration] awsvpc_conf = options[:network_configuration][:awsvpc_configuration] security_groups = awsvpc_conf[:security_groups] if [nil, '', 'nil'].include?(security_groups) security_groups = [] end if security_groups.empty? fetch = Network::Fetch.new(network[:vpc]) sg = fetch.security_group_id security_groups << sg security_groups.uniq! end # override security groups options[:network_configuration][:awsvpc_configuration][:security_groups] = security_groups options end
[ "def", "adjust_security_groups", "(", "options", ")", "return", "options", "unless", "options", "[", ":network_configuration", "]", "&&", "options", "[", ":network_configuration", "]", "[", ":awsvpc_configuration", "]", "awsvpc_conf", "=", "options", "[", ":network_configuration", "]", "[", ":awsvpc_configuration", "]", "security_groups", "=", "awsvpc_conf", "[", ":security_groups", "]", "if", "[", "nil", ",", "''", ",", "'nil'", "]", ".", "include?", "(", "security_groups", ")", "security_groups", "=", "[", "]", "end", "if", "security_groups", ".", "empty?", "fetch", "=", "Network", "::", "Fetch", ".", "new", "(", "network", "[", ":vpc", "]", ")", "sg", "=", "fetch", ".", "security_group_id", "security_groups", "<<", "sg", "security_groups", ".", "uniq!", "end", "# override security groups", "options", "[", ":network_configuration", "]", "[", ":awsvpc_configuration", "]", "[", ":security_groups", "]", "=", "security_groups", "options", "end" ]
Ensures at least 1 security group is assigned if awsvpc_configuration is provided.
[ "Ensures", "at", "least", "1", "security", "group", "is", "assigned", "if", "awsvpc_configuration", "is", "provided", "." ]
16ac3dad28edcab2693c0e7d89a1971aca65b8f9
https://github.com/tongueroo/ufo/blob/16ac3dad28edcab2693c0e7d89a1971aca65b8f9/lib/ufo/task.rb#L119-L139
train