_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q10600
Gym.Runner.move_app_thinning_size_report
train
def move_app_thinning_size_report if File.exist?(PackageCommandGenerator.app_thinning_size_report_path) FileUtils.mv(PackageCommandGenerator.app_thinning_size_report_path, File.expand_path(Gym.config[:output_directory]), force: true) app_thinning_size_report_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.app_thinning_size_report_path)) UI.success("Successfully exported the App Thinning Size Report.txt file:") UI.message(app_thinning_size_report_path) app_thinning_size_report_path end end
ruby
{ "resource": "" }
q10601
Gym.Runner.move_apps_folder
train
def move_apps_folder if Dir.exist?(PackageCommandGenerator.apps_path) FileUtils.mv(PackageCommandGenerator.apps_path, File.expand_path(Gym.config[:output_directory]), force: true) apps_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.apps_path)) UI.success("Successfully exported Apps folder:") UI.message(apps_path) apps_path end end
ruby
{ "resource": "" }
q10602
Fastlane.SwiftFastlaneAPIGenerator.determine_api_version
train
def determine_api_version(new_file_content: nil, old_file_content: nil) # we know 100% there is a difference, so no need to compare unless old_file_content.length >= new_file_content.length old_api_version = find_api_version_string(content: old_file_content) return DEFAULT_API_VERSION_STRING if old_api_version.nil? return increment_api_version_string(api_version_string: old_api_version) end relevant_old_file_content = old_file_content[0..(new_file_content.length - 1)] if relevant_old_file_content == new_file_content # no changes at all, just return the same old api version string return find_api_version_string(content: old_file_content) else # there are differences, so calculate a new api_version_string old_api_version = find_api_version_string(content: old_file_content) return DEFAULT_API_VERSION_STRING if old_api_version.nil? return increment_api_version_string(api_version_string: old_api_version) end end
ruby
{ "resource": "" }
q10603
Fastlane.SwiftFastlaneAPIGenerator.increment_api_version_string
train
def increment_api_version_string(api_version_string: nil, increment_by: :patch) versions = api_version_string.split(".") major = versions[0].to_i minor = versions[1].to_i patch = versions[2].to_i case increment_by when :patch patch += 1 when :minor minor += 1 patch = 0 when :major major += 1 minor = 0 patch = 0 end new_version_string = [major, minor, patch].join(".") return new_version_string end
ruby
{ "resource": "" }
q10604
CredentialsManager.AppfileConfig.for_lane
train
def for_lane(lane_name) if lane_name.to_s.split(" ").count > 1 # That's the legacy syntax 'platform name' puts("You use deprecated syntax '#{lane_name}' in your Appfile.".yellow) puts("Please follow the Appfile guide: https://docs.fastlane.tools/advanced/#appfile".yellow) platform, lane_name = lane_name.split(" ") return unless platform == ENV["FASTLANE_PLATFORM_NAME"] # the lane name will be verified below end if ENV["FASTLANE_LANE_NAME"] == lane_name.to_s yield end end
ruby
{ "resource": "" }
q10605
Fastlane.SwiftRunnerUpgrader.file_needs_update?
train
def file_needs_update?(filename: nil) # looking for something like: FastlaneRunnerAPIVersion [0.9.1] regex_to_use = API_VERSION_REGEX source = File.join(self.source_swift_code_file_folder_path, "/#{filename}") target = File.join(self.target_swift_code_file_folder_path, "/#{filename}") # target doesn't have the file yet, so ya, I'd say it needs to be updated return true unless File.exist?(target) source_file_content = File.read(source) target_file_content = File.read(target) bundled_version = source_file_content.match(regex_to_use)[1] target_version = target_file_content.match(regex_to_use)[1] file_versions_are_different = bundled_version != target_version UI.verbose("#{filename} FastlaneRunnerAPIVersion (bundled/target): #{bundled_version}/#{target_version}") files_are_different = source_file_content != target_file_content if files_are_different && !file_versions_are_different UI.verbose("File versions are the same, but the two files are not equal, so that's a problem, setting needs update to 'true'") end needs_update = file_versions_are_different || files_are_different return needs_update end
ruby
{ "resource": "" }
q10606
Fastlane.SwiftRunnerUpgrader.copy_file_if_needed!
train
def copy_file_if_needed!(filename: nil, dry_run: false) needs_update = file_needs_update?(filename: filename) UI.verbose("file #{filename} needs an update") if needs_update # Ok, we know if this file needs an update, can return now if it's a dry run return needs_update if dry_run unless needs_update # no work needed, just return return false end source = File.join(self.source_swift_code_file_folder_path, "/#{filename}") target = File.join(self.target_swift_code_file_folder_path, "/#{filename}") FileUtils.cp(source, target) UI.verbose("Copied #{source} to #{target}") return true end
ruby
{ "resource": "" }
q10607
Thrift.ThreadPoolServer.serve
train
def serve @server_transport.listen begin loop do @thread_q.push(:token) Thread.new do begin loop do client = @server_transport.accept trans = @transport_factory.get_transport(client) prot = @protocol_factory.get_protocol(trans) begin loop do @processor.process(prot, prot) end rescue Thrift::TransportException, Thrift::ProtocolException => e ensure trans.close end end rescue => e @exception_q.push(e) ensure @thread_q.pop # thread died! end end end ensure @server_transport.close end end
ruby
{ "resource": "" }
q10608
Thrift.JsonProtocol.write_json_char
train
def write_json_char(ch) # This table describes the handling for the first 0x30 characters # 0 : escape using "\u00xx" notation # 1 : just output index # <other> : escape using "\<other>" notation kJSONCharTable = [ # 0 1 2 3 4 5 6 7 8 9 A B C D E F 0, 0, 0, 0, 0, 0, 0, 0,'b','t','n', 0,'f','r', 0, 0, # 0 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, # 1 1, 1,'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, # 2 ] ch_value = ch[0] if (ch_value.kind_of? String) ch_value = ch.bytes.first end if (ch_value >= 0x30) if (ch == @@kJSONBackslash) # Only special character >= 0x30 is '\' trans.write(@@kJSONBackslash) trans.write(@@kJSONBackslash) else trans.write(ch) end else outCh = kJSONCharTable[ch_value]; # Check if regular character, backslash escaped, or JSON escaped if outCh.kind_of? String trans.write(@@kJSONBackslash) trans.write(outCh) elsif outCh == 1 trans.write(ch) else write_json_escape_char(ch) end end end
ruby
{ "resource": "" }
q10609
Thrift.JsonProtocol.write_json_string
train
def write_json_string(str) @context.write(trans) trans.write(@@kJSONStringDelimiter) str.split('').each do |ch| write_json_char(ch) end trans.write(@@kJSONStringDelimiter) end
ruby
{ "resource": "" }
q10610
Thrift.JsonProtocol.write_json_base64
train
def write_json_base64(str) @context.write(trans) trans.write(@@kJSONStringDelimiter) trans.write(Base64.strict_encode64(str)) trans.write(@@kJSONStringDelimiter) end
ruby
{ "resource": "" }
q10611
Thrift.JsonProtocol.write_json_double
train
def write_json_double(num) @context.write(trans) # Normalize output of thrift::to_string for NaNs and Infinities special = false; if (num.nan?) special = true; val = @@kThriftNan; elsif (num.infinite?) special = true; val = @@kThriftInfinity; if (num < 0.0) val = @@kThriftNegativeInfinity; end else val = num.to_s end escapeNum = special || @context.escapeNum if (escapeNum) trans.write(@@kJSONStringDelimiter) end trans.write(val) if (escapeNum) trans.write(@@kJSONStringDelimiter) end end
ruby
{ "resource": "" }
q10612
Thrift.JsonProtocol.read_json_escape_char
train
def read_json_escape_char str = @reader.read str += @reader.read str += @reader.read str += @reader.read if RUBY_VERSION >= '1.9' str.hex.chr(Encoding::UTF_8) else str.hex.chr end end
ruby
{ "resource": "" }
q10613
Thrift.JsonProtocol.read_json_string
train
def read_json_string(skipContext = false) # This string's characters must match up with the elements in escape_char_vals. # I don't have '/' on this list even though it appears on www.json.org -- # it is not in the RFC -> it is. See RFC 4627 escape_chars = "\"\\/bfnrt" # The elements of this array must match up with the sequence of characters in # escape_chars escape_char_vals = [ "\"", "\\", "\/", "\b", "\f", "\n", "\r", "\t", ] if !skipContext @context.read(@reader) end read_json_syntax_char(@@kJSONStringDelimiter) ch = "" str = "" while (true) ch = @reader.read if (ch == @@kJSONStringDelimiter) break end if (ch == @@kJSONBackslash) ch = @reader.read if (ch == 'u') ch = read_json_escape_char else pos = escape_chars.index(ch); if (pos.nil?) # not found raise ProtocolException.new(ProtocolException::INVALID_DATA, "Expected control char, got \'#{ch}\'.") end ch = escape_char_vals[pos] end end str += ch end return str end
ruby
{ "resource": "" }
q10614
Thrift.JsonProtocol.read_json_base64
train
def read_json_base64 str = read_json_string m = str.length % 4 if m != 0 # Add missing padding (4 - m).times do str += '=' end end Base64.strict_decode64(str) end
ruby
{ "resource": "" }
q10615
Thrift.JsonProtocol.read_json_numeric_chars
train
def read_json_numeric_chars str = "" while (true) ch = @reader.peek if (!is_json_numeric(ch)) break; end ch = @reader.read str += ch end return str end
ruby
{ "resource": "" }
q10616
Thrift.JsonProtocol.read_json_integer
train
def read_json_integer @context.read(@reader) if (@context.escapeNum) read_json_syntax_char(@@kJSONStringDelimiter) end str = read_json_numeric_chars begin num = Integer(str); rescue raise ProtocolException.new(ProtocolException::INVALID_DATA, "Expected numeric value; got \"#{str}\"") end if (@context.escapeNum) read_json_syntax_char(@@kJSONStringDelimiter) end return num end
ruby
{ "resource": "" }
q10617
Thrift.JsonProtocol.read_json_double
train
def read_json_double @context.read(@reader) num = 0 if (@reader.peek == @@kJSONStringDelimiter) str = read_json_string(true) # Check for NaN, Infinity and -Infinity if (str == @@kThriftNan) num = (+1.0/0.0)/(+1.0/0.0) elsif (str == @@kThriftInfinity) num = +1.0/0.0 elsif (str == @@kThriftNegativeInfinity) num = -1.0/0.0 else if (!@context.escapeNum) # Raise exception -- we should not be in a string in this case raise ProtocolException.new(ProtocolException::INVALID_DATA, "Numeric data unexpectedly quoted") end begin num = Float(str) rescue raise ProtocolException.new(ProtocolException::INVALID_DATA, "Expected numeric value; got \"#{str}\"") end end else if (@context.escapeNum) # This will throw - we should have had a quote if escapeNum == true read_json_syntax_char(@@kJSONStringDelimiter) end str = read_json_numeric_chars begin num = Float(str) rescue raise ProtocolException.new(ProtocolException::INVALID_DATA, "Expected numeric value; got \"#{str}\"") end end return num end
ruby
{ "resource": "" }
q10618
Thrift.BaseProtocol.write_field
train
def write_field(*args) if args.size == 3 # handles the documented method signature - write_field(field_info, fid, value) field_info = args[0] fid = args[1] value = args[2] elsif args.size == 4 # handles the deprecated method signature - write_field(name, type, fid, value) field_info = {:name => args[0], :type => args[1]} fid = args[2] value = args[3] else raise ArgumentError, "wrong number of arguments (#{args.size} for 3)" end write_field_begin(field_info[:name], field_info[:type], fid) write_type(field_info, value) write_field_end end
ruby
{ "resource": "" }
q10619
Thrift.BaseProtocol.write_type
train
def write_type(field_info, value) # if field_info is a Fixnum, assume it is a Thrift::Types constant # convert it into a field_info Hash for backwards compatibility if field_info.is_a? Fixnum field_info = {:type => field_info} end case field_info[:type] when Types::BOOL write_bool(value) when Types::BYTE write_byte(value) when Types::DOUBLE write_double(value) when Types::I16 write_i16(value) when Types::I32 write_i32(value) when Types::I64 write_i64(value) when Types::STRING if field_info[:binary] write_binary(value) else write_string(value) end when Types::STRUCT value.write(self) else raise NotImplementedError end end
ruby
{ "resource": "" }
q10620
Thrift.BaseProtocol.read_type
train
def read_type(field_info) # if field_info is a Fixnum, assume it is a Thrift::Types constant # convert it into a field_info Hash for backwards compatibility if field_info.is_a? Fixnum field_info = {:type => field_info} end case field_info[:type] when Types::BOOL read_bool when Types::BYTE read_byte when Types::DOUBLE read_double when Types::I16 read_i16 when Types::I32 read_i32 when Types::I64 read_i64 when Types::STRING if field_info[:binary] read_binary else read_string end else raise NotImplementedError end end
ruby
{ "resource": "" }
q10621
Thrift.CompactProtocol.write_field_begin_internal
train
def write_field_begin_internal(type, id, type_override=nil) last_id = @last_field.pop # if there's a type override, use that. typeToWrite = type_override || CompactTypes.get_compact_type(type) # check if we can use delta encoding for the field id if id > last_id && id - last_id <= 15 # write them together write_byte((id - last_id) << 4 | typeToWrite) else # write them separate write_byte(typeToWrite) write_i16(id) end @last_field.push(id) nil end
ruby
{ "resource": "" }
q10622
Thrift.CompactProtocol.write_collection_begin
train
def write_collection_begin(elem_type, size) if size <= 14 write_byte(size << 4 | CompactTypes.get_compact_type(elem_type)) else write_byte(0xf0 | CompactTypes.get_compact_type(elem_type)) write_varint32(size) end end
ruby
{ "resource": "" }
q10623
Thrift.BufferedTransport.read_into_buffer
train
def read_into_buffer(buffer, size) i = 0 while i < size # If the read buffer is exhausted, try to read up to DEFAULT_BUFFER more bytes into it. if @index >= @rbuf.size @rbuf = @transport.read(DEFAULT_BUFFER) @index = 0 end # The read buffer has some data now, so copy bytes over to the output buffer. byte = Bytes.get_string_byte(@rbuf, @index) Bytes.set_string_byte(buffer, i, byte) @index += 1 i += 1 end i end
ruby
{ "resource": "" }
q10624
Server.BenchmarkHandler.fibonacci
train
def fibonacci(n) seq = [1, 1] 3.upto(n) do seq << seq[-1] + seq[-2] end seq[n-1] # n is 1-based end
ruby
{ "resource": "" }
q10625
Thrift.FramedTransport.flush
train
def flush return @transport.flush unless @write out = [@wbuf.length].pack('N') # Array#pack should return a BINARY encoded String, so it shouldn't be necessary to force encoding out << @wbuf @transport.write(out) @transport.flush @wbuf = Bytes.empty_byte_buffer end
ruby
{ "resource": "" }
q10626
LiquidInterpolatable.Filters.to_uri
train
def to_uri(uri, base_uri = nil) case base_uri when nil, '' Utils.normalize_uri(uri.to_s) else Utils.normalize_uri(base_uri) + Utils.normalize_uri(uri.to_s) end rescue URI::Error nil end
ruby
{ "resource": "" }
q10627
LiquidInterpolatable.Filters.to_xpath
train
def to_xpath(string) subs = string.to_s.scan(/\G(?:\A\z|[^"]+|[^']+)/).map { |x| case x when /"/ %Q{'#{x}'} else %Q{"#{x}"} end } if subs.size == 1 subs.first else 'concat(' << subs.join(', ') << ')' end end
ruby
{ "resource": "" }
q10628
Agents.WebsiteAgent.store_payload!
train
def store_payload!(old_events, result) case interpolated['mode'].presence when 'on_change' result_json = result.to_json if found = old_events.find { |event| event.payload.to_json == result_json } found.update!(expires_at: new_event_expiration_date) false else true end when 'all', 'merge', '' true else raise "Illegal options[mode]: #{interpolated['mode']}" end end
ruby
{ "resource": "" }
q10629
Vagrant.BatchAction.run
train
def run par = false if @allow_parallel par = true @logger.info("Enabling parallelization by default.") end if par @actions.each do |machine, _, _| if !machine.provider_options[:parallel] @logger.info("Disabling parallelization because provider doesn't support it: #{machine.provider_name}") par = false break end end end if par && @actions.length <= 1 @logger.info("Disabling parallelization because only executing one action") par = false end @logger.info("Batch action will parallelize: #{par.inspect}") threads = [] @actions.each do |machine, action, options| @logger.info("Starting action: #{machine} #{action} #{options}") # Create the new thread to run our action. This is basically just # calling the action but also contains some error handling in it # as well. thread = Thread.new do Thread.current[:error] = nil # Record our pid when we started in order to figure out if # we've forked... start_pid = Process.pid begin if action.is_a?(Proc) action.call(machine) else machine.send(:action, action, options) end rescue Exception => e # If we're not parallelizing, then raise the error. We also # don't raise the error if we've forked, because it'll hang # the process. raise if !par && Process.pid == start_pid # Store the exception that will be processed later Thread.current[:error] = e # We can only do the things below if we do not fork, otherwise # it'll hang the process. if Process.pid == start_pid # Let the user know that this process had an error early # so that they see it while other things are happening. machine.ui.error(I18n.t("vagrant.general.batch_notify_error")) end end # If we forked during the process run, we need to do a hard # exit here. Ruby's fork only copies the running process (which # would be us), so if we return from this thread, it results # in a zombie Ruby process. if Process.pid != start_pid # We forked. exit_status = true if Thread.current[:error] # We had an error, print the stack trace and exit immediately. exit_status = false error = Thread.current[:error] @logger.error(error.inspect) @logger.error(error.message) @logger.error(error.backtrace.join("\n")) end Process.exit!(exit_status) end end # Set some attributes on the thread for later thread[:machine] = machine if !par thread.join(THREAD_MAX_JOIN_TIMEOUT) while thread.alive? end threads << thread end errors = [] threads.each do |thread| # Wait for the thread to complete thread.join(THREAD_MAX_JOIN_TIMEOUT) while thread.alive? # If the thread had an error, then store the error to show later if thread[:error] e = thread[:error] # If the error isn't a Vagrant error, then store the backtrace # as well. if !thread[:error].is_a?(Errors::VagrantError) e = thread[:error] message = e.message message += "\n" message += "\n#{e.backtrace.join("\n")}" errors << I18n.t("vagrant.general.batch_unexpected_error", machine: thread[:machine].name, message: message) else errors << I18n.t("vagrant.general.batch_vagrant_error", machine: thread[:machine].name, message: thread[:error].message) end end end if !errors.empty? raise Errors::BatchMultiError, message: errors.join("\n\n") end end
ruby
{ "resource": "" }
q10630
Vagrant.Registry.get
train
def get(key) return nil if !@items.key?(key) return @results_cache[key] if @results_cache.key?(key) @results_cache[key] = @items[key].call end
ruby
{ "resource": "" }
q10631
Vagrant.Registry.merge
train
def merge(other) self.class.new.tap do |result| result.merge!(self) result.merge!(other) end end
ruby
{ "resource": "" }
q10632
Vagrant.Bundler.init!
train
def init!(plugins, repair=false) if !@initial_specifications @initial_specifications = Gem::Specification.find_all{true} else Gem::Specification.all = @initial_specifications Gem::Specification.reset end # Add HashiCorp RubyGems source if !Gem.sources.include?(HASHICORP_GEMSTORE) current_sources = Gem.sources.sources.dup Gem.sources.clear Gem.sources << HASHICORP_GEMSTORE current_sources.each do |src| Gem.sources << src end end # Generate dependencies for all registered plugins plugin_deps = plugins.map do |name, info| Gem::Dependency.new(name, info['installed_gem_version'].to_s.empty? ? '> 0' : info['installed_gem_version']) end @logger.debug("Current generated plugin dependency list: #{plugin_deps}") # Load dependencies into a request set for resolution request_set = Gem::RequestSet.new(*plugin_deps) # Never allow dependencies to be remotely satisfied during init request_set.remote = false repair_result = nil begin # Compose set for resolution composed_set = generate_vagrant_set # Resolve the request set to ensure proper activation order solution = request_set.resolve(composed_set) rescue Gem::UnsatisfiableDependencyError => failure if repair raise failure if @init_retried @logger.debug("Resolution failed but attempting to repair. Failure: #{failure}") install(plugins) @init_retried = true retry else raise end end # Activate the gems activate_solution(solution) full_vagrant_spec_list = @initial_specifications + solution.map(&:full_spec) if(defined?(::Bundler)) @logger.debug("Updating Bundler with full specification list") ::Bundler.rubygems.replace_entrypoints(full_vagrant_spec_list) end Gem.post_reset do Gem::Specification.all = full_vagrant_spec_list end Gem::Specification.reset nil end
ruby
{ "resource": "" }
q10633
Vagrant.Bundler.update
train
def update(plugins, specific, **opts) specific ||= [] update = opts.merge({gems: specific.empty? ? true : specific}) internal_install(plugins, update) end
ruby
{ "resource": "" }
q10634
Vagrant.Bundler.clean
train
def clean(plugins, **opts) @logger.debug("Cleaning Vagrant plugins of stale gems.") # Generate dependencies for all registered plugins plugin_deps = plugins.map do |name, info| gem_version = info['installed_gem_version'] gem_version = info['gem_version'] if gem_version.to_s.empty? gem_version = "> 0" if gem_version.to_s.empty? Gem::Dependency.new(name, gem_version) end @logger.debug("Current plugin dependency list: #{plugin_deps}") # Load dependencies into a request set for resolution request_set = Gem::RequestSet.new(*plugin_deps) # Never allow dependencies to be remotely satisfied during cleaning request_set.remote = false # Sets that we can resolve our dependencies from. Note that we only # resolve from the current set as all required deps are activated during # init. current_set = generate_vagrant_set # Collect all plugin specifications plugin_specs = Dir.glob(plugin_gem_path.join('specifications/*.gemspec').to_s).map do |spec_path| Gem::Specification.load(spec_path) end # Include environment specific specification if enabled if env_plugin_gem_path plugin_specs += Dir.glob(env_plugin_gem_path.join('specifications/*.gemspec').to_s).map do |spec_path| Gem::Specification.load(spec_path) end end @logger.debug("Generating current plugin state solution set.") # Resolve the request set to ensure proper activation order solution = request_set.resolve(current_set) solution_specs = solution.map(&:full_spec) solution_full_names = solution_specs.map(&:full_name) # Find all specs installed to plugins directory that are not # found within the solution set. plugin_specs.delete_if do |spec| solution_full_names.include?(spec.full_name) end if env_plugin_gem_path # If we are cleaning locally, remove any global specs. If # not, remove any local specs if opts[:env_local] @logger.debug("Removing specifications that are not environment local") plugin_specs.delete_if do |spec| spec.full_gem_path.to_s.include?(plugin_gem_path.realpath.to_s) end else @logger.debug("Removing specifications that are environment local") plugin_specs.delete_if do |spec| spec.full_gem_path.to_s.include?(env_plugin_gem_path.realpath.to_s) end end end @logger.debug("Specifications to be removed - #{plugin_specs.map(&:full_name)}") # Now delete all unused specs plugin_specs.each do |spec| @logger.debug("Uninstalling gem - #{spec.full_name}") Gem::Uninstaller.new(spec.name, version: spec.version, install_dir: plugin_gem_path, all: true, executables: true, force: true, ignore: true, ).uninstall_gem(spec) end solution.find_all do |spec| plugins.keys.include?(spec.name) end end
ruby
{ "resource": "" }
q10635
Vagrant.Bundler.validate_configured_sources!
train
def validate_configured_sources! Gem.sources.each_source do |src| begin src.load_specs(:released) rescue Gem::Exception => source_error if ENV["VAGRANT_ALLOW_PLUGIN_SOURCE_ERRORS"] @logger.warn("Failed to load configured plugin source: #{src}!") @logger.warn("Error received attempting to load source (#{src}): #{source_error}") @logger.warn("Ignoring plugin source load failure due user request via env variable") else @logger.error("Failed to load configured plugin source `#{src}`: #{source_error}") raise Vagrant::Errors::PluginSourceError, source: src.uri.to_s, error_msg: source_error.message end end end end
ruby
{ "resource": "" }
q10636
Vagrant.Bundler.generate_builtin_set
train
def generate_builtin_set(system_plugins=[]) builtin_set = BuiltinSet.new @logger.debug("Generating new builtin set instance.") vagrant_internal_specs.each do |spec| if !system_plugins.include?(spec.name) builtin_set.add_builtin_spec(spec) end end builtin_set end
ruby
{ "resource": "" }
q10637
Vagrant.Bundler.activate_solution
train
def activate_solution(solution) retried = false begin @logger.debug("Activating solution set: #{solution.map(&:full_name)}") solution.each do |activation_request| unless activation_request.full_spec.activated? @logger.debug("Activating gem #{activation_request.full_spec.full_name}") activation_request.full_spec.activate if(defined?(::Bundler)) @logger.debug("Marking gem #{activation_request.full_spec.full_name} loaded within Bundler.") ::Bundler.rubygems.mark_loaded activation_request.full_spec end end end rescue Gem::LoadError => e # Depending on the version of Ruby, the ordering of the solution set # will be either 0..n (molinillo) or n..0 (pre-molinillo). Instead of # attempting to determine what's in use, or if it has some how changed # again, just reverse order on failure and attempt again. if retried @logger.error("Failed to load solution set - #{e.class}: #{e}") matcher = e.message.match(/Could not find '(?<gem_name>[^']+)'/) if matcher && !matcher["gem_name"].empty? desired_activation_request = solution.detect do |request| request.name == matcher["gem_name"] end if desired_activation_request && !desired_activation_request.full_spec.activated? activation_request = desired_activation_request @logger.warn("Found misordered activation request for #{desired_activation_request.full_name}. Moving to solution HEAD.") solution.delete(desired_activation_request) solution.unshift(desired_activation_request) retry end end raise else @logger.debug("Failed to load solution set. Retrying with reverse order.") retried = true solution.reverse! retry end end end
ruby
{ "resource": "" }
q10638
Vagrant.MachineIndex.delete
train
def delete(entry) return true if !entry.id @lock.synchronize do with_index_lock do return true if !@machines[entry.id] # If we don't have the lock, then we need to acquire it. if !@machine_locks[entry.id] raise "Unlocked delete on machine: #{entry.id}" end # Reload so we have the latest data, then delete and save unlocked_reload @machines.delete(entry.id) unlocked_save # Release access on this machine unlocked_release(entry.id) end end true end
ruby
{ "resource": "" }
q10639
Vagrant.MachineIndex.find_by_prefix
train
def find_by_prefix(prefix) @machines.each do |uuid, data| return data.merge("id" => uuid) if uuid.start_with?(prefix) end nil end
ruby
{ "resource": "" }
q10640
Vagrant.MachineIndex.lock_machine
train
def lock_machine(uuid) lock_path = @data_dir.join("#{uuid}.lock") lock_file = lock_path.open("w+") if lock_file.flock(File::LOCK_EX | File::LOCK_NB) === false lock_file.close lock_file = nil end lock_file end
ruby
{ "resource": "" }
q10641
Vagrant.MachineIndex.unlocked_release
train
def unlocked_release(id) lock_file = @machine_locks[id] if lock_file lock_file.close begin File.delete(lock_file.path) rescue Errno::EACCES # Another process is probably opened it, no problem. end @machine_locks.delete(id) end end
ruby
{ "resource": "" }
q10642
Vagrant.MachineIndex.unlocked_reload
train
def unlocked_reload return if !@index_file.file? data = nil begin data = JSON.load(@index_file.read) rescue JSON::ParserError raise Errors::CorruptMachineIndex, path: @index_file.to_s end if data if !data["version"] || data["version"].to_i != 1 raise Errors::CorruptMachineIndex, path: @index_file.to_s end @machines = data["machines"] || {} end end
ruby
{ "resource": "" }
q10643
Vagrant.MachineIndex.with_index_lock
train
def with_index_lock lock_path = "#{@index_file}.lock" File.open(lock_path, "w+") do |f| f.flock(File::LOCK_EX) yield end end
ruby
{ "resource": "" }
q10644
Vagrant.BoxMetadata.version
train
def version(version, **opts) requirements = version.split(",").map do |v| Gem::Requirement.new(v.strip) end providers = nil providers = Array(opts[:provider]).map(&:to_sym) if opts[:provider] @version_map.keys.sort.reverse.each do |v| next if !requirements.all? { |r| r.satisfied_by?(v) } version = Version.new(@version_map[v]) next if (providers & version.providers).empty? if providers return version end nil end
ruby
{ "resource": "" }
q10645
Vagrant.CLI.help
train
def help # We use the optionparser for this. Its just easier. We don't use # an optionparser above because I don't think the performance hits # of creating a whole object are worth checking only a couple flags. opts = OptionParser.new do |o| o.banner = "Usage: vagrant [options] <command> [<args>]" o.separator "" o.on("-v", "--version", "Print the version and exit.") o.on("-h", "--help", "Print this help.") o.separator "" o.separator "Common commands:" # Add the available subcommands as separators in order to print them # out as well. commands = {} longest = 0 Vagrant.plugin("2").manager.commands.each do |key, data| # Skip non-primary commands. These only show up in extended # help output. next if !data[1][:primary] key = key.to_s klass = data[0].call commands[key] = klass.synopsis longest = key.length if key.length > longest end commands.keys.sort.each do |key| o.separator " #{key.ljust(longest+2)} #{commands[key]}" @env.ui.machine("cli-command", key.dup) end o.separator "" o.separator "For help on any individual command run `vagrant COMMAND -h`" o.separator "" o.separator "Additional subcommands are available, but are either more advanced" o.separator "or not commonly used. To see all subcommands, run the command" o.separator "`vagrant list-commands`." end @env.ui.info(opts.help, prefix: false) end
ruby
{ "resource": "" }
q10646
Vagrant.Environment.action_runner
train
def action_runner @action_runner ||= Action::Runner.new do { action_runner: action_runner, box_collection: boxes, hook: method(:hook), host: host, machine_index: machine_index, gems_path: gems_path, home_path: home_path, root_path: root_path, tmp_path: tmp_path, ui: @ui, env: self } end end
ruby
{ "resource": "" }
q10647
Vagrant.Environment.active_machines
train
def active_machines # We have no active machines if we have no data path return [] if !@local_data_path machine_folder = @local_data_path.join("machines") # If the machine folder is not a directory then we just return # an empty array since no active machines exist. return [] if !machine_folder.directory? # Traverse the machines folder accumulate a result result = [] machine_folder.children(true).each do |name_folder| # If this isn't a directory then it isn't a machine next if !name_folder.directory? name = name_folder.basename.to_s.to_sym name_folder.children(true).each do |provider_folder| # If this isn't a directory then it isn't a provider next if !provider_folder.directory? # If this machine doesn't have an ID, then ignore next if !provider_folder.join("id").file? provider = provider_folder.basename.to_s.to_sym result << [name, provider] end end # Return the results result end
ruby
{ "resource": "" }
q10648
Vagrant.Environment.batch
train
def batch(parallel=true) parallel = false if ENV["VAGRANT_NO_PARALLEL"] @batch_lock.synchronize do BatchAction.new(parallel).tap do |b| # Yield it so that the caller can setup actions yield b # And run it! b.run end end end
ruby
{ "resource": "" }
q10649
Vagrant.Environment.hook
train
def hook(name, opts=nil) @logger.info("Running hook: #{name}") opts ||= {} opts[:callable] ||= Action::Builder.new opts[:runner] ||= action_runner opts[:action_name] = name opts[:env] = self opts.delete(:runner).run(opts.delete(:callable), opts) end
ruby
{ "resource": "" }
q10650
Vagrant.Environment.host
train
def host return @host if defined?(@host) # Determine the host class to use. ":detect" is an old Vagrant config # that shouldn't be valid anymore, but we respect it here by assuming # its old behavior. No need to deprecate this because I thin it is # fairly harmless. host_klass = vagrantfile.config.vagrant.host host_klass = nil if host_klass == :detect begin @host = Host.new( host_klass, Vagrant.plugin("2").manager.hosts, Vagrant.plugin("2").manager.host_capabilities, self) rescue Errors::CapabilityHostNotDetected # If the auto-detect failed, then we create a brand new host # with no capabilities and use that. This should almost never happen # since Vagrant works on most host OS's now, so this is a "slow path" klass = Class.new(Vagrant.plugin("2", :host)) do def detect?(env); true; end end hosts = { generic: [klass, nil] } host_caps = {} @host = Host.new(:generic, hosts, host_caps, self) rescue Errors::CapabilityHostExplicitNotDetected => e raise Errors::HostExplicitNotDetected, e.extra_data end end
ruby
{ "resource": "" }
q10651
Vagrant.Environment.lock
train
def lock(name="global", **opts) f = nil # If we don't have a block, then locking is useless, so ignore it return if !block_given? # This allows multiple locks in the same process to be nested return yield if @locks[name] || opts[:noop] # The path to this lock lock_path = data_dir.join("lock.#{name}.lock") @logger.debug("Attempting to acquire process-lock: #{name}") lock("dotlock", noop: name == "dotlock", retry: true) do f = File.open(lock_path, "w+") end # The file locking fails only if it returns "false." If it # succeeds it returns a 0, so we must explicitly check for # the proper error case. while f.flock(File::LOCK_EX | File::LOCK_NB) === false @logger.warn("Process-lock in use: #{name}") if !opts[:retry] raise Errors::EnvironmentLockedError, name: name end sleep 0.2 end @logger.info("Acquired process lock: #{name}") result = nil begin # Mark that we have a lock @locks[name] = true result = yield ensure # We need to make sure that no matter what this is always # reset to false so we don't think we have a lock when we # actually don't. @locks.delete(name) @logger.info("Released process lock: #{name}") end # Clean up the lock file, this requires another lock if name != "dotlock" lock("dotlock", retry: true) do f.close begin File.delete(lock_path) rescue @logger.error( "Failed to delete lock file #{lock_path} - some other thread " + "might be trying to acquire it. ignoring this error") end end end # Return the result return result ensure begin f.close if f rescue IOError end end
ruby
{ "resource": "" }
q10652
Vagrant.Environment.push
train
def push(name) @logger.info("Getting push: #{name}") name = name.to_sym pushes = self.vagrantfile.config.push.__compiled_pushes if !pushes.key?(name) raise Vagrant::Errors::PushStrategyNotDefined, name: name, pushes: pushes.keys end strategy, config = pushes[name] push_registry = Vagrant.plugin("2").manager.pushes klass, _ = push_registry.get(strategy) if klass.nil? raise Vagrant::Errors::PushStrategyNotLoaded, name: strategy, pushes: push_registry.keys end klass.new(self, config).push end
ruby
{ "resource": "" }
q10653
Vagrant.Environment.machine
train
def machine(name, provider, refresh=false) @logger.info("Getting machine: #{name} (#{provider})") # Compose the cache key of the name and provider, and return from # the cache if we have that. cache_key = [name, provider] @machines ||= {} if refresh @logger.info("Refreshing machine (busting cache): #{name} (#{provider})") @machines.delete(cache_key) end if @machines.key?(cache_key) @logger.info("Returning cached machine: #{name} (#{provider})") return @machines[cache_key] end @logger.info("Uncached load of machine.") # Determine the machine data directory and pass it to the machine. machine_data_path = @local_data_path.join( "machines/#{name}/#{provider}") # Create the machine and cache it for future calls. This will also # return the machine from this method. @machines[cache_key] = vagrantfile.machine( name, provider, boxes, machine_data_path, self) end
ruby
{ "resource": "" }
q10654
Vagrant.Environment.setup_local_data_path
train
def setup_local_data_path(force=false) if @local_data_path.nil? @logger.warn("No local data path is set. Local data cannot be stored.") return end @logger.info("Local data path: #{@local_data_path}") # If the local data path is a file, then we are probably seeing an # old (V1) "dotfile." In this case, we upgrade it. The upgrade process # will remove the old data file if it is successful. if @local_data_path.file? upgrade_v1_dotfile(@local_data_path) end # If we don't have a root path, we don't setup anything return if !force && root_path.nil? begin @logger.debug("Creating: #{@local_data_path}") FileUtils.mkdir_p(@local_data_path) # Create the rgloader/loader file so we can use encoded files. loader_file = @local_data_path.join("rgloader", "loader.rb") if !loader_file.file? source_loader = Vagrant.source_root.join("templates/rgloader.rb") FileUtils.mkdir_p(@local_data_path.join("rgloader").to_s) FileUtils.cp(source_loader.to_s, loader_file.to_s) end rescue Errno::EACCES raise Errors::LocalDataDirectoryNotAccessible, local_data_path: @local_data_path.to_s end end
ruby
{ "resource": "" }
q10655
Vagrant.Environment.process_configured_plugins
train
def process_configured_plugins return if !Vagrant.plugins_enabled? errors = vagrantfile.config.vagrant.validate(nil) if !errors["vagrant"].empty? raise Errors::ConfigInvalid, errors: Util::TemplateRenderer.render( "config/validation_failed", errors: errors) end # Check if defined plugins are installed installed = Plugin::Manager.instance.installed_plugins needs_install = [] config_plugins = vagrantfile.config.vagrant.plugins config_plugins.each do |name, info| if !installed[name] needs_install << name end end if !needs_install.empty? ui.warn(I18n.t("vagrant.plugins.local.uninstalled_plugins", plugins: needs_install.sort.join(", "))) if !Vagrant.auto_install_local_plugins? answer = nil until ["y", "n"].include?(answer) answer = ui.ask(I18n.t("vagrant.plugins.local.request_plugin_install") + " [N]: ") answer = answer.strip.downcase answer = "n" if answer.to_s.empty? end if answer == "n" raise Errors::PluginMissingLocalError, plugins: needs_install.sort.join(", ") end end needs_install.each do |name| pconfig = Util::HashWithIndifferentAccess.new(config_plugins[name]) ui.info(I18n.t("vagrant.commands.plugin.installing", name: name)) options = {sources: Vagrant::Bundler::DEFAULT_GEM_SOURCES.dup, env_local: true} options[:sources] = pconfig[:sources] if pconfig[:sources] options[:require] = pconfig[:entry_point] if pconfig[:entry_point] options[:version] = pconfig[:version] if pconfig[:version] spec = Plugin::Manager.instance.install_plugin(name, options) ui.info(I18n.t("vagrant.commands.plugin.installed", name: spec.name, version: spec.version.to_s)) end ui.info("\n") # Force halt after installation and require command to be run again. This # will proper load any new locally installed plugins which are now available. ui.warn(I18n.t("vagrant.plugins.local.install_rerun_command")) exit(-1) end Vagrant::Plugin::Manager.instance.local_file.installed_plugins end
ruby
{ "resource": "" }
q10656
Vagrant.Environment.copy_insecure_private_key
train
def copy_insecure_private_key if !@default_private_key_path.exist? @logger.info("Copying private key to home directory") source = File.expand_path("keys/vagrant", Vagrant.source_root) destination = @default_private_key_path begin FileUtils.cp(source, destination) rescue Errno::EACCES raise Errors::CopyPrivateKeyFailed, source: source, destination: destination end end if !Util::Platform.windows? # On Windows, permissions don't matter as much, so don't worry # about doing chmod. if Util::FileMode.from_octal(@default_private_key_path.stat.mode) != "600" @logger.info("Changing permissions on private key to 0600") @default_private_key_path.chmod(0600) end end end
ruby
{ "resource": "" }
q10657
Vagrant.Environment.find_vagrantfile
train
def find_vagrantfile(search_path, filenames=nil) filenames ||= ["Vagrantfile", "vagrantfile"] filenames.each do |vagrantfile| current_path = search_path.join(vagrantfile) return current_path if current_path.file? end nil end
ruby
{ "resource": "" }
q10658
Vagrant.Environment.upgrade_home_path_v1_1
train
def upgrade_home_path_v1_1 if !ENV["VAGRANT_UPGRADE_SILENT_1_5"] @ui.ask(I18n.t("vagrant.upgrading_home_path_v1_5")) end collection = BoxCollection.new( @home_path.join("boxes"), temp_dir_root: tmp_path) collection.upgrade_v1_1_v1_5 end
ruby
{ "resource": "" }
q10659
Vagrant.Environment.upgrade_v1_dotfile
train
def upgrade_v1_dotfile(path) @logger.info("Upgrading V1 dotfile to V2 directory structure...") # First, verify the file isn't empty. If it is an empty file, we # just delete it and go on with life. contents = path.read.strip if contents.strip == "" @logger.info("V1 dotfile was empty. Removing and moving on.") path.delete return end # Otherwise, verify there is valid JSON in here since a Vagrant # environment would always ensure valid JSON. This is a sanity check # to make sure we don't nuke a dotfile that is not ours... @logger.debug("Attempting to parse JSON of V1 file") json_data = nil begin json_data = JSON.parse(contents) @logger.debug("JSON parsed successfully. Things are okay.") rescue JSON::ParserError # The file could've been tampered with since Vagrant 1.0.x is # supposed to ensure that the contents are valid JSON. Show an error. raise Errors::DotfileUpgradeJSONError, state_file: path.to_s end # Alright, let's upgrade this guy to the new structure. Start by # backing up the old dotfile. backup_file = path.dirname.join(".vagrant.v1.#{Time.now.to_i}") @logger.info("Renaming old dotfile to: #{backup_file}") path.rename(backup_file) # Now, we create the actual local data directory. This should succeed # this time since we renamed the old conflicting V1. setup_local_data_path(true) if json_data["active"] @logger.debug("Upgrading to V2 style for each active VM") json_data["active"].each do |name, id| @logger.info("Upgrading dotfile: #{name} (#{id})") # Create the machine configuration directory directory = @local_data_path.join("machines/#{name}/virtualbox") FileUtils.mkdir_p(directory) # Write the ID file directory.join("id").open("w+") do |f| f.write(id) end end end # Upgrade complete! Let the user know @ui.info(I18n.t("vagrant.general.upgraded_v1_dotfile", backup_path: backup_file.to_s)) end
ruby
{ "resource": "" }
q10660
Vagrant.Guest.detect!
train
def detect! guest_name = @machine.config.vm.guest initialize_capabilities!(guest_name, @guests, @capabilities, @machine) rescue Errors::CapabilityHostExplicitNotDetected => e raise Errors::GuestExplicitNotDetected, value: e.extra_data[:value] rescue Errors::CapabilityHostNotDetected raise Errors::GuestNotDetected end
ruby
{ "resource": "" }
q10661
Vagrant.Vagrantfile.machine
train
def machine(name, provider, boxes, data_path, env) # Load the configuration for the machine results = machine_config(name, provider, boxes, data_path) box = results[:box] config = results[:config] config_errors = results[:config_errors] config_warnings = results[:config_warnings] provider_cls = results[:provider_cls] provider_options = results[:provider_options] # If there were warnings or errors we want to output them if !config_warnings.empty? || !config_errors.empty? # The color of the output depends on whether we have warnings # or errors... level = config_errors.empty? ? :warn : :error output = Util::TemplateRenderer.render( "config/messages", warnings: config_warnings, errors: config_errors).chomp env.ui.send(level, I18n.t("vagrant.general.config_upgrade_messages", name: name, output: output)) # If we had errors, then we bail raise Errors::ConfigUpgradeErrors if !config_errors.empty? end # Get the provider configuration from the final loaded configuration provider_config = config.vm.get_provider_config(provider) # Create machine data directory if it doesn't exist # XXX: Permissions error here. FileUtils.mkdir_p(data_path) # Create the machine and cache it for future calls. This will also # return the machine from this method. return Machine.new(name, provider, provider_cls, provider_config, provider_options, config, data_path, box, env, self) end
ruby
{ "resource": "" }
q10662
Vagrant.Vagrantfile.machine_names_and_options
train
def machine_names_and_options {}.tap do |r| @config.vm.defined_vms.each do |name, subvm| r[name] = subvm.options || {} end end end
ruby
{ "resource": "" }
q10663
Vagrant.Vagrantfile.primary_machine_name
train
def primary_machine_name # If it is a single machine environment, then return the name return machine_names.first if machine_names.length == 1 # If it is a multi-machine environment, then return the primary @config.vm.defined_vms.each do |name, subvm| return name if subvm.options[:primary] end # If no primary was specified, nil it is nil end
ruby
{ "resource": "" }
q10664
Vagrant.Machine.action
train
def action(name, opts=nil) @triggers.fire_triggers(name, :before, @name.to_s, :action) @logger.info("Calling action: #{name} on provider #{@provider}") opts ||= {} # Determine whether we lock or not lock = true lock = opts.delete(:lock) if opts.key?(:lock) # Extra env keys are the remaining opts extra_env = opts.dup # An environment is required for triggers to function properly. This is # passed in specifically for the `#Action::Warden` class triggers. We call it # `:trigger_env` instead of `env` in case it collides with an existing environment extra_env[:trigger_env] = @env check_cwd # Warns the UI if the machine was last used on a different dir # Create a deterministic ID for this machine vf = nil vf = @env.vagrantfile_name[0] if @env.vagrantfile_name id = Digest::MD5.hexdigest( "#{@env.root_path}#{vf}#{@env.local_data_path}#{@name}") # We only lock if we're not executing an SSH action. In the future # we will want to do more fine-grained unlocking in actions themselves # but for a 1.6.2 release this will work. locker = Proc.new { |*args, &block| block.call } locker = @env.method(:lock) if lock && !name.to_s.start_with?("ssh") # Lock this machine for the duration of this action return_env = locker.call("machine-action-#{id}") do # Get the callable from the provider. callable = @provider.action(name) # If this action doesn't exist on the provider, then an exception # must be raised. if callable.nil? raise Errors::UnimplementedProviderAction, action: name, provider: @provider.to_s end # Call the action ui.machine("action", name.to_s, "start") action_result = action_raw(name, callable, extra_env) ui.machine("action", name.to_s, "end") action_result end @triggers.fire_triggers(name, :after, @name.to_s, :action) # preserve returning environment after machine action runs return return_env rescue Errors::EnvironmentLockedError raise Errors::MachineActionLockedError, action: name, name: @name end
ruby
{ "resource": "" }
q10665
Vagrant.Machine.action_raw
train
def action_raw(name, callable, extra_env=nil) # Run the action with the action runner on the environment env = { action_name: "machine_action_#{name}".to_sym, machine: self, machine_action: name, ui: @ui, }.merge(extra_env || {}) @env.action_runner.run(callable, env) end
ruby
{ "resource": "" }
q10666
Vagrant.Machine.id=
train
def id=(value) @logger.info("New machine ID: #{value.inspect}") id_file = nil if @data_dir # The file that will store the id if we have one. This allows the # ID to persist across Vagrant runs. Also, store the UUID for the # machine index. id_file = @data_dir.join("id") end if value if id_file # Write the "id" file with the id given. id_file.open("w+") do |f| f.write(value) end end if uid_file # Write the user id that created this machine uid_file.open("w+") do |f| f.write(Process.uid.to_s) end end # If we don't have a UUID, then create one if index_uuid.nil? # Create the index entry and save it entry = MachineIndex::Entry.new entry.local_data_path = @env.local_data_path entry.name = @name.to_s entry.provider = @provider_name.to_s entry.state = "preparing" entry.vagrantfile_path = @env.root_path entry.vagrantfile_name = @env.vagrantfile_name if @box entry.extra_data["box"] = { "name" => @box.name, "provider" => @box.provider.to_s, "version" => @box.version.to_s, } end entry = @env.machine_index.set(entry) @env.machine_index.release(entry) # Store our UUID so we can access it later if @index_uuid_file @index_uuid_file.open("w+") do |f| f.write(entry.id) end end end else # Delete the file, since the machine is now destroyed id_file.delete if id_file && id_file.file? uid_file.delete if uid_file && uid_file.file? # If we have a UUID associated with the index, remove it uuid = index_uuid if uuid entry = @env.machine_index.get(uuid) @env.machine_index.delete(entry) if entry end if @data_dir # Delete the entire data directory contents since all state # associated with the VM is now gone. @data_dir.children.each do |child| begin child.rmtree rescue Errno::EACCES @logger.info("EACCESS deleting file: #{child}") end end end end # Store the ID locally @id = value.nil? ? nil : value.to_s # Notify the provider that the ID changed in case it needs to do # any accounting from it. @provider.machine_id_changed end
ruby
{ "resource": "" }
q10667
Vagrant.Machine.reload
train
def reload old_id = @id @id = nil if @data_dir # Read the id file from the data directory if it exists as the # ID for the pre-existing physical representation of this machine. id_file = @data_dir.join("id") id_content = id_file.read.strip if id_file.file? if !id_content.to_s.empty? @id = id_content end end if @id != old_id && @provider # It changed, notify the provider @provider.machine_id_changed end @id end
ruby
{ "resource": "" }
q10668
Vagrant.Machine.state
train
def state result = @provider.state raise Errors::MachineStateInvalid if !result.is_a?(MachineState) # Update our state cache if we have a UUID and an entry in the # master index. uuid = index_uuid if uuid # active_machines provides access to query this info on each machine # from a different thread, ensure multiple machines do not access # the locked entry simultaneously as this triggers a locked machine # exception. @state_mutex.synchronize do entry = @env.machine_index.get(uuid) if entry entry.state = result.short_description @env.machine_index.set(entry) @env.machine_index.release(entry) end end end result end
ruby
{ "resource": "" }
q10669
Vagrant.Machine.check_cwd
train
def check_cwd desired_encoding = @env.root_path.to_s.encoding vagrant_cwd_filepath = @data_dir.join('vagrant_cwd') vagrant_cwd = if File.exist?(vagrant_cwd_filepath) File.read(vagrant_cwd_filepath, external_encoding: desired_encoding ).chomp end if !File.identical?(vagrant_cwd.to_s, @env.root_path.to_s) if vagrant_cwd ui.warn(I18n.t( 'vagrant.moved_cwd', old_wd: "#{vagrant_cwd}", current_wd: "#{@env.root_path.to_s}")) end File.write(vagrant_cwd_filepath, @env.root_path.to_s, external_encoding: desired_encoding ) end end
ruby
{ "resource": "" }
q10670
Vagrant.BoxCollection.all
train
def all results = [] with_collection_lock do @logger.debug("Finding all boxes in: #{@directory}") @directory.children(true).each do |child| # Ignore non-directories, since files are not interesting to # us in our folder structure. next if !child.directory? box_name = undir_name(child.basename.to_s) # Otherwise, traverse the subdirectories and see what versions # we have. child.children(true).each do |versiondir| next if !versiondir.directory? next if versiondir.basename.to_s.start_with?(".") version = versiondir.basename.to_s versiondir.children(true).each do |provider| # Ensure version of box is correct before continuing if !Gem::Version.correct?(version) ui = Vagrant::UI::Prefixed.new(Vagrant::UI::Colored.new, "vagrant") ui.warn(I18n.t("vagrant.box_version_malformed", version: version, box_name: box_name)) @logger.debug("Invalid version #{version} for box #{box_name}") next end # Verify this is a potentially valid box. If it looks # correct enough then include it. if provider.directory? && provider.join("metadata.json").file? provider_name = provider.basename.to_s.to_sym @logger.debug("Box: #{box_name} (#{provider_name}, #{version})") results << [box_name, version, provider_name] else @logger.debug("Invalid box #{box_name}, ignoring: #{provider}") end end end end end # Sort the list to group like providers and properly ordered versions results.sort_by! do |box_result| [box_result[0], box_result[2], Gem::Version.new(box_result[1])] end results end
ruby
{ "resource": "" }
q10671
Vagrant.BoxCollection.find
train
def find(name, providers, version) providers = Array(providers) # Build up the requirements we have requirements = version.to_s.split(",").map do |v| Gem::Requirement.new(v.strip) end with_collection_lock do box_directory = @directory.join(dir_name(name)) if !box_directory.directory? @logger.info("Box not found: #{name} (#{providers.join(", ")})") return nil end # Keep a mapping of Gem::Version mangled versions => directories. # ie. 0.1.0.pre.alpha.2 => 0.1.0-alpha.2 # This is so we can sort version numbers properly here, but still # refer to the real directory names in path checks below and pass an # unmangled version string to Box.new version_dir_map = {} versions = box_directory.children(true).map do |versiondir| next if !versiondir.directory? next if versiondir.basename.to_s.start_with?(".") version = Gem::Version.new(versiondir.basename.to_s) version_dir_map[version.to_s] = versiondir.basename.to_s version end.compact # Traverse through versions with the latest version first versions.sort.reverse.each do |v| if !requirements.all? { |r| r.satisfied_by?(v) } # Unsatisfied version requirements next end versiondir = box_directory.join(version_dir_map[v.to_s]) providers.each do |provider| provider_dir = versiondir.join(provider.to_s) next if !provider_dir.directory? @logger.info("Box found: #{name} (#{provider})") metadata_url = nil metadata_url_file = box_directory.join("metadata_url") metadata_url = metadata_url_file.read if metadata_url_file.file? if metadata_url && @hook hook_env = @hook.call( :authenticate_box_url, box_urls: [metadata_url]) metadata_url = hook_env[:box_urls].first end return Box.new( name, provider, version_dir_map[v.to_s], provider_dir, metadata_url: metadata_url, ) end end end nil end
ruby
{ "resource": "" }
q10672
Vagrant.BoxCollection.upgrade_v1_1_v1_5
train
def upgrade_v1_1_v1_5 with_collection_lock do temp_dir = Pathname.new(Dir.mktmpdir(TEMP_PREFIX, @temp_root)) @directory.children(true).each do |boxdir| # Ignore all non-directories because they can't be boxes next if !boxdir.directory? box_name = boxdir.basename.to_s # If it is a v1 box, then we need to upgrade it first if v1_box?(boxdir) upgrade_dir = v1_upgrade(boxdir) FileUtils.mv(upgrade_dir, boxdir.join("virtualbox")) end # Create the directory for this box new_box_dir = temp_dir.join(dir_name(box_name), "0") new_box_dir.mkpath # Go through each provider and move it boxdir.children(true).each do |providerdir| FileUtils.cp_r(providerdir, new_box_dir.join(providerdir.basename)) end end # Move the folder into place @directory.rmtree FileUtils.mv(temp_dir.to_s, @directory.to_s) end end
ruby
{ "resource": "" }
q10673
Vagrant.BoxCollection.clean
train
def clean(name) return false if exists?(name) path = File.join(directory, dir_name(name)) FileUtils.rm_rf(path) end
ruby
{ "resource": "" }
q10674
Vagrant.BoxCollection.dir_name
train
def dir_name(name) name = name.dup name.gsub!(":", VAGRANT_COLON) if Util::Platform.windows? name.gsub!("/", VAGRANT_SLASH) name end
ruby
{ "resource": "" }
q10675
Vagrant.BoxCollection.undir_name
train
def undir_name(name) name = name.dup name.gsub!(VAGRANT_COLON, ":") name.gsub!(VAGRANT_SLASH, "/") name end
ruby
{ "resource": "" }
q10676
Vagrant.BoxCollection.v1_upgrade
train
def v1_upgrade(dir) @logger.debug("Upgrading box in directory: #{dir}") temp_dir = Pathname.new(Dir.mktmpdir(TEMP_PREFIX, @temp_root)) @logger.debug("Temporary directory for upgrading: #{temp_dir}") # Move all the things into the temporary directory dir.children(true).each do |child| # Don't move the temp_dir next if child == temp_dir # Move every other directory into the temporary directory @logger.debug("Copying to upgrade directory: #{child}") FileUtils.mv(child, temp_dir.join(child.basename)) end # If there is no metadata.json file, make one, since this is how # we determine if the box is a V2 box. metadata_file = temp_dir.join("metadata.json") if !metadata_file.file? metadata_file.open("w") do |f| f.write(JSON.generate({ provider: "virtualbox" })) end end # Return the temporary directory temp_dir end
ruby
{ "resource": "" }
q10677
Vagrant.BoxCollection.with_temp_dir
train
def with_temp_dir(dir=nil) dir ||= Dir.mktmpdir(TEMP_PREFIX, @temp_root) dir = Pathname.new(dir) yield dir ensure FileUtils.rm_rf(dir.to_s) end
ruby
{ "resource": "" }
q10678
Vagrant.CapabilityHost.initialize_capabilities!
train
def initialize_capabilities!(host, hosts, capabilities, *args) @cap_logger = Log4r::Logger.new( "vagrant::capability_host::#{self.class.to_s.downcase}") if host && !hosts[host] raise Errors::CapabilityHostExplicitNotDetected, value: host.to_s end if !host host = autodetect_capability_host(hosts, *args) if !host raise Errors::CapabilityHostNotDetected if !host end if !hosts[host] # This should never happen because the autodetect above uses the # hosts hash to look up hosts. And if an explicit host is specified, # we do another check higher up. raise "Internal error. Host not found: #{host}" end name = host host_info = hosts[name] host = host_info[0].new chain = [] chain << [name, host] # Build the proper chain of parents if there are any. # This allows us to do "inheritance" of capabilities later if host_info[1] parent_name = host_info[1] parent_info = hosts[parent_name] while parent_info chain << [parent_name, parent_info[0].new] parent_name = parent_info[1] parent_info = hosts[parent_name] end end @cap_host_chain = chain @cap_args = args @cap_caps = capabilities true end
ruby
{ "resource": "" }
q10679
Vagrant.CapabilityHost.capability
train
def capability(cap_name, *args) cap_mod = capability_module(cap_name.to_sym) if !cap_mod raise Errors::CapabilityNotFound, cap: cap_name.to_s, host: @cap_host_chain[0][0].to_s end cap_method = nil begin cap_method = cap_mod.method(cap_name) rescue NameError raise Errors::CapabilityInvalid, cap: cap_name.to_s, host: @cap_host_chain[0][0].to_s end args = @cap_args + args @cap_logger.info( "Execute capability: #{cap_name} #{args.inspect} (#{@cap_host_chain[0][0]})") cap_method.call(*args) end
ruby
{ "resource": "" }
q10680
Vagrant.CapabilityHost.capability_module
train
def capability_module(cap_name) @cap_logger.debug("Searching for cap: #{cap_name}") @cap_host_chain.each do |host_name, host| @cap_logger.debug("Checking in: #{host_name}") caps = @cap_caps[host_name] if caps && caps.key?(cap_name) @cap_logger.debug("Found cap: #{cap_name} in #{host_name}") return caps[cap_name] end end nil end
ruby
{ "resource": "" }
q10681
Vagrant.Box.in_use?
train
def in_use?(index) results = [] index.each do |entry| box_data = entry.extra_data["box"] next if !box_data # If all the data matches, record it if box_data["name"] == self.name && box_data["provider"] == self.provider.to_s && box_data["version"] == self.version.to_s results << entry end end return nil if results.empty? results end
ruby
{ "resource": "" }
q10682
Vagrant.Box.load_metadata
train
def load_metadata(**download_options) tf = Tempfile.new("vagrant-load-metadata") tf.close url = @metadata_url if File.file?(url) || url !~ /^[a-z0-9]+:.*$/i url = File.expand_path(url) url = Util::Platform.cygwin_windows_path(url) url = "file:#{url}" end opts = { headers: ["Accept: application/json"] }.merge(download_options) Util::Downloader.new(url, tf.path, **opts).download! BoxMetadata.new(File.open(tf.path, "r")) rescue Errors::DownloaderError => e raise Errors::BoxMetadataDownloadError, message: e.extra_data[:message] ensure tf.unlink if tf end
ruby
{ "resource": "" }
q10683
Vagrant.Box.has_update?
train
def has_update?(version=nil, download_options: {}) if !@metadata_url raise Errors::BoxUpdateNoMetadata, name: @name end if download_options.delete(:automatic_check) && !automatic_update_check_allowed? @logger.info("Skipping box update check") return end version += ", " if version version ||= "" version += "> #{@version}" md = self.load_metadata(download_options) newer = md.version(version, provider: @provider) return nil if !newer [md, newer, newer.provider(@provider)] end
ruby
{ "resource": "" }
q10684
Vagrant.Box.automatic_update_check_allowed?
train
def automatic_update_check_allowed? check_path = directory.join("box_update_check") if check_path.exist? last_check_span = Time.now.to_i - check_path.mtime.to_i if last_check_span < BOX_UPDATE_CHECK_INTERVAL @logger.info("box update check is under the interval threshold") return false end end FileUtils.touch(check_path) true end
ruby
{ "resource": "" }
q10685
Vagrant.Box.repackage
train
def repackage(path) @logger.debug("Repackaging box '#{@name}' to: #{path}") Util::SafeChdir.safe_chdir(@directory) do # Find all the files in our current directory and tar it up! files = Dir.glob(File.join(".", "**", "*")).select { |f| File.file?(f) } # Package! Util::Subprocess.execute("bsdtar", "-czf", path.to_s, *files) end @logger.info("Repackaged box '#{@name}' successfully: #{path}") true end
ruby
{ "resource": "" }
q10686
Vagrant.Alias.interpret
train
def interpret(line) # is it a comment? return nil if line.strip.start_with?("#") keyword, command = line.split("=", 2).collect(&:strip) # validate the keyword if keyword.match(/\s/i) raise Errors::AliasInvalidError, alias: line, message: "Alias keywords must not contain any whitespace." end [keyword, command] end
ruby
{ "resource": "" }
q10687
Vagrant.Alias.register
train
def register(keyword, command) @aliases.register(keyword.to_sym) do lambda do |args| # directly execute shell commands if command.start_with?("!") return Util::SafeExec.exec "#{command[1..-1]} #{args.join(" ")}".strip end return CLI.new(command.split.concat(args), @env).execute end end end
ruby
{ "resource": "" }
q10688
Sinatra.Helpers.redirect
train
def redirect(uri, *args) if env['HTTP_VERSION'] == 'HTTP/1.1' and env["REQUEST_METHOD"] != 'GET' status 303 else status 302 end # According to RFC 2616 section 14.30, "the field value consists of a # single absolute URI" response['Location'] = uri(uri, settings.absolute_redirects?, settings.prefixed_redirects?) halt(*args) end
ruby
{ "resource": "" }
q10689
Sinatra.Helpers.uri
train
def uri(addr = nil, absolute = true, add_script_name = true) return addr if addr =~ /\A[A-z][A-z0-9\+\.\-]*:/ uri = [host = ""] if absolute host << "http#{'s' if request.secure?}://" if request.forwarded? or request.port != (request.secure? ? 443 : 80) host << request.host_with_port else host << request.host end end uri << request.script_name.to_s if add_script_name uri << (addr ? addr : request.path_info).to_s File.join uri end
ruby
{ "resource": "" }
q10690
Sinatra.Helpers.content_type
train
def content_type(type = nil, params={}) return response['Content-Type'] unless type default = params.delete :default mime_type = mime_type(type) || default fail "Unknown media type: %p" % type if mime_type.nil? mime_type = mime_type.dup unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type } params[:charset] = params.delete('charset') || settings.default_encoding end params.delete :charset if mime_type.include? 'charset' unless params.empty? mime_type << (mime_type.include?(';') ? ', ' : ';') mime_type << params.map { |kv| kv.join('=') }.join(', ') end response['Content-Type'] = mime_type end
ruby
{ "resource": "" }
q10691
Sinatra.Helpers.stream
train
def stream(keep_open = false) scheduler = env['async.callback'] ? EventMachine : Stream current = @params.dup body Stream.new(scheduler, keep_open) { |out| with_params(current) { yield(out) } } end
ruby
{ "resource": "" }
q10692
Sinatra.Helpers.etag_matches?
train
def etag_matches?(list, new_resource = request.post?) return !new_resource if list == '*' list.to_s.split(/\s*,\s*/).include? response['ETag'] end
ruby
{ "resource": "" }
q10693
Sinatra.Templates.render_ruby
train
def render_ruby(engine, template, options={}, locals={}, &block) options, template = template, nil if template.is_a?(Hash) template = Proc.new { block } if template.nil? render engine, template, options, locals end
ruby
{ "resource": "" }
q10694
Sinatra.Base.filter!
train
def filter!(type, base = settings) filter! type, base.superclass if base.superclass.respond_to?(:filters) base.filters[type].each { |args| process_route(*args) } end
ruby
{ "resource": "" }
q10695
Sinatra.Base.route!
train
def route!(base = settings, pass_block=nil) if routes = base.routes[@request.request_method] routes.each do |pattern, keys, conditions, block| pass_block = process_route(pattern, keys, conditions) do |*args| route_eval { block[*args] } end end end # Run routes defined in superclass. if base.superclass.respond_to?(:routes) return route!(base.superclass, pass_block) end route_eval(&pass_block) if pass_block route_missing end
ruby
{ "resource": "" }
q10696
Sinatra.Base.indifferent_hash
train
def indifferent_hash Hash.new {|hash,key| hash[key.to_s] if Symbol === key } end
ruby
{ "resource": "" }
q10697
RJSON.Parser._reduce_22
train
def _reduce_22(val, _values, result) n = val[0]; result = n.count('.') > 0 ? n.to_f : n.to_i result end
ruby
{ "resource": "" }
q10698
Fluent.Supervisor.dry_run
train
def dry_run begin Fluent::Engine.dry_run_mode = true change_privilege init_engine run_configure rescue Fluent::ConfigError => e $log.error "config error", file: @config_path, error: e $log.debug_backtrace exit!(1) ensure Fluent::Engine.dry_run_mode = false end end
ruby
{ "resource": "" }
q10699
Fluent.MessagePackEventStream.slice
train
def slice(index, num) ensure_unpacked! MultiEventStream.new(@unpacked_times.slice(index, num), @unpacked_records.slice(index, num)) end
ruby
{ "resource": "" }