idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
1,000
def fetch_build ( repo_slug , build_number , token ) url = "project/#{repo_slug}/#{build_number}" params = { "circle-token" => token } response = client . get url , params , accept : "application/json" json = JSON . parse ( response . body , symbolize_names : true ) json end
Make the API call and parse the JSON
1,001
def validate_file_contains_plugin! ( file ) plugin_count_was = Danger :: Plugin . all_plugins . length yield if Danger :: Plugin . all_plugins . length == plugin_count_was raise ( "#{file} doesn't contain any valid danger plugins." ) end end
Raises an error when the given block does not register a plugin .
1,002
def print_known_info rows = [ ] rows += method_values_for_plugin_hashes ( core_dsl_attributes ) rows << [ "---" , "---" ] rows += method_values_for_plugin_hashes ( external_dsl_attributes ) rows << [ "---" , "---" ] rows << [ "SCM" , env . scm . class ] rows << [ "Source" , env . ci_source . class ] rows << [ "Requests" , env . request_source . class ] rows << [ "Base Commit" , env . meta_info_for_base ] rows << [ "Head Commit" , env . meta_info_for_head ] params = { } params [ :rows ] = rows . each { | current | current [ 0 ] = current [ 0 ] . yellow } params [ :title ] = "Danger v#{Danger::VERSION}\nDSL Attributes" . green ui . section ( "Info:" ) do ui . puts table = Terminal :: Table . new ( params ) table . align_column ( 0 , :right ) ui . puts table ui . puts end end
Iterates through the DSL s attributes and table s the output
1,003
def message @message ||= begin description , stacktrace = parse . values_at ( :description , :stacktrace ) msg = description msg = msg . red if msg . respond_to? ( :red ) msg << stacktrace if stacktrace msg end end
The message of the exception reports the content of podspec for the line that generated the original exception .
1,004
def run log . info "synapse: starting..." statsd_increment ( 'synapse.start' ) statsd_time ( 'synapse.watchers.start.time' ) do @service_watchers . map do | watcher | begin watcher . start statsd_increment ( "synapse.watcher.start" , [ 'start_result:success' , "watcher_name:#{watcher.name}" ] ) rescue Exception => e statsd_increment ( "synapse.watcher.start" , [ 'start_result:fail' , "watcher_name:#{watcher.name}" , "exception_name:#{e.class.name}" , "exception_message:#{e.message}" ] ) raise e end end end statsd_time ( 'synapse.main_loop.elapsed_time' ) do loops = 0 loop do @service_watchers . each do | w | alive = w . ping? statsd_increment ( 'synapse.watcher.ping.count' , [ "watcher_name:#{w.name}" , "ping_result:#{alive ? "success" : "failure"}" ] ) raise "synapse: service watcher #{w.name} failed ping!" unless alive end if @config_updated @config_updated = false statsd_increment ( 'synapse.config.update' ) @config_generators . each do | config_generator | log . info "synapse: configuring #{config_generator.name}" begin config_generator . update_config ( @service_watchers ) rescue StandardError => e statsd_increment ( "synapse.config.update_failed" , [ "config_name:#{config_generator.name}" ] ) log . error "synapse: update config failed for config #{config_generator.name} with exception #{e}" raise e end end end sleep 1 @config_generators . each do | config_generator | config_generator . tick ( @service_watchers ) end loops += 1 log . debug "synapse: still running at #{Time.now}" if ( loops % 60 ) == 0 end end rescue StandardError => e statsd_increment ( 'synapse.stop' , [ 'stop_avenue:abort' , 'stop_location:main_loop' , "exception_name:#{e.class.name}" , "exception_message:#{e.message}" ] ) log . error "synapse: encountered unexpected exception #{e.inspect} in main thread" raise e ensure log . warn "synapse: exiting; sending stop signal to all watchers" @service_watchers . map do | w | begin w . stop statsd_increment ( "synapse.watcher.stop" , [ 'stop_avenue:clean' , 'stop_location:main_loop' , "watcher_name:#{w.name}" ] ) rescue Exception => e statsd_increment ( "synapse.watcher.stop" , [ 'stop_avenue:exception' , 'stop_location:main_loop' , "watcher_name:#{w.name}" , "exception_name:#{e.class.name}" , "exception_message:#{e.message}" ] ) raise e end end statsd_increment ( 'synapse.stop' , [ 'stop_avenue:clean' , 'stop_location:main_loop' ] ) end
start all the watchers and enable haproxy configuration
1,005
def visit_or_create ( started_at : nil ) ahoy . track_visit ( started_at : started_at ) if ! visit && Ahoy . server_side_visits visit end
if we don t have a visit let s try to create one first
1,006
def track ( name , properties = { } , options = { } ) if exclude? debug "Event excluded" elsif missing_params? debug "Missing required parameters" else data = { visit_token : visit_token , user_id : user . try ( :id ) , name : name . to_s , properties : properties , time : trusted_time ( options [ :time ] ) , event_id : options [ :id ] || generate_id } . select { | _ , v | v } @store . track_event ( data ) end true rescue => e report_exception ( e ) end
can t use keyword arguments here
1,007
def escape_wildcards ( unescaped ) case ActiveRecord :: Base . connection . adapter_name when "Mysql2" . freeze , "PostgreSQL" . freeze unescaped . to_s . gsub ( / \\ / , '\\\\\\1' ) else unescaped end end
replace % \ to \ % \\
1,008
def attribute_name ( column_name = nil ) if column_name @state_machine . config . column = column_name . to_sym else @state_machine . config . column ||= :aasm_state end @state_machine . config . column end
This method is both a getter and a setter
1,009
def i18n_klass ( klass ) klass . model_name . respond_to? ( :i18n_key ) ? klass . model_name . i18n_key : klass . name . underscore end
added for rails < 3 . 0 . 3 compatibility
1,010
def aasm ( * args , & block ) if args [ 0 ] . is_a? ( Symbol ) || args [ 0 ] . is_a? ( String ) state_machine_name = args [ 0 ] . to_sym options = args [ 1 ] || { } else state_machine_name = :default options = args [ 0 ] || { } end AASM :: StateMachineStore . fetch ( self , true ) . register ( state_machine_name , AASM :: StateMachine . new ( state_machine_name ) ) aasm_klass = options [ :with_klass ] || AASM :: Base raise ArgumentError , "The class #{aasm_klass} must inherit from AASM::Base!" unless aasm_klass . ancestors . include? ( AASM :: Base ) @aasm ||= Concurrent :: Map . new if @aasm [ state_machine_name ] options . each do | key , value | @aasm [ state_machine_name ] . state_machine . config . send ( "#{key}=" , value ) end else @aasm [ state_machine_name ] = aasm_klass . new ( self , state_machine_name , AASM :: StateMachineStore . fetch ( self , true ) . machine ( state_machine_name ) , options ) end @aasm [ state_machine_name ] . instance_eval ( & block ) if block @aasm [ state_machine_name ] end
this is the entry point for all state and event definitions
1,011
def may_fire? ( obj , to_state = :: AASM :: NO_VALUE , * args ) _fire ( obj , { :test_only => true } , to_state , * args ) end
a neutered version of fire - it doesn t actually fire the event it just executes the transition guards to determine if a transition is even an option given current conditions .
1,012
def config @config ||= begin raise ( ConfigError , "Cannot find config file: #{file_name}" ) unless File . exist? ( file_name ) env_config = YAML . load ( ERB . new ( File . new ( file_name ) . read ) . result ) [ env ] raise ( ConfigError , "Cannot find environment: #{env} in config file: #{file_name}" ) unless env_config env_config = self . class . send ( :deep_symbolize_keys , env_config ) self . class . send ( :migrate_old_formats! , env_config ) end end
Load the Encryption Configuration from a YAML file .
1,013
def close ( close_child_stream = true ) return if closed? if size . positive? final = @stream_cipher . final @ios . write ( final ) unless final . empty? end @ios . close if close_child_stream @closed = true end
Encrypt data before writing to the supplied stream Close the IO Stream .
1,014
def encrypt ( str , random_iv : SymmetricEncryption . randomize_iv? , compress : false , header : always_add_header ) return if str . nil? str = str . to_s return str if str . empty? encrypted = binary_encrypt ( str , random_iv : random_iv , compress : compress , header : header ) encode ( encrypted ) end
Encrypt and then encode a string
1,015
def decrypt ( str ) decoded = decode ( str ) return unless decoded return decoded if decoded . empty? decrypted = binary_decrypt ( decoded ) decrypted . force_encoding ( SymmetricEncryption :: BINARY_ENCODING ) unless decrypted . force_encoding ( SymmetricEncryption :: UTF8_ENCODING ) . valid_encoding? decrypted end
Decode and Decrypt string Returns a decrypted string after decoding it first according to the encoding setting of this cipher Returns nil if encrypted_string is nil Returns if encrypted_string ==
1,016
def binary_encrypt ( str , random_iv : SymmetricEncryption . randomize_iv? , compress : false , header : always_add_header ) return if str . nil? string = str . to_s return string if string . empty? header = Header . new ( version : version , compress : compress ) if header || random_iv || compress openssl_cipher = :: OpenSSL :: Cipher . new ( cipher_name ) openssl_cipher . encrypt openssl_cipher . key = @key result = if header if random_iv openssl_cipher . iv = header . iv = openssl_cipher . random_iv elsif iv openssl_cipher . iv = iv end header . to_s + openssl_cipher . update ( compress ? Zlib :: Deflate . deflate ( string ) : string ) else openssl_cipher . iv = iv if iv openssl_cipher . update ( string ) end result << openssl_cipher . final end
Advanced use only
1,017
def read_string ( buffer , offset ) len = buffer . byteslice ( offset , 2 ) . unpack ( 'v' ) . first offset += 2 out = buffer . byteslice ( offset , len ) [ out , offset + len ] end
Extracts a string from the supplied buffer . The buffer starts with a 2 byte length indicator in little endian format .
1,018
def gets ( sep_string , length = nil ) return read ( length ) if sep_string . nil? while ( index = @read_buffer . index ( sep_string ) ) . nil? && ! @ios . eof? break if length && @read_buffer . length >= length read_block end index ||= - 1 data = @read_buffer . slice! ( 0 .. index ) @pos += data . length return nil if data . empty? && eof? data end
Reads a single decrypted line from the file up to and including the optional sep_string . A sep_string of nil reads the entire contents of the file Returns nil on eof The stream must be opened for reading or an IOError will be raised .
1,019
def read_header @pos = 0 buf = @ios . read ( @buffer_size , @output_buffer ||= '' . b ) iv , key , cipher_name , cipher = nil header = Header . new if header . parse! ( buf ) @header_present = true @compressed = header . compressed? @version = header . version cipher = header . cipher cipher_name = header . cipher_name || cipher . cipher_name key = header . key iv = header . iv else @header_present = false @compressed = nil cipher = SymmetricEncryption . cipher ( @version ) cipher_name = cipher . cipher_name end @stream_cipher = :: OpenSSL :: Cipher . new ( cipher_name ) @stream_cipher . decrypt @stream_cipher . key = key || cipher . send ( :key ) @stream_cipher . iv = iv || cipher . iv decrypt ( buf ) end
Read the header from the file if present
1,020
def each ( & block ) @ids . each_slice ( @page_size ) do | page_of_ids | resources = @paging_block . call ( page_of_ids ) resources . each ( & block ) end end
Yields each item
1,021
def revision clazz = auditable_type . constantize ( clazz . find_by_id ( auditable_id ) || clazz . new ) . tap do | m | self . class . assign_revision_attributes ( m , self . class . reconstruct_attributes ( ancestors ) . merge ( audit_version : version ) ) end end
Return an instance of what the object looked like at this revision . If the object has been destroyed this will be a new record .
1,022
def new_attributes ( audited_changes || { } ) . inject ( { } . with_indifferent_access ) do | attrs , ( attr , values ) | attrs [ attr ] = values . is_a? ( Array ) ? values . last : values attrs end end
Returns a hash of the changed attributes with the new values
1,023
def old_attributes ( audited_changes || { } ) . inject ( { } . with_indifferent_access ) do | attrs , ( attr , values ) | attrs [ attr ] = Array ( values ) . first attrs end end
Returns a hash of the changed attributes with the old values
1,024
def undo case action when 'create' auditable . destroy! when 'destroy' auditable_type . constantize . create! ( audited_changes ) when 'update' auditable . update_attributes! ( audited_changes . transform_values ( & :first ) ) else raise StandardError , "invalid action given #{action}" end end
Allows user to undo changes
1,025
def user_as_string = ( user ) self . user_as_model = self . username = nil user . is_a? ( :: ActiveRecord :: Base ) ? self . user_as_model = user : self . username = user end
Allows user to be set to either a string or an ActiveRecord object
1,026
def table ( name = nil , options = { } , & block ) if block_given? if name . is_a? ( Hash ) options = name else collection = name end table = Table :: Builder . build ( options , & block ) elsif name . is_a? ( Trestle :: Table ) table = name else table = admin . tables . fetch ( name ) { raise ArgumentError , "Unable to find table named #{name.inspect}" } end collection ||= options [ :collection ] || table . options [ :collection ] collection = collection . call if collection . respond_to? ( :call ) render "trestle/table/table" , table : table , collection : collection end
Renders an existing named table or builds and renders a custom table if a block is provided .
1,027
def page_entries_info ( collection , options = { } ) entry_name = options [ :entry_name ] || "entry" entry_name = entry_name . pluralize unless collection . total_count == 1 if collection . total_pages < 2 t ( 'trestle.helpers.page_entries_info.one_page.display_entries' , entry_name : entry_name , count : collection . total_count , default : "Displaying <strong>all %{count}</strong> %{entry_name}" ) else first = number_with_delimiter ( collection . offset_value + 1 ) last = number_with_delimiter ( ( sum = collection . offset_value + collection . limit_value ) > collection . total_count ? collection . total_count : sum ) total = number_with_delimiter ( collection . total_count ) t ( 'trestle.helpers.page_entries_info.more_pages.display_entries' , entry_name : entry_name , first : first , last : last , total : total , default : "Displaying %{entry_name} <strong>%{first}&nbsp;-&nbsp;%{last}</strong> of <b>%{total}</b>" ) end . html_safe end
Custom version of Kaminari s page_entries_info helper to use a Trestle - scoped I18n key and add a delimiter to the total count .
1,028
def hook ( name , options = { } , & block ) hooks [ name . to_s ] << Hook . new ( name . to_s , options , & block ) end
Register an extension hook
1,029
def trigger_rollback ( user = AnonymousUser . new , env : nil , force : false ) rollback = build_rollback ( user , env : env , force : force ) rollback . save! rollback . enqueue lock_reason = "A rollback for #{rollback.since_commit.sha} has been triggered. " "Please make sure the reason for the rollback has been addressed before deploying again." stack . update! ( lock_reason : lock_reason , lock_author_id : user . id ) rollback end
Rolls the stack back to this deploy
1,030
def compiler_swift_version ( user_version ) return LATEST_SWIFT_VERSION unless user_version LONG_SWIFT_VERSIONS . select do | version | user_version . start_with? ( version ) end . last || "#{user_version[0]}.0" end
Go from a full Swift version like 4 . 2 . 1 to something valid for SWIFT_VERSION .
1,031
def fetch_related_resource_id_tree ( relationship ) relationship_name = relationship . name . to_sym @related_resource_id_trees [ relationship_name ] ||= RelatedResourceIdTree . new ( relationship , self ) end
Gets the related Resource Id Tree for a relationship and creates it first if it does not exist
1,032
def add_resource_fragment ( fragment , include_related ) fragment . primary = true init_included_relationships ( fragment , include_related ) @fragments [ fragment . identity ] = fragment end
Adds a Resource Fragment to the Resources hash
1,033
def add_resource_fragment ( fragment , include_related ) init_included_relationships ( fragment , include_related ) fragment . related_from . each do | rid | @source_resource_id_tree . fragments [ rid ] . add_related_identity ( parent_relationship . name , fragment . identity ) end @fragments [ fragment . identity ] = fragment end
Adds a Resource Fragment to the fragments hash
1,034
def error_reporting scope : nil , timeout : nil , client_config : nil Google :: Cloud . error_reporting @project , @keyfile , scope : scope , timeout : ( timeout || @timeout ) , client_config : client_config end
Create a new object for connecting to the Stackdriver Error Reporting service . Each call creates a new connection .
1,035
def dns scope : nil , retries : nil , timeout : nil Google :: Cloud . dns @project , @keyfile , scope : scope , retries : ( retries || @retries ) , timeout : ( timeout || @timeout ) end
Creates a new object for connecting to the DNS service . Each call creates a new connection .
1,036
def spanner scope : nil , timeout : nil , client_config : nil Google :: Cloud . spanner @project , @keyfile , scope : scope , timeout : ( timeout || @timeout ) , client_config : client_config end
Creates a new object for connecting to the Spanner service . Each call creates a new connection .
1,037
def logging scope : nil , timeout : nil , client_config : nil timeout ||= @timeout Google :: Cloud . logging @project , @keyfile , scope : scope , timeout : timeout , client_config : client_config end
Creates a new object for connecting to the Stackdriver Logging service . Each call creates a new connection .
1,038
def bigquery scope : nil , retries : nil , timeout : nil Google :: Cloud . bigquery @project , @keyfile , scope : scope , retries : ( retries || @retries ) , timeout : ( timeout || @timeout ) end
Creates a new object for connecting to the BigQuery service . Each call creates a new connection .
1,039
def debugger service_name : nil , service_version : nil , scope : nil , timeout : nil , client_config : nil Google :: Cloud . debugger @project , @keyfile , service_name : service_name , service_version : service_version , scope : scope , timeout : ( timeout || @timeout ) , client_config : client_config end
Creates a new debugger object for instrumenting Stackdriver Debugger for an application . Each call creates a new debugger agent with independent connection service .
1,040
def datastore scope : nil , timeout : nil , client_config : nil Google :: Cloud . datastore @project , @keyfile , scope : scope , timeout : ( timeout || @timeout ) , client_config : client_config end
Creates a new object for connecting to the Datastore service . Each call creates a new connection .
1,041
def resource_manager scope : nil , retries : nil , timeout : nil Google :: Cloud . resource_manager @keyfile , scope : scope , retries : ( retries || @retries ) , timeout : ( timeout || @timeout ) end
Creates a new object for connecting to the Resource Manager service . Each call creates a new connection .
1,042
def storage scope : nil , retries : nil , timeout : nil Google :: Cloud . storage @project , @keyfile , scope : scope , retries : ( retries || @retries ) , timeout : ( timeout || @timeout ) end
Creates a new object for connecting to the Storage service . Each call creates a new connection .
1,043
def translate key = nil , scope : nil , retries : nil , timeout : nil Google :: Cloud . translate key , project_id : @project , credentials : @keyfile , scope : scope , retries : ( retries || @retries ) , timeout : ( timeout || @timeout ) end
Creates a new object for connecting to the Cloud Translation API . Each call creates a new connection .
1,044
def firestore scope : nil , timeout : nil , client_config : nil Google :: Cloud . firestore @project , @keyfile , scope : scope , timeout : ( timeout || @timeout ) , client_config : client_config end
Creates a new object for connecting to the Firestore service . Each call creates a new connection .
1,045
def trace scope : nil , timeout : nil , client_config : nil Google :: Cloud . trace @project , @keyfile , scope : scope , timeout : ( timeout || @timeout ) , client_config : client_config end
Creates a new object for connecting to the Stackdriver Trace service . Each call creates a new connection .
1,046
def bigtable scope : nil , timeout : nil , credentials : nil , client_config : nil Google :: Cloud . bigtable ( project_id : @project , credentials : ( credentials || @keyfile ) , scope : scope , timeout : ( timeout || @timeout ) , client_config : client_config ) end
Creates a new object for connecting to the Cloud Bigtable service .
1,047
def matching_body_hashes? ( query_parameters , pattern , content_type ) return false unless query_parameters . is_a? ( Hash ) return false unless query_parameters . keys . sort == pattern . keys . sort query_parameters . each do | key , actual | expected = pattern [ key ] if actual . is_a? ( Hash ) && expected . is_a? ( Hash ) return false unless matching_body_hashes? ( actual , expected , content_type ) else expected = WebMock :: Util :: ValuesStringifier . stringify_values ( expected ) if url_encoded_body? ( content_type ) return false unless expected === actual end end true end
Compare two hashes for equality
1,048
def call ( html , context = { } , result = nil ) context = @default_context . merge ( context ) context = context . freeze result ||= @result_class . new payload = default_payload filters : @filters . map ( & :name ) , context : context , result : result instrument 'call_pipeline.html_pipeline' , payload do result [ :output ] = @filters . inject ( html ) do | doc , filter | perform_filter ( filter , doc , context , result ) end end result end
Apply all filters in the pipeline to the given HTML .
1,049
def to_document ( input , context = { } , result = nil ) result = call ( input , context , result ) HTML :: Pipeline . parse ( result [ :output ] ) end
Like call but guarantee the value returned is a DocumentFragment . Pipelines may return a DocumentFragment or a String . Callers that need a DocumentFragment should use this method .
1,050
def to_html ( input , context = { } , result = nil ) result = call ( input , context , result = nil ) output = result [ :output ] if output . respond_to? ( :to_html ) output . to_html else output . to_s end end
Like call but guarantee the value returned is a string of HTML markup .
1,051
def total_pages count_without_padding = total_count count_without_padding -= @_padding if defined? ( @_padding ) && @_padding count_without_padding = 0 if count_without_padding < 0 total_pages_count = ( count_without_padding . to_f / limit_value ) . ceil max_pages && ( max_pages < total_pages_count ) ? max_pages : total_pages_count rescue FloatDomainError raise ZeroPerPageOperation , "The number of total pages was incalculable. Perhaps you called .per(0)?" end
Total number of pages
1,052
def current_page offset_without_padding = offset_value offset_without_padding -= @_padding if defined? ( @_padding ) && @_padding offset_without_padding = 0 if offset_without_padding < 0 ( offset_without_padding / limit_value ) + 1 rescue ZeroDivisionError raise ZeroPerPageOperation , "Current page was incalculable. Perhaps you called .per(0)?" end
Current page number
1,053
def entry_name ( options = { } ) default = options [ :count ] == 1 ? model_name . human : model_name . human . pluralize model_name . human ( options . reverse_merge ( default : default ) ) end
Used for page_entry_info
1,054
def call_action ( matches ) @action . arity > 0 ? @action . call ( matches ) : @action . call rescue => ex UI . error "Problem with watch action!\n#{ex.message}" UI . error ex . backtrace . join ( "\n" ) end
Executes a watcher action .
1,055
def start if defined? ( JRUBY_VERSION ) unless options [ :no_interactions ] abort "\nSorry, JRuby and interactive mode are incompatible.\n" "As a workaround, use the '-i' option instead.\n\n" "More info: \n" " * https://github.com/guard/guard/issues/754\n" " * https://github.com/jruby/jruby/issues/2383\n\n" end end exit ( Cli :: Environments :: Valid . new ( options ) . start_guard ) end
Start Guard by initializing the defined Guard plugins and watch the file system .
1,056
def notifiers Cli :: Environments :: EvaluateOnly . new ( options ) . evaluate DslDescriber . new . notifiers end
List the Notifiers for use in your system .
1,057
def init ( * plugin_names ) env = Cli :: Environments :: Valid . new ( options ) exitcode = env . initialize_guardfile ( plugin_names ) exit ( exitcode ) end
Initializes the templates of all installed Guard plugins and adds them to the Guardfile when no Guard name is passed . When passing Guard plugin names it does the same but only for those Guard plugins .
1,058
def show Cli :: Environments :: EvaluateOnly . new ( options ) . evaluate DslDescriber . new . show end
Shows all Guard plugins and their options that are defined in the Guardfile
1,059
def add_to_guardfile klass = plugin_class require_relative "guardfile/evaluator" options = Guard . state . session . evaluator_options evaluator = Guardfile :: Evaluator . new ( options ) begin evaluator . evaluate rescue Guard :: Guardfile :: Evaluator :: NoPluginsError end if evaluator . guardfile_include? ( name ) UI . info "Guardfile already includes #{ name } guard" else content = File . read ( "Guardfile" ) File . open ( "Guardfile" , "wb" ) do | f | f . puts ( content ) f . puts ( "" ) f . puts ( klass . template ( plugin_location ) ) end UI . info INFO_ADDED_GUARD_TO_GUARDFILE % name end end
Adds a plugin s template to the Guardfile .
1,060
def _plugin_constant @_plugin_constant ||= Guard . constants . detect do | c | c . to_s . casecmp ( _constant_name . downcase ) . zero? end end
Returns the constant for the current plugin .
1,061
def interactor ( options ) case options when :off Interactor . enabled = false when Hash Interactor . options = options end end
Sets the interactor options or disable the interactor .
1,062
def guard ( name , options = { } ) @plugin_options = options . merge ( watchers : [ ] , callbacks : [ ] ) yield if block_given? @current_groups ||= [ ] groups = @current_groups && @current_groups . last || [ :default ] groups . each do | group | opts = @plugin_options . merge ( group : group ) Guard . state . session . plugins . add ( name , opts ) end @plugin_options = nil end
Declares a Guard plugin to be used when running guard start .
1,063
def watch ( pattern , & action ) @plugin_options ||= nil return guard ( :plugin ) { watch ( pattern , & action ) } unless @plugin_options @plugin_options [ :watchers ] << Watcher . new ( pattern , action ) end
Defines a pattern to be watched in order to run actions on file modification .
1,064
def callback ( * args , & block ) @plugin_options ||= nil fail "callback must be called within a guard block" unless @plugin_options block , events = if args . size > 1 args else [ block , args [ 0 ] ] end @plugin_options [ :callbacks ] << { events : events , listener : block } end
Defines a callback to execute arbitrary code before or after any of the start stop reload run_all run_on_changes run_on_additions run_on_modifications and run_on_removals plugin method .
1,065
def logger ( options ) if options [ :level ] options [ :level ] = options [ :level ] . to_sym unless [ :debug , :info , :warn , :error ] . include? options [ :level ] UI . warning ( format ( WARN_INVALID_LOG_LEVEL , options [ :level ] ) ) options . delete :level end end if options [ :only ] && options [ :except ] UI . warning WARN_INVALID_LOG_OPTIONS options . delete :only options . delete :except end [ :only , :except ] . each do | name | next unless options [ name ] list = [ ] . push ( options [ name ] ) . flatten . map do | plugin | Regexp . escape ( plugin . to_s ) end options [ name ] = Regexp . new ( list . join ( "|" ) , Regexp :: IGNORECASE ) end UI . options = UI . options . merge ( options ) end
Configures the Guard logger .
1,066
def directories ( directories ) directories . each do | dir | fail "Directory #{dir.inspect} does not exist!" unless Dir . exist? ( dir ) end Guard . state . session . watchdirs = directories end
Sets the directories to pass to Listen
1,067
def start ( options = { } ) setup ( options ) UI . debug "Guard starts all plugins" Runner . new . run ( :start ) listener . start watched = Guard . state . session . watchdirs . join ( "', '" ) UI . info "Guard is now watching at '#{ watched }'" exitcode = 0 begin while interactor . foreground != :exit Guard . queue . process while Guard . queue . pending? end rescue Interrupt rescue SystemExit => e exitcode = e . status end exitcode ensure stop end
Start Guard by evaluating the Guardfile initializing declared Guard plugins and starting the available file change listener . Main method for Guard that is called from the CLI when Guard starts .
1,068
def run_all ( scopes = { } ) UI . clear ( force : true ) UI . action_with_scopes ( "Run" , scopes ) Runner . new . run ( :run_all , scopes ) end
Trigger run_all on all Guard plugins currently enabled .
1,069
def pause ( expected = nil ) paused = listener . paused? states = { paused : true , unpaused : false , toggle : ! paused } pause = states [ expected || :toggle ] fail ArgumentError , "invalid mode: #{expected.inspect}" if pause . nil? return if pause == paused listener . public_send ( pause ? :pause : :start ) UI . info "File event handling has been #{pause ? 'paused' : 'resumed'}" end
Pause Guard listening to file changes .
1,070
def show groups = Guard . state . session . groups . all objects = [ ] empty_plugin = OpenStruct . new empty_plugin . options = [ [ "" , nil ] ] groups . each do | group | plugins = Array ( Guard . state . session . plugins . all ( group : group . name ) ) plugins = [ empty_plugin ] if plugins . empty? plugins . each do | plugin | options = plugin . options options = [ [ "" , nil ] ] if options . empty? options . each do | option , raw_value | value = raw_value . nil? ? "" : raw_value . inspect objects << [ group . title , plugin . title , option . to_s , value ] end end end rows = [ ] prev_group = prev_plugin = prev_option = prev_value = nil objects . each do | group , plugin , option , value | group_changed = prev_group != group plugin_changed = ( prev_plugin != plugin || group_changed ) rows << :split if group_changed || plugin_changed rows << { Group : group_changed ? group : "" , Plugin : plugin_changed ? plugin : "" , Option : option , Value : value } prev_group = group prev_plugin = plugin prev_option = option prev_value = value end Formatador . display_compact_table ( rows . drop ( 1 ) , [ :Group , :Plugin , :Option , :Value ] ) end
Shows all Guard plugins and their options that are defined in the Guardfile .
1,071
def notifiers supported = Notifier . supported Notifier . connect ( notify : true , silent : true ) detected = Notifier . detected Notifier . disconnect detected_names = detected . map { | item | item [ :name ] } final_rows = supported . each_with_object ( [ ] ) do | ( name , _ ) , rows | available = detected_names . include? ( name ) ? "✔" : " " notifier = detected . detect { | n | n [ :name ] == name } used = notifier ? "✔" : " " options = notifier ? notifier [ :options ] : { } if options . empty? rows << :split _add_row ( rows , name , available , used , "" , "" ) else options . each_with_index do | ( option , value ) , index | if index == 0 rows << :split _add_row ( rows , name , available , used , option . to_s , value . inspect ) else _add_row ( rows , "" , "" , "" , option . to_s , value . inspect ) end end end rows end Formatador . display_compact_table ( final_rows . drop ( 1 ) , [ :Name , :Available , :Used , :Option , :Value ] ) end
Shows all notifiers and their options that are defined in the Guardfile .
1,072
def run ( task , scope_hash = { } ) Lumberjack . unit_of_work do items = Guard . state . scope . grouped_plugins ( scope_hash || { } ) items . each do | _group , plugins | _run_group_plugins ( plugins ) do | plugin | _supervise ( plugin , task ) if plugin . respond_to? ( task ) end end end end
Runs a Guard - task on all registered plugins .
1,073
def run_on_changes ( modified , added , removed ) types = { MODIFICATION_TASKS => modified , ADDITION_TASKS => added , REMOVAL_TASKS => removed } UI . clearable Guard . state . scope . grouped_plugins . each do | _group , plugins | _run_group_plugins ( plugins ) do | plugin | UI . clear types . each do | tasks , unmatched_paths | next if unmatched_paths . empty? match_result = Watcher . match_files ( plugin , unmatched_paths ) next if match_result . empty? task = tasks . detect { | meth | plugin . respond_to? ( meth ) } _supervise ( plugin , task , match_result ) if task end end end end
Runs the appropriate tasks on all registered plugins based on the passed changes .
1,074
def _supervise ( plugin , task , * args ) catch self . class . stopping_symbol_for ( plugin ) do plugin . hook ( "#{ task }_begin" , * args ) result = UI . options . with_progname ( plugin . class . name ) do begin plugin . send ( task , * args ) rescue Interrupt throw ( :task_has_failed ) end end plugin . hook ( "#{ task }_end" , result ) result end rescue ScriptError , StandardError , RuntimeError UI . error ( "#{ plugin.class.name } failed to achieve its" " <#{ task }>, exception was:" "\n#{ $!.class }: #{ $!.message }" "\n#{ $!.backtrace.join("\n") }" ) Guard . state . session . plugins . remove ( plugin ) UI . info ( "\n#{ plugin.class.name } has just been fired" ) $! end
Run a Guard plugin task but remove the Guard plugin when his work leads to a system failure .
1,075
def content_length return nil if @headers . include? ( Headers :: TRANSFER_ENCODING ) value = @headers [ Headers :: CONTENT_LENGTH ] return nil unless value begin Integer ( value ) rescue ArgumentError nil end end
Value of the Content - Length header .
1,076
def readpartial ( size = BUFFER_SIZE ) return unless @pending_response chunk = @parser . read ( size ) return chunk if chunk finished = ( read_more ( size ) == :eof ) || @parser . finished? chunk = @parser . read ( size ) finish_response if finished chunk . to_s end
Read a chunk of the body
1,077
def start_tls ( req , options ) return unless req . uri . https? && ! failed_proxy_connect? ssl_context = options . ssl_context unless ssl_context ssl_context = OpenSSL :: SSL :: SSLContext . new ssl_context . set_params ( options . ssl || { } ) end @socket . start_tls ( req . uri . host , options . ssl_socket_class , ssl_context ) end
Sets up SSL context and starts TLS if needed .
1,078
def send_proxy_connect_request ( req ) return unless req . uri . https? && req . using_proxy? @pending_request = true req . connect_using_proxy @socket @pending_request = false @pending_response = true read_headers! @proxy_response_headers = @parser . headers if @parser . status_code != 200 @failed_proxy_connect = true return end @parser . reset @pending_response = false end
Open tunnel through proxy
1,079
def set_keep_alive return @keep_alive = false unless @persistent @keep_alive = case @parser . http_version when HTTP_1_0 @parser . headers [ Headers :: CONNECTION ] == KEEP_ALIVE when HTTP_1_1 @parser . headers [ Headers :: CONNECTION ] != CLOSE else false end end
Store whether the connection should be kept alive . Once we reset the parser we lose all of this state .
1,080
def read_more ( size ) return if @parser . finished? value = @socket . readpartial ( size , @buffer ) if value == :eof @parser << "" :eof elsif value @parser << value end rescue IOError , SocketError , SystemCallError => ex raise ConnectionError , "error reading from socket: #{ex}" , ex . backtrace end
Feeds some more data into parser
1,081
def via ( * proxy ) proxy_hash = { } proxy_hash [ :proxy_address ] = proxy [ 0 ] if proxy [ 0 ] . is_a? ( String ) proxy_hash [ :proxy_port ] = proxy [ 1 ] if proxy [ 1 ] . is_a? ( Integer ) proxy_hash [ :proxy_username ] = proxy [ 2 ] if proxy [ 2 ] . is_a? ( String ) proxy_hash [ :proxy_password ] = proxy [ 3 ] if proxy [ 3 ] . is_a? ( String ) proxy_hash [ :proxy_headers ] = proxy [ 2 ] if proxy [ 2 ] . is_a? ( Hash ) proxy_hash [ :proxy_headers ] = proxy [ 4 ] if proxy [ 4 ] . is_a? ( Hash ) raise ( RequestError , "invalid HTTP proxy: #{proxy_hash}" ) unless ( 2 .. 5 ) . cover? ( proxy_hash . keys . size ) branch default_options . with_proxy ( proxy_hash ) end
Make a request through an HTTP proxy
1,082
def basic_auth ( opts ) user = opts . fetch :user pass = opts . fetch :pass auth ( "Basic " + Base64 . strict_encode64 ( "#{user}:#{pass}" ) ) end
Make a request with the given Basic authorization header
1,083
def request ( verb , uri , opts = { } ) opts = @default_options . merge ( opts ) req = build_request ( verb , uri , opts ) res = perform ( req , opts ) return res unless opts . follow Redirector . new ( opts . follow ) . perform ( req , res ) do | request | perform ( request , opts ) end end
Make an HTTP request
1,084
def build_request ( verb , uri , opts = { } ) opts = @default_options . merge ( opts ) uri = make_request_uri ( uri , opts ) headers = make_request_headers ( opts ) body = make_request_body ( opts , headers ) req = HTTP :: Request . new ( :verb => verb , :uri => uri , :uri_normalizer => opts . feature ( :normalize_uri ) &. normalizer , :proxy => opts . proxy , :headers => headers , :body => body ) opts . features . inject ( req ) do | request , ( _name , feature ) | feature . wrap_request ( request ) end end
Prepare an HTTP request
1,085
def verify_connection! ( uri ) if default_options . persistent? && uri . origin != default_options . persistent raise StateError , "Persistence is enabled for #{default_options.persistent}, but we got #{uri.origin}" elsif @connection && ( ! @connection . keep_alive? || @connection . expired? ) close elsif @state == :dirty close end end
Verify our request isn t going to be made against another URI
1,086
def make_request_uri ( uri , opts ) uri = uri . to_s if default_options . persistent? && uri !~ HTTP_OR_HTTPS_RE uri = "#{default_options.persistent}#{uri}" end uri = HTTP :: URI . parse uri if opts . params && ! opts . params . empty? uri . query_values = uri . query_values ( Array ) . to_a . concat ( opts . params . to_a ) end uri . path = "/" if uri . path . empty? uri end
Merges query params if needed
1,087
def make_request_body ( opts , headers ) case when opts . body opts . body when opts . form form = HTTP :: FormData . create opts . form headers [ Headers :: CONTENT_TYPE ] ||= form . content_type form when opts . json body = MimeType [ :json ] . encode opts . json headers [ Headers :: CONTENT_TYPE ] ||= "application/json; charset=#{body.encoding.name}" body end end
Create the request body object to send
1,088
def delete ( name ) name = normalize_header name . to_s @pile . delete_if { | k , _ | k == name } end
Removes header .
1,089
def add ( name , value ) name = normalize_header name . to_s Array ( value ) . each { | v | @pile << [ name , validate_value ( v ) ] } end
Appends header .
1,090
def get ( name ) name = normalize_header name . to_s @pile . select { | k , _ | k == name } . map { | _ , v | v } end
Returns list of header values if any .
1,091
def include? ( name ) name = normalize_header name . to_s @pile . any? { | k , _ | k == name } end
Tells whenever header with given name is set or not .
1,092
def merge! ( other ) self . class . coerce ( other ) . to_h . each { | name , values | set name , values } end
Merges other headers into self .
1,093
def normalize_header ( name ) return name if name =~ CANONICAL_NAME_RE normalized = name . split ( / \- / ) . each ( & :capitalize! ) . join ( "-" ) return normalized if normalized =~ COMPLIANT_NAME_RE raise HeaderError , "Invalid HTTP header field name: #{name.inspect}" end
Transforms name to canonical HTTP header capitalization
1,094
def validate_value ( value ) v = value . to_s return v unless v . include? ( "\n" ) raise HeaderError , "Invalid HTTP header field value: #{v.inspect}" end
Ensures there is no new line character in the header value
1,095
def redirect_to ( uri ) raise StateError , "no Location header in redirect" unless uri verb = @request . verb code = @response . status . code if UNSAFE_VERBS . include? ( verb ) && STRICT_SENSITIVE_CODES . include? ( code ) raise StateError , "can't follow #{@response.status} redirect" if @strict verb = :get end verb = :get if ! SEE_OTHER_ALLOWED_VERBS . include? ( verb ) && 303 == code @request . redirect ( uri , verb ) end
Redirect policy for follow
1,096
def stream ( socket ) include_proxy_headers if using_proxy? && ! @uri . https? Request :: Writer . new ( socket , body , headers , headline ) . stream end
Stream the request to a socket
1,097
def proxy_connect_headers connect_headers = HTTP :: Headers . coerce ( Headers :: HOST => headers [ Headers :: HOST ] , Headers :: USER_AGENT => headers [ Headers :: USER_AGENT ] ) connect_headers [ Headers :: PROXY_AUTHORIZATION ] = proxy_authorization_header if using_authenticated_proxy? connect_headers . merge! ( proxy [ :proxy_headers ] ) if proxy . key? ( :proxy_headers ) connect_headers end
Headers to send with proxy connect request
1,098
def column ( column_number , sheet = nil ) if column_number . is_a? ( :: String ) column_number = :: Roo :: Utils . letter_to_number ( column_number ) end sheet_for ( sheet ) . column ( column_number ) end
returns all values in this column as an array column numbers are 1 2 3 ... like in the spreadsheet
1,099
def excelx_format ( row , col , sheet = nil ) key = normalize ( row , col ) sheet_for ( sheet ) . excelx_format ( key ) end
returns the internal format of an excel cell