repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
fastlane/fastlane | sigh/lib/sigh/runner.rb | Sigh.Runner.create_profile! | def create_profile!
cert = certificate_to_use
bundle_id = Sigh.config[:app_identifier]
name = Sigh.config[:provisioning_name] || [bundle_id, profile_type.pretty_type].join(' ')
unless Sigh.config[:skip_fetch_profiles]
if Spaceship.provisioning_profile.all.find { |p| p.name == name }
UI.error("The name '#{name}' is already taken, using another one.")
name += " #{Time.now.to_i}"
end
end
UI.important("Creating new provisioning profile for '#{Sigh.config[:app_identifier]}' with name '#{name}' for '#{Sigh.config[:platform]}' platform")
profile = profile_type.create!(name: name,
bundle_id: bundle_id,
certificate: cert,
mac: Sigh.config[:platform].to_s == 'macos',
sub_platform: Sigh.config[:platform].to_s == 'tvos' ? 'tvOS' : nil,
template_name: Sigh.config[:template_name])
profile
end | ruby | def create_profile!
cert = certificate_to_use
bundle_id = Sigh.config[:app_identifier]
name = Sigh.config[:provisioning_name] || [bundle_id, profile_type.pretty_type].join(' ')
unless Sigh.config[:skip_fetch_profiles]
if Spaceship.provisioning_profile.all.find { |p| p.name == name }
UI.error("The name '#{name}' is already taken, using another one.")
name += " #{Time.now.to_i}"
end
end
UI.important("Creating new provisioning profile for '#{Sigh.config[:app_identifier]}' with name '#{name}' for '#{Sigh.config[:platform]}' platform")
profile = profile_type.create!(name: name,
bundle_id: bundle_id,
certificate: cert,
mac: Sigh.config[:platform].to_s == 'macos',
sub_platform: Sigh.config[:platform].to_s == 'tvos' ? 'tvOS' : nil,
template_name: Sigh.config[:template_name])
profile
end | [
"def",
"create_profile!",
"cert",
"=",
"certificate_to_use",
"bundle_id",
"=",
"Sigh",
".",
"config",
"[",
":app_identifier",
"]",
"name",
"=",
"Sigh",
".",
"config",
"[",
":provisioning_name",
"]",
"||",
"[",
"bundle_id",
",",
"profile_type",
".",
"pretty_type",
"]",
".",
"join",
"(",
"' '",
")",
"unless",
"Sigh",
".",
"config",
"[",
":skip_fetch_profiles",
"]",
"if",
"Spaceship",
".",
"provisioning_profile",
".",
"all",
".",
"find",
"{",
"|",
"p",
"|",
"p",
".",
"name",
"==",
"name",
"}",
"UI",
".",
"error",
"(",
"\"The name '#{name}' is already taken, using another one.\"",
")",
"name",
"+=",
"\" #{Time.now.to_i}\"",
"end",
"end",
"UI",
".",
"important",
"(",
"\"Creating new provisioning profile for '#{Sigh.config[:app_identifier]}' with name '#{name}' for '#{Sigh.config[:platform]}' platform\"",
")",
"profile",
"=",
"profile_type",
".",
"create!",
"(",
"name",
":",
"name",
",",
"bundle_id",
":",
"bundle_id",
",",
"certificate",
":",
"cert",
",",
"mac",
":",
"Sigh",
".",
"config",
"[",
":platform",
"]",
".",
"to_s",
"==",
"'macos'",
",",
"sub_platform",
":",
"Sigh",
".",
"config",
"[",
":platform",
"]",
".",
"to_s",
"==",
"'tvos'",
"?",
"'tvOS'",
":",
"nil",
",",
"template_name",
":",
"Sigh",
".",
"config",
"[",
":template_name",
"]",
")",
"profile",
"end"
] | Create a new profile and return it | [
"Create",
"a",
"new",
"profile",
"and",
"return",
"it"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/sigh/lib/sigh/runner.rb#L122-L142 | train |
fastlane/fastlane | sigh/lib/sigh/runner.rb | Sigh.Runner.certificate_to_use | def certificate_to_use
certificates = certificates_for_profile_and_platform
# Filter them
certificates = certificates.find_all do |c|
if Sigh.config[:cert_id]
next unless c.id == Sigh.config[:cert_id].strip
end
if Sigh.config[:cert_owner_name]
next unless c.owner_name.strip == Sigh.config[:cert_owner_name].strip
end
true
end
# verify certificates
if Helper.mac?
unless Sigh.config[:skip_certificate_verification]
certificates = certificates.find_all do |c|
file = Tempfile.new('cert')
file.write(c.download_raw)
file.close
FastlaneCore::CertChecker.installed?(file.path)
end
end
end
if certificates.count > 1 && !Sigh.config[:development]
UI.important("Found more than one code signing identity. Choosing the first one. Check out `fastlane sigh --help` to see all available options.")
UI.important("Available Code Signing Identities for current filters:")
certificates.each do |c|
str = ["\t- Name:", c.owner_name, "- ID:", c.id + " - Expires", c.expires.strftime("%d/%m/%Y")].join(" ")
UI.message(str.green)
end
end
if certificates.count == 0
filters = ""
filters << "Owner Name: '#{Sigh.config[:cert_owner_name]}' " if Sigh.config[:cert_owner_name]
filters << "Certificate ID: '#{Sigh.config[:cert_id]}' " if Sigh.config[:cert_id]
UI.important("No certificates for filter: #{filters}") if filters.length > 0
message = "Could not find a matching code signing identity for type '#{profile_type.to_s.split(':').last}'. "
message += "It is recommended to use match to manage code signing for you, more information on https://codesigning.guide. "
message += "If you don't want to do so, you can also use cert to generate a new one: https://fastlane.tools/cert"
UI.user_error!(message)
end
return certificates if Sigh.config[:development] # development profiles support multiple certificates
return certificates.first
end | ruby | def certificate_to_use
certificates = certificates_for_profile_and_platform
# Filter them
certificates = certificates.find_all do |c|
if Sigh.config[:cert_id]
next unless c.id == Sigh.config[:cert_id].strip
end
if Sigh.config[:cert_owner_name]
next unless c.owner_name.strip == Sigh.config[:cert_owner_name].strip
end
true
end
# verify certificates
if Helper.mac?
unless Sigh.config[:skip_certificate_verification]
certificates = certificates.find_all do |c|
file = Tempfile.new('cert')
file.write(c.download_raw)
file.close
FastlaneCore::CertChecker.installed?(file.path)
end
end
end
if certificates.count > 1 && !Sigh.config[:development]
UI.important("Found more than one code signing identity. Choosing the first one. Check out `fastlane sigh --help` to see all available options.")
UI.important("Available Code Signing Identities for current filters:")
certificates.each do |c|
str = ["\t- Name:", c.owner_name, "- ID:", c.id + " - Expires", c.expires.strftime("%d/%m/%Y")].join(" ")
UI.message(str.green)
end
end
if certificates.count == 0
filters = ""
filters << "Owner Name: '#{Sigh.config[:cert_owner_name]}' " if Sigh.config[:cert_owner_name]
filters << "Certificate ID: '#{Sigh.config[:cert_id]}' " if Sigh.config[:cert_id]
UI.important("No certificates for filter: #{filters}") if filters.length > 0
message = "Could not find a matching code signing identity for type '#{profile_type.to_s.split(':').last}'. "
message += "It is recommended to use match to manage code signing for you, more information on https://codesigning.guide. "
message += "If you don't want to do so, you can also use cert to generate a new one: https://fastlane.tools/cert"
UI.user_error!(message)
end
return certificates if Sigh.config[:development] # development profiles support multiple certificates
return certificates.first
end | [
"def",
"certificate_to_use",
"certificates",
"=",
"certificates_for_profile_and_platform",
"# Filter them",
"certificates",
"=",
"certificates",
".",
"find_all",
"do",
"|",
"c",
"|",
"if",
"Sigh",
".",
"config",
"[",
":cert_id",
"]",
"next",
"unless",
"c",
".",
"id",
"==",
"Sigh",
".",
"config",
"[",
":cert_id",
"]",
".",
"strip",
"end",
"if",
"Sigh",
".",
"config",
"[",
":cert_owner_name",
"]",
"next",
"unless",
"c",
".",
"owner_name",
".",
"strip",
"==",
"Sigh",
".",
"config",
"[",
":cert_owner_name",
"]",
".",
"strip",
"end",
"true",
"end",
"# verify certificates",
"if",
"Helper",
".",
"mac?",
"unless",
"Sigh",
".",
"config",
"[",
":skip_certificate_verification",
"]",
"certificates",
"=",
"certificates",
".",
"find_all",
"do",
"|",
"c",
"|",
"file",
"=",
"Tempfile",
".",
"new",
"(",
"'cert'",
")",
"file",
".",
"write",
"(",
"c",
".",
"download_raw",
")",
"file",
".",
"close",
"FastlaneCore",
"::",
"CertChecker",
".",
"installed?",
"(",
"file",
".",
"path",
")",
"end",
"end",
"end",
"if",
"certificates",
".",
"count",
">",
"1",
"&&",
"!",
"Sigh",
".",
"config",
"[",
":development",
"]",
"UI",
".",
"important",
"(",
"\"Found more than one code signing identity. Choosing the first one. Check out `fastlane sigh --help` to see all available options.\"",
")",
"UI",
".",
"important",
"(",
"\"Available Code Signing Identities for current filters:\"",
")",
"certificates",
".",
"each",
"do",
"|",
"c",
"|",
"str",
"=",
"[",
"\"\\t- Name:\"",
",",
"c",
".",
"owner_name",
",",
"\"- ID:\"",
",",
"c",
".",
"id",
"+",
"\" - Expires\"",
",",
"c",
".",
"expires",
".",
"strftime",
"(",
"\"%d/%m/%Y\"",
")",
"]",
".",
"join",
"(",
"\" \"",
")",
"UI",
".",
"message",
"(",
"str",
".",
"green",
")",
"end",
"end",
"if",
"certificates",
".",
"count",
"==",
"0",
"filters",
"=",
"\"\"",
"filters",
"<<",
"\"Owner Name: '#{Sigh.config[:cert_owner_name]}' \"",
"if",
"Sigh",
".",
"config",
"[",
":cert_owner_name",
"]",
"filters",
"<<",
"\"Certificate ID: '#{Sigh.config[:cert_id]}' \"",
"if",
"Sigh",
".",
"config",
"[",
":cert_id",
"]",
"UI",
".",
"important",
"(",
"\"No certificates for filter: #{filters}\"",
")",
"if",
"filters",
".",
"length",
">",
"0",
"message",
"=",
"\"Could not find a matching code signing identity for type '#{profile_type.to_s.split(':').last}'. \"",
"message",
"+=",
"\"It is recommended to use match to manage code signing for you, more information on https://codesigning.guide. \"",
"message",
"+=",
"\"If you don't want to do so, you can also use cert to generate a new one: https://fastlane.tools/cert\"",
"UI",
".",
"user_error!",
"(",
"message",
")",
"end",
"return",
"certificates",
"if",
"Sigh",
".",
"config",
"[",
":development",
"]",
"# development profiles support multiple certificates",
"return",
"certificates",
".",
"first",
"end"
] | Certificate to use based on the current distribution mode | [
"Certificate",
"to",
"use",
"based",
"on",
"the",
"current",
"distribution",
"mode"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/sigh/lib/sigh/runner.rb#L186-L237 | train |
fastlane/fastlane | sigh/lib/sigh/runner.rb | Sigh.Runner.download_profile | def download_profile(profile)
UI.important("Downloading provisioning profile...")
profile_name ||= "#{profile_type.pretty_type}_#{Sigh.config[:app_identifier]}"
if Sigh.config[:platform].to_s == 'tvos'
profile_name += "_tvos"
end
if Sigh.config[:platform].to_s == 'macos'
profile_name += '.provisionprofile'
else
profile_name += '.mobileprovision'
end
tmp_path = Dir.mktmpdir("profile_download")
output_path = File.join(tmp_path, profile_name)
File.open(output_path, "wb") do |f|
f.write(profile.download)
end
UI.success("Successfully downloaded provisioning profile...")
return output_path
end | ruby | def download_profile(profile)
UI.important("Downloading provisioning profile...")
profile_name ||= "#{profile_type.pretty_type}_#{Sigh.config[:app_identifier]}"
if Sigh.config[:platform].to_s == 'tvos'
profile_name += "_tvos"
end
if Sigh.config[:platform].to_s == 'macos'
profile_name += '.provisionprofile'
else
profile_name += '.mobileprovision'
end
tmp_path = Dir.mktmpdir("profile_download")
output_path = File.join(tmp_path, profile_name)
File.open(output_path, "wb") do |f|
f.write(profile.download)
end
UI.success("Successfully downloaded provisioning profile...")
return output_path
end | [
"def",
"download_profile",
"(",
"profile",
")",
"UI",
".",
"important",
"(",
"\"Downloading provisioning profile...\"",
")",
"profile_name",
"||=",
"\"#{profile_type.pretty_type}_#{Sigh.config[:app_identifier]}\"",
"if",
"Sigh",
".",
"config",
"[",
":platform",
"]",
".",
"to_s",
"==",
"'tvos'",
"profile_name",
"+=",
"\"_tvos\"",
"end",
"if",
"Sigh",
".",
"config",
"[",
":platform",
"]",
".",
"to_s",
"==",
"'macos'",
"profile_name",
"+=",
"'.provisionprofile'",
"else",
"profile_name",
"+=",
"'.mobileprovision'",
"end",
"tmp_path",
"=",
"Dir",
".",
"mktmpdir",
"(",
"\"profile_download\"",
")",
"output_path",
"=",
"File",
".",
"join",
"(",
"tmp_path",
",",
"profile_name",
")",
"File",
".",
"open",
"(",
"output_path",
",",
"\"wb\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"profile",
".",
"download",
")",
"end",
"UI",
".",
"success",
"(",
"\"Successfully downloaded provisioning profile...\"",
")",
"return",
"output_path",
"end"
] | Downloads and stores the provisioning profile | [
"Downloads",
"and",
"stores",
"the",
"provisioning",
"profile"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/sigh/lib/sigh/runner.rb#L240-L262 | train |
fastlane/fastlane | sigh/lib/sigh/runner.rb | Sigh.Runner.ensure_app_exists! | def ensure_app_exists!
return if Spaceship::App.find(Sigh.config[:app_identifier], mac: Sigh.config[:platform].to_s == 'macos')
print_produce_command(Sigh.config)
UI.user_error!("Could not find App with App Identifier '#{Sigh.config[:app_identifier]}'")
end | ruby | def ensure_app_exists!
return if Spaceship::App.find(Sigh.config[:app_identifier], mac: Sigh.config[:platform].to_s == 'macos')
print_produce_command(Sigh.config)
UI.user_error!("Could not find App with App Identifier '#{Sigh.config[:app_identifier]}'")
end | [
"def",
"ensure_app_exists!",
"return",
"if",
"Spaceship",
"::",
"App",
".",
"find",
"(",
"Sigh",
".",
"config",
"[",
":app_identifier",
"]",
",",
"mac",
":",
"Sigh",
".",
"config",
"[",
":platform",
"]",
".",
"to_s",
"==",
"'macos'",
")",
"print_produce_command",
"(",
"Sigh",
".",
"config",
")",
"UI",
".",
"user_error!",
"(",
"\"Could not find App with App Identifier '#{Sigh.config[:app_identifier]}'\"",
")",
"end"
] | Makes sure the current App ID exists. If not, it will show an appropriate error message | [
"Makes",
"sure",
"the",
"current",
"App",
"ID",
"exists",
".",
"If",
"not",
"it",
"will",
"show",
"an",
"appropriate",
"error",
"message"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/sigh/lib/sigh/runner.rb#L265-L269 | train |
fastlane/fastlane | sigh/lib/sigh/download_all.rb | Sigh.DownloadAll.download_all | def download_all(download_xcode_profiles: false)
UI.message("Starting login with user '#{Sigh.config[:username]}'")
Spaceship.login(Sigh.config[:username], nil)
Spaceship.select_team
UI.message("Successfully logged in")
Spaceship.provisioning_profile.all(xcode: download_xcode_profiles).each do |profile|
if profile.valid?
UI.message("Downloading profile '#{profile.name}'...")
download_profile(profile)
else
UI.important("Skipping invalid/expired profile '#{profile.name}'")
end
end
if download_xcode_profiles
UI.message("This run also included all Xcode managed provisioning profiles, as you used the `--download_xcode_profiles` flag")
else
UI.message("All Xcode managed provisioning profiles were ignored on this, to include them use the `--download_xcode_profiles` flag")
end
end | ruby | def download_all(download_xcode_profiles: false)
UI.message("Starting login with user '#{Sigh.config[:username]}'")
Spaceship.login(Sigh.config[:username], nil)
Spaceship.select_team
UI.message("Successfully logged in")
Spaceship.provisioning_profile.all(xcode: download_xcode_profiles).each do |profile|
if profile.valid?
UI.message("Downloading profile '#{profile.name}'...")
download_profile(profile)
else
UI.important("Skipping invalid/expired profile '#{profile.name}'")
end
end
if download_xcode_profiles
UI.message("This run also included all Xcode managed provisioning profiles, as you used the `--download_xcode_profiles` flag")
else
UI.message("All Xcode managed provisioning profiles were ignored on this, to include them use the `--download_xcode_profiles` flag")
end
end | [
"def",
"download_all",
"(",
"download_xcode_profiles",
":",
"false",
")",
"UI",
".",
"message",
"(",
"\"Starting login with user '#{Sigh.config[:username]}'\"",
")",
"Spaceship",
".",
"login",
"(",
"Sigh",
".",
"config",
"[",
":username",
"]",
",",
"nil",
")",
"Spaceship",
".",
"select_team",
"UI",
".",
"message",
"(",
"\"Successfully logged in\"",
")",
"Spaceship",
".",
"provisioning_profile",
".",
"all",
"(",
"xcode",
":",
"download_xcode_profiles",
")",
".",
"each",
"do",
"|",
"profile",
"|",
"if",
"profile",
".",
"valid?",
"UI",
".",
"message",
"(",
"\"Downloading profile '#{profile.name}'...\"",
")",
"download_profile",
"(",
"profile",
")",
"else",
"UI",
".",
"important",
"(",
"\"Skipping invalid/expired profile '#{profile.name}'\"",
")",
"end",
"end",
"if",
"download_xcode_profiles",
"UI",
".",
"message",
"(",
"\"This run also included all Xcode managed provisioning profiles, as you used the `--download_xcode_profiles` flag\"",
")",
"else",
"UI",
".",
"message",
"(",
"\"All Xcode managed provisioning profiles were ignored on this, to include them use the `--download_xcode_profiles` flag\"",
")",
"end",
"end"
] | Download all valid provisioning profiles | [
"Download",
"all",
"valid",
"provisioning",
"profiles"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/sigh/lib/sigh/download_all.rb#L9-L29 | train |
fastlane/fastlane | fastlane/lib/fastlane/server/socket_server.rb | Fastlane.SocketServer.handle_control_command | def handle_control_command(command)
exit_reason = nil
if command.cancel_signal?
UI.verbose("received cancel signal shutting down, reason: #{command.reason}")
# send an ack to the client to let it know we're shutting down
cancel_response = '{"payload":{"status":"cancelled"}}'
send_response(cancel_response)
exit_reason = :cancelled
elsif command.done_signal?
UI.verbose("received done signal shutting down")
# client is already in the process of shutting down, no need to ack
exit_reason = :done
end
# if the command came in with a user-facing message, display it
if command.user_message
UI.important(command.user_message)
end
# currently all control commands should trigger a disconnect and shutdown
handle_disconnect(error: false, exit_reason: exit_reason)
return COMMAND_EXECUTION_STATE[:already_shutdown]
end | ruby | def handle_control_command(command)
exit_reason = nil
if command.cancel_signal?
UI.verbose("received cancel signal shutting down, reason: #{command.reason}")
# send an ack to the client to let it know we're shutting down
cancel_response = '{"payload":{"status":"cancelled"}}'
send_response(cancel_response)
exit_reason = :cancelled
elsif command.done_signal?
UI.verbose("received done signal shutting down")
# client is already in the process of shutting down, no need to ack
exit_reason = :done
end
# if the command came in with a user-facing message, display it
if command.user_message
UI.important(command.user_message)
end
# currently all control commands should trigger a disconnect and shutdown
handle_disconnect(error: false, exit_reason: exit_reason)
return COMMAND_EXECUTION_STATE[:already_shutdown]
end | [
"def",
"handle_control_command",
"(",
"command",
")",
"exit_reason",
"=",
"nil",
"if",
"command",
".",
"cancel_signal?",
"UI",
".",
"verbose",
"(",
"\"received cancel signal shutting down, reason: #{command.reason}\"",
")",
"# send an ack to the client to let it know we're shutting down",
"cancel_response",
"=",
"'{\"payload\":{\"status\":\"cancelled\"}}'",
"send_response",
"(",
"cancel_response",
")",
"exit_reason",
"=",
":cancelled",
"elsif",
"command",
".",
"done_signal?",
"UI",
".",
"verbose",
"(",
"\"received done signal shutting down\"",
")",
"# client is already in the process of shutting down, no need to ack",
"exit_reason",
"=",
":done",
"end",
"# if the command came in with a user-facing message, display it",
"if",
"command",
".",
"user_message",
"UI",
".",
"important",
"(",
"command",
".",
"user_message",
")",
"end",
"# currently all control commands should trigger a disconnect and shutdown",
"handle_disconnect",
"(",
"error",
":",
"false",
",",
"exit_reason",
":",
"exit_reason",
")",
"return",
"COMMAND_EXECUTION_STATE",
"[",
":already_shutdown",
"]",
"end"
] | we got a server control command from the client to do something like shutdown | [
"we",
"got",
"a",
"server",
"control",
"command",
"from",
"the",
"client",
"to",
"do",
"something",
"like",
"shutdown"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane/lib/fastlane/server/socket_server.rb#L94-L119 | train |
fastlane/fastlane | fastlane/lib/fastlane/server/socket_server.rb | Fastlane.SocketServer.send_response | def send_response(json)
UI.verbose("sending #{json}")
begin
@client.puts(json) # Send some json to the client
rescue Errno::EPIPE => e
UI.verbose(e)
return COMMAND_EXECUTION_STATE[:error]
end
return COMMAND_EXECUTION_STATE[:ready]
end | ruby | def send_response(json)
UI.verbose("sending #{json}")
begin
@client.puts(json) # Send some json to the client
rescue Errno::EPIPE => e
UI.verbose(e)
return COMMAND_EXECUTION_STATE[:error]
end
return COMMAND_EXECUTION_STATE[:ready]
end | [
"def",
"send_response",
"(",
"json",
")",
"UI",
".",
"verbose",
"(",
"\"sending #{json}\"",
")",
"begin",
"@client",
".",
"puts",
"(",
"json",
")",
"# Send some json to the client",
"rescue",
"Errno",
"::",
"EPIPE",
"=>",
"e",
"UI",
".",
"verbose",
"(",
"e",
")",
"return",
"COMMAND_EXECUTION_STATE",
"[",
":error",
"]",
"end",
"return",
"COMMAND_EXECUTION_STATE",
"[",
":ready",
"]",
"end"
] | send json back to client | [
"send",
"json",
"back",
"to",
"client"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane/lib/fastlane/server/socket_server.rb#L128-L137 | train |
fastlane/fastlane | fastlane/lib/fastlane/server/socket_server.rb | Fastlane.SocketServer.execute_action_command | def execute_action_command(command: nil)
command_return = @command_executor.execute(command: command, target_object: nil)
## probably need to just return Strings, or ready_for_next with object isn't String
return_object = command_return.return_value
return_value_type = command_return.return_value_type
closure_arg = command_return.closure_argument_value
return_object = return_value_processor.prepare_object(
return_value: return_object,
return_value_type: return_value_type
)
if closure_arg.nil?
closure_arg = closure_arg.to_s
else
closure_arg = return_value_processor.prepare_object(
return_value: closure_arg,
return_value_type: :string # always assume string for closure error_callback
)
end
Thread.current[:exception] = nil
payload = {
payload: {
status: "ready_for_next",
return_object: return_object,
closure_argument_value: closure_arg
}
}
return JSON.generate(payload)
rescue StandardError => e
Thread.current[:exception] = e
exception_array = []
exception_array << "#{e.class}:"
exception_array << e.backtrace
while e.respond_to?("cause") && (e = e.cause)
exception_array << "cause: #{e.class}"
exception_array << e.backtrace
end
payload = {
payload: {
status: "failure",
failure_information: exception_array.flatten
}
}
return JSON.generate(payload)
end | ruby | def execute_action_command(command: nil)
command_return = @command_executor.execute(command: command, target_object: nil)
## probably need to just return Strings, or ready_for_next with object isn't String
return_object = command_return.return_value
return_value_type = command_return.return_value_type
closure_arg = command_return.closure_argument_value
return_object = return_value_processor.prepare_object(
return_value: return_object,
return_value_type: return_value_type
)
if closure_arg.nil?
closure_arg = closure_arg.to_s
else
closure_arg = return_value_processor.prepare_object(
return_value: closure_arg,
return_value_type: :string # always assume string for closure error_callback
)
end
Thread.current[:exception] = nil
payload = {
payload: {
status: "ready_for_next",
return_object: return_object,
closure_argument_value: closure_arg
}
}
return JSON.generate(payload)
rescue StandardError => e
Thread.current[:exception] = e
exception_array = []
exception_array << "#{e.class}:"
exception_array << e.backtrace
while e.respond_to?("cause") && (e = e.cause)
exception_array << "cause: #{e.class}"
exception_array << e.backtrace
end
payload = {
payload: {
status: "failure",
failure_information: exception_array.flatten
}
}
return JSON.generate(payload)
end | [
"def",
"execute_action_command",
"(",
"command",
":",
"nil",
")",
"command_return",
"=",
"@command_executor",
".",
"execute",
"(",
"command",
":",
"command",
",",
"target_object",
":",
"nil",
")",
"## probably need to just return Strings, or ready_for_next with object isn't String",
"return_object",
"=",
"command_return",
".",
"return_value",
"return_value_type",
"=",
"command_return",
".",
"return_value_type",
"closure_arg",
"=",
"command_return",
".",
"closure_argument_value",
"return_object",
"=",
"return_value_processor",
".",
"prepare_object",
"(",
"return_value",
":",
"return_object",
",",
"return_value_type",
":",
"return_value_type",
")",
"if",
"closure_arg",
".",
"nil?",
"closure_arg",
"=",
"closure_arg",
".",
"to_s",
"else",
"closure_arg",
"=",
"return_value_processor",
".",
"prepare_object",
"(",
"return_value",
":",
"closure_arg",
",",
"return_value_type",
":",
":string",
"# always assume string for closure error_callback",
")",
"end",
"Thread",
".",
"current",
"[",
":exception",
"]",
"=",
"nil",
"payload",
"=",
"{",
"payload",
":",
"{",
"status",
":",
"\"ready_for_next\"",
",",
"return_object",
":",
"return_object",
",",
"closure_argument_value",
":",
"closure_arg",
"}",
"}",
"return",
"JSON",
".",
"generate",
"(",
"payload",
")",
"rescue",
"StandardError",
"=>",
"e",
"Thread",
".",
"current",
"[",
":exception",
"]",
"=",
"e",
"exception_array",
"=",
"[",
"]",
"exception_array",
"<<",
"\"#{e.class}:\"",
"exception_array",
"<<",
"e",
".",
"backtrace",
"while",
"e",
".",
"respond_to?",
"(",
"\"cause\"",
")",
"&&",
"(",
"e",
"=",
"e",
".",
"cause",
")",
"exception_array",
"<<",
"\"cause: #{e.class}\"",
"exception_array",
"<<",
"e",
".",
"backtrace",
"end",
"payload",
"=",
"{",
"payload",
":",
"{",
"status",
":",
"\"failure\"",
",",
"failure_information",
":",
"exception_array",
".",
"flatten",
"}",
"}",
"return",
"JSON",
".",
"generate",
"(",
"payload",
")",
"end"
] | execute fastlane action command | [
"execute",
"fastlane",
"action",
"command"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane/lib/fastlane/server/socket_server.rb#L180-L230 | train |
fastlane/fastlane | fastlane_core/lib/fastlane_core/project.rb | FastlaneCore.Project.schemes | def schemes
@schemes ||= if workspace?
workspace.schemes.reject do |k, v|
v.include?("Pods/Pods.xcodeproj")
end.keys
else
Xcodeproj::Project.schemes(path)
end
end | ruby | def schemes
@schemes ||= if workspace?
workspace.schemes.reject do |k, v|
v.include?("Pods/Pods.xcodeproj")
end.keys
else
Xcodeproj::Project.schemes(path)
end
end | [
"def",
"schemes",
"@schemes",
"||=",
"if",
"workspace?",
"workspace",
".",
"schemes",
".",
"reject",
"do",
"|",
"k",
",",
"v",
"|",
"v",
".",
"include?",
"(",
"\"Pods/Pods.xcodeproj\"",
")",
"end",
".",
"keys",
"else",
"Xcodeproj",
"::",
"Project",
".",
"schemes",
"(",
"path",
")",
"end",
"end"
] | Get all available schemes in an array | [
"Get",
"all",
"available",
"schemes",
"in",
"an",
"array"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane_core/lib/fastlane_core/project.rb#L118-L126 | train |
fastlane/fastlane | fastlane_core/lib/fastlane_core/project.rb | FastlaneCore.Project.select_scheme | def select_scheme(preferred_to_include: nil)
if options[:scheme].to_s.length > 0
# Verify the scheme is available
unless schemes.include?(options[:scheme].to_s)
UI.error("Couldn't find specified scheme '#{options[:scheme]}'. Please make sure that the scheme is shared, see https://developer.apple.com/library/content/documentation/IDEs/Conceptual/xcode_guide-continuous_integration/ConfigureBots.html#//apple_ref/doc/uid/TP40013292-CH9-SW3")
options[:scheme] = nil
end
end
return if options[:scheme].to_s.length > 0
if schemes.count == 1
options[:scheme] = schemes.last
elsif schemes.count > 1
preferred = nil
if preferred_to_include
preferred = schemes.find_all { |a| a.downcase.include?(preferred_to_include.downcase) }
end
if preferred_to_include && preferred.count == 1
options[:scheme] = preferred.last
elsif automated_scheme_selection? && schemes.include?(project_name)
UI.important("Using scheme matching project name (#{project_name}).")
options[:scheme] = project_name
elsif Helper.ci?
UI.error("Multiple schemes found but you haven't specified one.")
UI.error("Since this is a CI, please pass one using the `scheme` option")
show_scheme_shared_information
UI.user_error!("Multiple schemes found")
else
puts("Select Scheme: ")
options[:scheme] = choose(*schemes)
end
else
show_scheme_shared_information
UI.user_error!("No Schemes found")
end
end | ruby | def select_scheme(preferred_to_include: nil)
if options[:scheme].to_s.length > 0
# Verify the scheme is available
unless schemes.include?(options[:scheme].to_s)
UI.error("Couldn't find specified scheme '#{options[:scheme]}'. Please make sure that the scheme is shared, see https://developer.apple.com/library/content/documentation/IDEs/Conceptual/xcode_guide-continuous_integration/ConfigureBots.html#//apple_ref/doc/uid/TP40013292-CH9-SW3")
options[:scheme] = nil
end
end
return if options[:scheme].to_s.length > 0
if schemes.count == 1
options[:scheme] = schemes.last
elsif schemes.count > 1
preferred = nil
if preferred_to_include
preferred = schemes.find_all { |a| a.downcase.include?(preferred_to_include.downcase) }
end
if preferred_to_include && preferred.count == 1
options[:scheme] = preferred.last
elsif automated_scheme_selection? && schemes.include?(project_name)
UI.important("Using scheme matching project name (#{project_name}).")
options[:scheme] = project_name
elsif Helper.ci?
UI.error("Multiple schemes found but you haven't specified one.")
UI.error("Since this is a CI, please pass one using the `scheme` option")
show_scheme_shared_information
UI.user_error!("Multiple schemes found")
else
puts("Select Scheme: ")
options[:scheme] = choose(*schemes)
end
else
show_scheme_shared_information
UI.user_error!("No Schemes found")
end
end | [
"def",
"select_scheme",
"(",
"preferred_to_include",
":",
"nil",
")",
"if",
"options",
"[",
":scheme",
"]",
".",
"to_s",
".",
"length",
">",
"0",
"# Verify the scheme is available",
"unless",
"schemes",
".",
"include?",
"(",
"options",
"[",
":scheme",
"]",
".",
"to_s",
")",
"UI",
".",
"error",
"(",
"\"Couldn't find specified scheme '#{options[:scheme]}'. Please make sure that the scheme is shared, see https://developer.apple.com/library/content/documentation/IDEs/Conceptual/xcode_guide-continuous_integration/ConfigureBots.html#//apple_ref/doc/uid/TP40013292-CH9-SW3\"",
")",
"options",
"[",
":scheme",
"]",
"=",
"nil",
"end",
"end",
"return",
"if",
"options",
"[",
":scheme",
"]",
".",
"to_s",
".",
"length",
">",
"0",
"if",
"schemes",
".",
"count",
"==",
"1",
"options",
"[",
":scheme",
"]",
"=",
"schemes",
".",
"last",
"elsif",
"schemes",
".",
"count",
">",
"1",
"preferred",
"=",
"nil",
"if",
"preferred_to_include",
"preferred",
"=",
"schemes",
".",
"find_all",
"{",
"|",
"a",
"|",
"a",
".",
"downcase",
".",
"include?",
"(",
"preferred_to_include",
".",
"downcase",
")",
"}",
"end",
"if",
"preferred_to_include",
"&&",
"preferred",
".",
"count",
"==",
"1",
"options",
"[",
":scheme",
"]",
"=",
"preferred",
".",
"last",
"elsif",
"automated_scheme_selection?",
"&&",
"schemes",
".",
"include?",
"(",
"project_name",
")",
"UI",
".",
"important",
"(",
"\"Using scheme matching project name (#{project_name}).\"",
")",
"options",
"[",
":scheme",
"]",
"=",
"project_name",
"elsif",
"Helper",
".",
"ci?",
"UI",
".",
"error",
"(",
"\"Multiple schemes found but you haven't specified one.\"",
")",
"UI",
".",
"error",
"(",
"\"Since this is a CI, please pass one using the `scheme` option\"",
")",
"show_scheme_shared_information",
"UI",
".",
"user_error!",
"(",
"\"Multiple schemes found\"",
")",
"else",
"puts",
"(",
"\"Select Scheme: \"",
")",
"options",
"[",
":scheme",
"]",
"=",
"choose",
"(",
"schemes",
")",
"end",
"else",
"show_scheme_shared_information",
"UI",
".",
"user_error!",
"(",
"\"No Schemes found\"",
")",
"end",
"end"
] | Let the user select a scheme
Use a scheme containing the preferred_to_include string when multiple schemes were found | [
"Let",
"the",
"user",
"select",
"a",
"scheme",
"Use",
"a",
"scheme",
"containing",
"the",
"preferred_to_include",
"string",
"when",
"multiple",
"schemes",
"were",
"found"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane_core/lib/fastlane_core/project.rb#L130-L168 | train |
fastlane/fastlane | fastlane_core/lib/fastlane_core/project.rb | FastlaneCore.Project.configurations | def configurations
@configurations ||= if workspace?
workspace
.file_references
.map(&:path)
.reject { |p| p.include?("Pods/Pods.xcodeproj") }
.map do |p|
# To maintain backwards compatibility, we
# silently ignore non-existent projects from
# workspaces.
begin
Xcodeproj::Project.open(p).build_configurations
rescue
[]
end
end
.flatten
.compact
.map(&:name)
else
project.build_configurations.map(&:name)
end
end | ruby | def configurations
@configurations ||= if workspace?
workspace
.file_references
.map(&:path)
.reject { |p| p.include?("Pods/Pods.xcodeproj") }
.map do |p|
# To maintain backwards compatibility, we
# silently ignore non-existent projects from
# workspaces.
begin
Xcodeproj::Project.open(p).build_configurations
rescue
[]
end
end
.flatten
.compact
.map(&:name)
else
project.build_configurations.map(&:name)
end
end | [
"def",
"configurations",
"@configurations",
"||=",
"if",
"workspace?",
"workspace",
".",
"file_references",
".",
"map",
"(",
":path",
")",
".",
"reject",
"{",
"|",
"p",
"|",
"p",
".",
"include?",
"(",
"\"Pods/Pods.xcodeproj\"",
")",
"}",
".",
"map",
"do",
"|",
"p",
"|",
"# To maintain backwards compatibility, we",
"# silently ignore non-existent projects from",
"# workspaces.",
"begin",
"Xcodeproj",
"::",
"Project",
".",
"open",
"(",
"p",
")",
".",
"build_configurations",
"rescue",
"[",
"]",
"end",
"end",
".",
"flatten",
".",
"compact",
".",
"map",
"(",
":name",
")",
"else",
"project",
".",
"build_configurations",
".",
"map",
"(",
":name",
")",
"end",
"end"
] | Get all available configurations in an array | [
"Get",
"all",
"available",
"configurations",
"in",
"an",
"array"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane_core/lib/fastlane_core/project.rb#L177-L199 | train |
fastlane/fastlane | fastlane_core/lib/fastlane_core/project.rb | FastlaneCore.Project.default_build_settings | def default_build_settings(key: nil, optional: true)
options[:scheme] ||= schemes.first if is_workspace
build_settings(key: key, optional: optional)
end | ruby | def default_build_settings(key: nil, optional: true)
options[:scheme] ||= schemes.first if is_workspace
build_settings(key: key, optional: optional)
end | [
"def",
"default_build_settings",
"(",
"key",
":",
"nil",
",",
"optional",
":",
"true",
")",
"options",
"[",
":scheme",
"]",
"||=",
"schemes",
".",
"first",
"if",
"is_workspace",
"build_settings",
"(",
"key",
":",
"key",
",",
"optional",
":",
"optional",
")",
"end"
] | Returns the build settings and sets the default scheme to the options hash | [
"Returns",
"the",
"build",
"settings",
"and",
"sets",
"the",
"default",
"scheme",
"to",
"the",
"options",
"hash"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane_core/lib/fastlane_core/project.rb#L385-L388 | train |
fastlane/fastlane | match/lib/match/nuke.rb | Match.Nuke.print_tables | def print_tables
puts("")
if self.certs.count > 0
rows = self.certs.collect do |cert|
cert_expiration = cert.expires.nil? ? "Unknown" : cert.expires.strftime("%Y-%m-%d")
[cert.name, cert.id, cert.class.to_s.split("::").last, cert_expiration]
end
puts(Terminal::Table.new({
title: "Certificates that are going to be revoked".green,
headings: ["Name", "ID", "Type", "Expires"],
rows: FastlaneCore::PrintTable.transform_output(rows)
}))
puts("")
end
if self.profiles.count > 0
rows = self.profiles.collect do |p|
status = p.status == 'Active' ? p.status.green : p.status.red
# Expires is somtimes nil
expires = p.expires ? p.expires.strftime("%Y-%m-%d") : nil
[p.name, p.id, status, p.type, expires]
end
puts(Terminal::Table.new({
title: "Provisioning Profiles that are going to be revoked".green,
headings: ["Name", "ID", "Status", "Type", "Expires"],
rows: FastlaneCore::PrintTable.transform_output(rows)
}))
puts("")
end
if self.files.count > 0
rows = self.files.collect do |f|
components = f.split(File::SEPARATOR)[-3..-1]
# from "...1o7xtmh/certs/distribution/8K38XUY3AY.cer" to "distribution cert"
file_type = components[0..1].reverse.join(" ")[0..-2]
[file_type, components[2]]
end
puts(Terminal::Table.new({
title: "Files that are going to be deleted".green + "\n" + self.storage.human_readable_description,
headings: ["Type", "File Name"],
rows: rows
}))
puts("")
end
end | ruby | def print_tables
puts("")
if self.certs.count > 0
rows = self.certs.collect do |cert|
cert_expiration = cert.expires.nil? ? "Unknown" : cert.expires.strftime("%Y-%m-%d")
[cert.name, cert.id, cert.class.to_s.split("::").last, cert_expiration]
end
puts(Terminal::Table.new({
title: "Certificates that are going to be revoked".green,
headings: ["Name", "ID", "Type", "Expires"],
rows: FastlaneCore::PrintTable.transform_output(rows)
}))
puts("")
end
if self.profiles.count > 0
rows = self.profiles.collect do |p|
status = p.status == 'Active' ? p.status.green : p.status.red
# Expires is somtimes nil
expires = p.expires ? p.expires.strftime("%Y-%m-%d") : nil
[p.name, p.id, status, p.type, expires]
end
puts(Terminal::Table.new({
title: "Provisioning Profiles that are going to be revoked".green,
headings: ["Name", "ID", "Status", "Type", "Expires"],
rows: FastlaneCore::PrintTable.transform_output(rows)
}))
puts("")
end
if self.files.count > 0
rows = self.files.collect do |f|
components = f.split(File::SEPARATOR)[-3..-1]
# from "...1o7xtmh/certs/distribution/8K38XUY3AY.cer" to "distribution cert"
file_type = components[0..1].reverse.join(" ")[0..-2]
[file_type, components[2]]
end
puts(Terminal::Table.new({
title: "Files that are going to be deleted".green + "\n" + self.storage.human_readable_description,
headings: ["Type", "File Name"],
rows: rows
}))
puts("")
end
end | [
"def",
"print_tables",
"puts",
"(",
"\"\"",
")",
"if",
"self",
".",
"certs",
".",
"count",
">",
"0",
"rows",
"=",
"self",
".",
"certs",
".",
"collect",
"do",
"|",
"cert",
"|",
"cert_expiration",
"=",
"cert",
".",
"expires",
".",
"nil?",
"?",
"\"Unknown\"",
":",
"cert",
".",
"expires",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
"[",
"cert",
".",
"name",
",",
"cert",
".",
"id",
",",
"cert",
".",
"class",
".",
"to_s",
".",
"split",
"(",
"\"::\"",
")",
".",
"last",
",",
"cert_expiration",
"]",
"end",
"puts",
"(",
"Terminal",
"::",
"Table",
".",
"new",
"(",
"{",
"title",
":",
"\"Certificates that are going to be revoked\"",
".",
"green",
",",
"headings",
":",
"[",
"\"Name\"",
",",
"\"ID\"",
",",
"\"Type\"",
",",
"\"Expires\"",
"]",
",",
"rows",
":",
"FastlaneCore",
"::",
"PrintTable",
".",
"transform_output",
"(",
"rows",
")",
"}",
")",
")",
"puts",
"(",
"\"\"",
")",
"end",
"if",
"self",
".",
"profiles",
".",
"count",
">",
"0",
"rows",
"=",
"self",
".",
"profiles",
".",
"collect",
"do",
"|",
"p",
"|",
"status",
"=",
"p",
".",
"status",
"==",
"'Active'",
"?",
"p",
".",
"status",
".",
"green",
":",
"p",
".",
"status",
".",
"red",
"# Expires is somtimes nil",
"expires",
"=",
"p",
".",
"expires",
"?",
"p",
".",
"expires",
".",
"strftime",
"(",
"\"%Y-%m-%d\"",
")",
":",
"nil",
"[",
"p",
".",
"name",
",",
"p",
".",
"id",
",",
"status",
",",
"p",
".",
"type",
",",
"expires",
"]",
"end",
"puts",
"(",
"Terminal",
"::",
"Table",
".",
"new",
"(",
"{",
"title",
":",
"\"Provisioning Profiles that are going to be revoked\"",
".",
"green",
",",
"headings",
":",
"[",
"\"Name\"",
",",
"\"ID\"",
",",
"\"Status\"",
",",
"\"Type\"",
",",
"\"Expires\"",
"]",
",",
"rows",
":",
"FastlaneCore",
"::",
"PrintTable",
".",
"transform_output",
"(",
"rows",
")",
"}",
")",
")",
"puts",
"(",
"\"\"",
")",
"end",
"if",
"self",
".",
"files",
".",
"count",
">",
"0",
"rows",
"=",
"self",
".",
"files",
".",
"collect",
"do",
"|",
"f",
"|",
"components",
"=",
"f",
".",
"split",
"(",
"File",
"::",
"SEPARATOR",
")",
"[",
"-",
"3",
"..",
"-",
"1",
"]",
"# from \"...1o7xtmh/certs/distribution/8K38XUY3AY.cer\" to \"distribution cert\"",
"file_type",
"=",
"components",
"[",
"0",
"..",
"1",
"]",
".",
"reverse",
".",
"join",
"(",
"\" \"",
")",
"[",
"0",
"..",
"-",
"2",
"]",
"[",
"file_type",
",",
"components",
"[",
"2",
"]",
"]",
"end",
"puts",
"(",
"Terminal",
"::",
"Table",
".",
"new",
"(",
"{",
"title",
":",
"\"Files that are going to be deleted\"",
".",
"green",
"+",
"\"\\n\"",
"+",
"self",
".",
"storage",
".",
"human_readable_description",
",",
"headings",
":",
"[",
"\"Type\"",
",",
"\"File Name\"",
"]",
",",
"rows",
":",
"rows",
"}",
")",
")",
"puts",
"(",
"\"\"",
")",
"end",
"end"
] | Print tables to ask the user | [
"Print",
"tables",
"to",
"ask",
"the",
"user"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/match/lib/match/nuke.rb#L132-L180 | train |
fastlane/fastlane | deliver/lib/deliver/upload_metadata.rb | Deliver.UploadMetadata.upload | def upload(options)
return if options[:skip_metadata]
# it is not possible to create new languages, because
# :keywords is not write-able on published versions
# therefore skip it.
verify_available_languages!(options) unless options[:edit_live]
app = options[:app]
details = app.details
if options[:edit_live]
# not all values are editable when using live_version
v = app.live_version(platform: options[:platform])
localised_options = LOCALISED_LIVE_VALUES
non_localised_options = NON_LOCALISED_LIVE_VALUES
if v.nil?
UI.message("Couldn't find live version, editing the current version on App Store Connect instead")
v = app.edit_version(platform: options[:platform])
# we don't want to update the localised_options and non_localised_options
# as we also check for `options[:edit_live]` at other areas in the code
# by not touching those 2 variables, deliver is more consistent with what the option says
# in the documentation
end
else
v = app.edit_version(platform: options[:platform])
localised_options = (LOCALISED_VERSION_VALUES + LOCALISED_APP_VALUES)
non_localised_options = (NON_LOCALISED_VERSION_VALUES + NON_LOCALISED_APP_VALUES)
end
individual = options[:individual_metadata_items] || []
localised_options.each do |key|
current = options[key]
next unless current
unless current.kind_of?(Hash)
UI.error("Error with provided '#{key}'. Must be a hash, the key being the language.")
next
end
current.each do |language, value|
next unless value.to_s.length > 0
strip_value = value.to_s.strip
if individual.include?(key.to_s)
upload_individual_item(app, v, language, key, strip_value)
else
v.send(key)[language] = strip_value if LOCALISED_VERSION_VALUES.include?(key)
details.send(key)[language] = strip_value if LOCALISED_APP_VALUES.include?(key)
end
end
end
non_localised_options.each do |key|
current = options[key].to_s.strip
next unless current.to_s.length > 0
v.send("#{key}=", current) if NON_LOCALISED_VERSION_VALUES.include?(key)
details.send("#{key}=", current) if NON_LOCALISED_APP_VALUES.include?(key)
end
v.release_on_approval = options[:automatic_release]
v.auto_release_date = options[:auto_release_date] unless options[:auto_release_date].nil?
v.toggle_phased_release(enabled: !!options[:phased_release]) unless options[:phased_release].nil?
set_trade_representative_contact_information(v, options)
set_review_information(v, options)
set_app_rating(v, options)
v.ratings_reset = options[:reset_ratings] unless options[:reset_ratings].nil?
Helper.show_loading_indicator("Uploading metadata to App Store Connect")
v.save!
Helper.hide_loading_indicator
begin
details.save!
UI.success("Successfully uploaded set of metadata to App Store Connect")
rescue Spaceship::TunesClient::ITunesConnectError => e
# This makes sure that we log invalid app names as user errors
# If another string needs to be checked here we should
# figure out a more generic way to handle these cases.
if e.message.include?('App Name cannot be longer than 50 characters') || e.message.include?('The app name you entered is already being used')
UI.error("Error in app name. Try using 'individual_metadata_items' to identify the problem language.")
UI.user_error!(e.message)
else
raise e
end
end
end | ruby | def upload(options)
return if options[:skip_metadata]
# it is not possible to create new languages, because
# :keywords is not write-able on published versions
# therefore skip it.
verify_available_languages!(options) unless options[:edit_live]
app = options[:app]
details = app.details
if options[:edit_live]
# not all values are editable when using live_version
v = app.live_version(platform: options[:platform])
localised_options = LOCALISED_LIVE_VALUES
non_localised_options = NON_LOCALISED_LIVE_VALUES
if v.nil?
UI.message("Couldn't find live version, editing the current version on App Store Connect instead")
v = app.edit_version(platform: options[:platform])
# we don't want to update the localised_options and non_localised_options
# as we also check for `options[:edit_live]` at other areas in the code
# by not touching those 2 variables, deliver is more consistent with what the option says
# in the documentation
end
else
v = app.edit_version(platform: options[:platform])
localised_options = (LOCALISED_VERSION_VALUES + LOCALISED_APP_VALUES)
non_localised_options = (NON_LOCALISED_VERSION_VALUES + NON_LOCALISED_APP_VALUES)
end
individual = options[:individual_metadata_items] || []
localised_options.each do |key|
current = options[key]
next unless current
unless current.kind_of?(Hash)
UI.error("Error with provided '#{key}'. Must be a hash, the key being the language.")
next
end
current.each do |language, value|
next unless value.to_s.length > 0
strip_value = value.to_s.strip
if individual.include?(key.to_s)
upload_individual_item(app, v, language, key, strip_value)
else
v.send(key)[language] = strip_value if LOCALISED_VERSION_VALUES.include?(key)
details.send(key)[language] = strip_value if LOCALISED_APP_VALUES.include?(key)
end
end
end
non_localised_options.each do |key|
current = options[key].to_s.strip
next unless current.to_s.length > 0
v.send("#{key}=", current) if NON_LOCALISED_VERSION_VALUES.include?(key)
details.send("#{key}=", current) if NON_LOCALISED_APP_VALUES.include?(key)
end
v.release_on_approval = options[:automatic_release]
v.auto_release_date = options[:auto_release_date] unless options[:auto_release_date].nil?
v.toggle_phased_release(enabled: !!options[:phased_release]) unless options[:phased_release].nil?
set_trade_representative_contact_information(v, options)
set_review_information(v, options)
set_app_rating(v, options)
v.ratings_reset = options[:reset_ratings] unless options[:reset_ratings].nil?
Helper.show_loading_indicator("Uploading metadata to App Store Connect")
v.save!
Helper.hide_loading_indicator
begin
details.save!
UI.success("Successfully uploaded set of metadata to App Store Connect")
rescue Spaceship::TunesClient::ITunesConnectError => e
# This makes sure that we log invalid app names as user errors
# If another string needs to be checked here we should
# figure out a more generic way to handle these cases.
if e.message.include?('App Name cannot be longer than 50 characters') || e.message.include?('The app name you entered is already being used')
UI.error("Error in app name. Try using 'individual_metadata_items' to identify the problem language.")
UI.user_error!(e.message)
else
raise e
end
end
end | [
"def",
"upload",
"(",
"options",
")",
"return",
"if",
"options",
"[",
":skip_metadata",
"]",
"# it is not possible to create new languages, because",
"# :keywords is not write-able on published versions",
"# therefore skip it.",
"verify_available_languages!",
"(",
"options",
")",
"unless",
"options",
"[",
":edit_live",
"]",
"app",
"=",
"options",
"[",
":app",
"]",
"details",
"=",
"app",
".",
"details",
"if",
"options",
"[",
":edit_live",
"]",
"# not all values are editable when using live_version",
"v",
"=",
"app",
".",
"live_version",
"(",
"platform",
":",
"options",
"[",
":platform",
"]",
")",
"localised_options",
"=",
"LOCALISED_LIVE_VALUES",
"non_localised_options",
"=",
"NON_LOCALISED_LIVE_VALUES",
"if",
"v",
".",
"nil?",
"UI",
".",
"message",
"(",
"\"Couldn't find live version, editing the current version on App Store Connect instead\"",
")",
"v",
"=",
"app",
".",
"edit_version",
"(",
"platform",
":",
"options",
"[",
":platform",
"]",
")",
"# we don't want to update the localised_options and non_localised_options",
"# as we also check for `options[:edit_live]` at other areas in the code",
"# by not touching those 2 variables, deliver is more consistent with what the option says",
"# in the documentation",
"end",
"else",
"v",
"=",
"app",
".",
"edit_version",
"(",
"platform",
":",
"options",
"[",
":platform",
"]",
")",
"localised_options",
"=",
"(",
"LOCALISED_VERSION_VALUES",
"+",
"LOCALISED_APP_VALUES",
")",
"non_localised_options",
"=",
"(",
"NON_LOCALISED_VERSION_VALUES",
"+",
"NON_LOCALISED_APP_VALUES",
")",
"end",
"individual",
"=",
"options",
"[",
":individual_metadata_items",
"]",
"||",
"[",
"]",
"localised_options",
".",
"each",
"do",
"|",
"key",
"|",
"current",
"=",
"options",
"[",
"key",
"]",
"next",
"unless",
"current",
"unless",
"current",
".",
"kind_of?",
"(",
"Hash",
")",
"UI",
".",
"error",
"(",
"\"Error with provided '#{key}'. Must be a hash, the key being the language.\"",
")",
"next",
"end",
"current",
".",
"each",
"do",
"|",
"language",
",",
"value",
"|",
"next",
"unless",
"value",
".",
"to_s",
".",
"length",
">",
"0",
"strip_value",
"=",
"value",
".",
"to_s",
".",
"strip",
"if",
"individual",
".",
"include?",
"(",
"key",
".",
"to_s",
")",
"upload_individual_item",
"(",
"app",
",",
"v",
",",
"language",
",",
"key",
",",
"strip_value",
")",
"else",
"v",
".",
"send",
"(",
"key",
")",
"[",
"language",
"]",
"=",
"strip_value",
"if",
"LOCALISED_VERSION_VALUES",
".",
"include?",
"(",
"key",
")",
"details",
".",
"send",
"(",
"key",
")",
"[",
"language",
"]",
"=",
"strip_value",
"if",
"LOCALISED_APP_VALUES",
".",
"include?",
"(",
"key",
")",
"end",
"end",
"end",
"non_localised_options",
".",
"each",
"do",
"|",
"key",
"|",
"current",
"=",
"options",
"[",
"key",
"]",
".",
"to_s",
".",
"strip",
"next",
"unless",
"current",
".",
"to_s",
".",
"length",
">",
"0",
"v",
".",
"send",
"(",
"\"#{key}=\"",
",",
"current",
")",
"if",
"NON_LOCALISED_VERSION_VALUES",
".",
"include?",
"(",
"key",
")",
"details",
".",
"send",
"(",
"\"#{key}=\"",
",",
"current",
")",
"if",
"NON_LOCALISED_APP_VALUES",
".",
"include?",
"(",
"key",
")",
"end",
"v",
".",
"release_on_approval",
"=",
"options",
"[",
":automatic_release",
"]",
"v",
".",
"auto_release_date",
"=",
"options",
"[",
":auto_release_date",
"]",
"unless",
"options",
"[",
":auto_release_date",
"]",
".",
"nil?",
"v",
".",
"toggle_phased_release",
"(",
"enabled",
":",
"!",
"!",
"options",
"[",
":phased_release",
"]",
")",
"unless",
"options",
"[",
":phased_release",
"]",
".",
"nil?",
"set_trade_representative_contact_information",
"(",
"v",
",",
"options",
")",
"set_review_information",
"(",
"v",
",",
"options",
")",
"set_app_rating",
"(",
"v",
",",
"options",
")",
"v",
".",
"ratings_reset",
"=",
"options",
"[",
":reset_ratings",
"]",
"unless",
"options",
"[",
":reset_ratings",
"]",
".",
"nil?",
"Helper",
".",
"show_loading_indicator",
"(",
"\"Uploading metadata to App Store Connect\"",
")",
"v",
".",
"save!",
"Helper",
".",
"hide_loading_indicator",
"begin",
"details",
".",
"save!",
"UI",
".",
"success",
"(",
"\"Successfully uploaded set of metadata to App Store Connect\"",
")",
"rescue",
"Spaceship",
"::",
"TunesClient",
"::",
"ITunesConnectError",
"=>",
"e",
"# This makes sure that we log invalid app names as user errors",
"# If another string needs to be checked here we should",
"# figure out a more generic way to handle these cases.",
"if",
"e",
".",
"message",
".",
"include?",
"(",
"'App Name cannot be longer than 50 characters'",
")",
"||",
"e",
".",
"message",
".",
"include?",
"(",
"'The app name you entered is already being used'",
")",
"UI",
".",
"error",
"(",
"\"Error in app name. Try using 'individual_metadata_items' to identify the problem language.\"",
")",
"UI",
".",
"user_error!",
"(",
"e",
".",
"message",
")",
"else",
"raise",
"e",
"end",
"end",
"end"
] | Make sure to call `load_from_filesystem` before calling upload | [
"Make",
"sure",
"to",
"call",
"load_from_filesystem",
"before",
"calling",
"upload"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/deliver/lib/deliver/upload_metadata.rb#L67-L152 | train |
fastlane/fastlane | deliver/lib/deliver/upload_metadata.rb | Deliver.UploadMetadata.upload_individual_item | def upload_individual_item(app, version, language, key, value)
details = app.details
version.send(key)[language] = value if LOCALISED_VERSION_VALUES.include?(key)
details.send(key)[language] = value if LOCALISED_APP_VALUES.include?(key)
Helper.show_loading_indicator("Uploading #{language} #{key} to App Store Connect")
version.save!
Helper.hide_loading_indicator
begin
details.save!
UI.success("Successfully uploaded #{language} #{key} to App Store Connect")
rescue Spaceship::TunesClient::ITunesConnectError => e
UI.error("Error in #{language} #{key}: \n#{value}")
UI.error(e.message) # Don't use user_error to allow all values to get checked
end
end | ruby | def upload_individual_item(app, version, language, key, value)
details = app.details
version.send(key)[language] = value if LOCALISED_VERSION_VALUES.include?(key)
details.send(key)[language] = value if LOCALISED_APP_VALUES.include?(key)
Helper.show_loading_indicator("Uploading #{language} #{key} to App Store Connect")
version.save!
Helper.hide_loading_indicator
begin
details.save!
UI.success("Successfully uploaded #{language} #{key} to App Store Connect")
rescue Spaceship::TunesClient::ITunesConnectError => e
UI.error("Error in #{language} #{key}: \n#{value}")
UI.error(e.message) # Don't use user_error to allow all values to get checked
end
end | [
"def",
"upload_individual_item",
"(",
"app",
",",
"version",
",",
"language",
",",
"key",
",",
"value",
")",
"details",
"=",
"app",
".",
"details",
"version",
".",
"send",
"(",
"key",
")",
"[",
"language",
"]",
"=",
"value",
"if",
"LOCALISED_VERSION_VALUES",
".",
"include?",
"(",
"key",
")",
"details",
".",
"send",
"(",
"key",
")",
"[",
"language",
"]",
"=",
"value",
"if",
"LOCALISED_APP_VALUES",
".",
"include?",
"(",
"key",
")",
"Helper",
".",
"show_loading_indicator",
"(",
"\"Uploading #{language} #{key} to App Store Connect\"",
")",
"version",
".",
"save!",
"Helper",
".",
"hide_loading_indicator",
"begin",
"details",
".",
"save!",
"UI",
".",
"success",
"(",
"\"Successfully uploaded #{language} #{key} to App Store Connect\"",
")",
"rescue",
"Spaceship",
"::",
"TunesClient",
"::",
"ITunesConnectError",
"=>",
"e",
"UI",
".",
"error",
"(",
"\"Error in #{language} #{key}: \\n#{value}\"",
")",
"UI",
".",
"error",
"(",
"e",
".",
"message",
")",
"# Don't use user_error to allow all values to get checked",
"end",
"end"
] | Uploads metadata individually by language to help identify exactly which items have issues | [
"Uploads",
"metadata",
"individually",
"by",
"language",
"to",
"help",
"identify",
"exactly",
"which",
"items",
"have",
"issues"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/deliver/lib/deliver/upload_metadata.rb#L155-L169 | train |
fastlane/fastlane | deliver/lib/deliver/upload_metadata.rb | Deliver.UploadMetadata.verify_available_languages! | def verify_available_languages!(options)
return if options[:skip_metadata]
# Collect all languages we need
# We only care about languages from user provided values
# as the other languages are on iTC already anyway
v = options[:app].edit_version(platform: options[:platform])
UI.user_error!("Could not find a version to edit for app '#{options[:app].name}', the app metadata is read-only currently") unless v
enabled_languages = options[:languages] || []
LOCALISED_VERSION_VALUES.each do |key|
current = options[key]
next unless current && current.kind_of?(Hash)
current.each do |language, value|
language = language.to_s
enabled_languages << language unless enabled_languages.include?(language)
end
end
# Reject "default" language from getting enabled
# because "default" is not an iTC language
enabled_languages = enabled_languages.reject do |lang|
lang == "default"
end.uniq
if enabled_languages.count > 0
v.create_languages(enabled_languages)
lng_text = "language"
lng_text += "s" if enabled_languages.count != 1
Helper.show_loading_indicator("Activating #{lng_text} #{enabled_languages.join(', ')}...")
v.save!
Helper.hide_loading_indicator
end
true
end | ruby | def verify_available_languages!(options)
return if options[:skip_metadata]
# Collect all languages we need
# We only care about languages from user provided values
# as the other languages are on iTC already anyway
v = options[:app].edit_version(platform: options[:platform])
UI.user_error!("Could not find a version to edit for app '#{options[:app].name}', the app metadata is read-only currently") unless v
enabled_languages = options[:languages] || []
LOCALISED_VERSION_VALUES.each do |key|
current = options[key]
next unless current && current.kind_of?(Hash)
current.each do |language, value|
language = language.to_s
enabled_languages << language unless enabled_languages.include?(language)
end
end
# Reject "default" language from getting enabled
# because "default" is not an iTC language
enabled_languages = enabled_languages.reject do |lang|
lang == "default"
end.uniq
if enabled_languages.count > 0
v.create_languages(enabled_languages)
lng_text = "language"
lng_text += "s" if enabled_languages.count != 1
Helper.show_loading_indicator("Activating #{lng_text} #{enabled_languages.join(', ')}...")
v.save!
Helper.hide_loading_indicator
end
true
end | [
"def",
"verify_available_languages!",
"(",
"options",
")",
"return",
"if",
"options",
"[",
":skip_metadata",
"]",
"# Collect all languages we need",
"# We only care about languages from user provided values",
"# as the other languages are on iTC already anyway",
"v",
"=",
"options",
"[",
":app",
"]",
".",
"edit_version",
"(",
"platform",
":",
"options",
"[",
":platform",
"]",
")",
"UI",
".",
"user_error!",
"(",
"\"Could not find a version to edit for app '#{options[:app].name}', the app metadata is read-only currently\"",
")",
"unless",
"v",
"enabled_languages",
"=",
"options",
"[",
":languages",
"]",
"||",
"[",
"]",
"LOCALISED_VERSION_VALUES",
".",
"each",
"do",
"|",
"key",
"|",
"current",
"=",
"options",
"[",
"key",
"]",
"next",
"unless",
"current",
"&&",
"current",
".",
"kind_of?",
"(",
"Hash",
")",
"current",
".",
"each",
"do",
"|",
"language",
",",
"value",
"|",
"language",
"=",
"language",
".",
"to_s",
"enabled_languages",
"<<",
"language",
"unless",
"enabled_languages",
".",
"include?",
"(",
"language",
")",
"end",
"end",
"# Reject \"default\" language from getting enabled",
"# because \"default\" is not an iTC language",
"enabled_languages",
"=",
"enabled_languages",
".",
"reject",
"do",
"|",
"lang",
"|",
"lang",
"==",
"\"default\"",
"end",
".",
"uniq",
"if",
"enabled_languages",
".",
"count",
">",
"0",
"v",
".",
"create_languages",
"(",
"enabled_languages",
")",
"lng_text",
"=",
"\"language\"",
"lng_text",
"+=",
"\"s\"",
"if",
"enabled_languages",
".",
"count",
"!=",
"1",
"Helper",
".",
"show_loading_indicator",
"(",
"\"Activating #{lng_text} #{enabled_languages.join(', ')}...\"",
")",
"v",
".",
"save!",
"Helper",
".",
"hide_loading_indicator",
"end",
"true",
"end"
] | Makes sure all languages we need are actually created | [
"Makes",
"sure",
"all",
"languages",
"we",
"need",
"are",
"actually",
"created"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/deliver/lib/deliver/upload_metadata.rb#L247-L281 | train |
fastlane/fastlane | deliver/lib/deliver/upload_metadata.rb | Deliver.UploadMetadata.load_from_filesystem | def load_from_filesystem(options)
return if options[:skip_metadata]
# Load localised data
ignore_validation = options[:ignore_language_directory_validation]
Loader.language_folders(options[:metadata_path], ignore_validation).each do |lang_folder|
language = File.basename(lang_folder)
(LOCALISED_VERSION_VALUES + LOCALISED_APP_VALUES).each do |key|
path = File.join(lang_folder, "#{key}.txt")
next unless File.exist?(path)
UI.message("Loading '#{path}'...")
options[key] ||= {}
options[key][language] ||= File.read(path)
end
end
# Load non localised data
(NON_LOCALISED_VERSION_VALUES + NON_LOCALISED_APP_VALUES).each do |key|
path = File.join(options[:metadata_path], "#{key}.txt")
next unless File.exist?(path)
UI.message("Loading '#{path}'...")
options[key] ||= File.read(path)
end
# Load trade representative contact information
options[:trade_representative_contact_information] ||= {}
TRADE_REPRESENTATIVE_CONTACT_INFORMATION_VALUES.values.each do |option_name|
path = File.join(options[:metadata_path], TRADE_REPRESENTATIVE_CONTACT_INFORMATION_DIR, "#{option_name}.txt")
next unless File.exist?(path)
next if options[:trade_representative_contact_information][option_name].to_s.length > 0
UI.message("Loading '#{path}'...")
options[:trade_representative_contact_information][option_name] ||= File.read(path)
end
# Load review information
options[:app_review_information] ||= {}
REVIEW_INFORMATION_VALUES.values.each do |option_name|
path = File.join(options[:metadata_path], REVIEW_INFORMATION_DIR, "#{option_name}.txt")
next unless File.exist?(path)
next if options[:app_review_information][option_name].to_s.length > 0
UI.message("Loading '#{path}'...")
options[:app_review_information][option_name] ||= File.read(path)
end
end | ruby | def load_from_filesystem(options)
return if options[:skip_metadata]
# Load localised data
ignore_validation = options[:ignore_language_directory_validation]
Loader.language_folders(options[:metadata_path], ignore_validation).each do |lang_folder|
language = File.basename(lang_folder)
(LOCALISED_VERSION_VALUES + LOCALISED_APP_VALUES).each do |key|
path = File.join(lang_folder, "#{key}.txt")
next unless File.exist?(path)
UI.message("Loading '#{path}'...")
options[key] ||= {}
options[key][language] ||= File.read(path)
end
end
# Load non localised data
(NON_LOCALISED_VERSION_VALUES + NON_LOCALISED_APP_VALUES).each do |key|
path = File.join(options[:metadata_path], "#{key}.txt")
next unless File.exist?(path)
UI.message("Loading '#{path}'...")
options[key] ||= File.read(path)
end
# Load trade representative contact information
options[:trade_representative_contact_information] ||= {}
TRADE_REPRESENTATIVE_CONTACT_INFORMATION_VALUES.values.each do |option_name|
path = File.join(options[:metadata_path], TRADE_REPRESENTATIVE_CONTACT_INFORMATION_DIR, "#{option_name}.txt")
next unless File.exist?(path)
next if options[:trade_representative_contact_information][option_name].to_s.length > 0
UI.message("Loading '#{path}'...")
options[:trade_representative_contact_information][option_name] ||= File.read(path)
end
# Load review information
options[:app_review_information] ||= {}
REVIEW_INFORMATION_VALUES.values.each do |option_name|
path = File.join(options[:metadata_path], REVIEW_INFORMATION_DIR, "#{option_name}.txt")
next unless File.exist?(path)
next if options[:app_review_information][option_name].to_s.length > 0
UI.message("Loading '#{path}'...")
options[:app_review_information][option_name] ||= File.read(path)
end
end | [
"def",
"load_from_filesystem",
"(",
"options",
")",
"return",
"if",
"options",
"[",
":skip_metadata",
"]",
"# Load localised data",
"ignore_validation",
"=",
"options",
"[",
":ignore_language_directory_validation",
"]",
"Loader",
".",
"language_folders",
"(",
"options",
"[",
":metadata_path",
"]",
",",
"ignore_validation",
")",
".",
"each",
"do",
"|",
"lang_folder",
"|",
"language",
"=",
"File",
".",
"basename",
"(",
"lang_folder",
")",
"(",
"LOCALISED_VERSION_VALUES",
"+",
"LOCALISED_APP_VALUES",
")",
".",
"each",
"do",
"|",
"key",
"|",
"path",
"=",
"File",
".",
"join",
"(",
"lang_folder",
",",
"\"#{key}.txt\"",
")",
"next",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"UI",
".",
"message",
"(",
"\"Loading '#{path}'...\"",
")",
"options",
"[",
"key",
"]",
"||=",
"{",
"}",
"options",
"[",
"key",
"]",
"[",
"language",
"]",
"||=",
"File",
".",
"read",
"(",
"path",
")",
"end",
"end",
"# Load non localised data",
"(",
"NON_LOCALISED_VERSION_VALUES",
"+",
"NON_LOCALISED_APP_VALUES",
")",
".",
"each",
"do",
"|",
"key",
"|",
"path",
"=",
"File",
".",
"join",
"(",
"options",
"[",
":metadata_path",
"]",
",",
"\"#{key}.txt\"",
")",
"next",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"UI",
".",
"message",
"(",
"\"Loading '#{path}'...\"",
")",
"options",
"[",
"key",
"]",
"||=",
"File",
".",
"read",
"(",
"path",
")",
"end",
"# Load trade representative contact information",
"options",
"[",
":trade_representative_contact_information",
"]",
"||=",
"{",
"}",
"TRADE_REPRESENTATIVE_CONTACT_INFORMATION_VALUES",
".",
"values",
".",
"each",
"do",
"|",
"option_name",
"|",
"path",
"=",
"File",
".",
"join",
"(",
"options",
"[",
":metadata_path",
"]",
",",
"TRADE_REPRESENTATIVE_CONTACT_INFORMATION_DIR",
",",
"\"#{option_name}.txt\"",
")",
"next",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"next",
"if",
"options",
"[",
":trade_representative_contact_information",
"]",
"[",
"option_name",
"]",
".",
"to_s",
".",
"length",
">",
"0",
"UI",
".",
"message",
"(",
"\"Loading '#{path}'...\"",
")",
"options",
"[",
":trade_representative_contact_information",
"]",
"[",
"option_name",
"]",
"||=",
"File",
".",
"read",
"(",
"path",
")",
"end",
"# Load review information",
"options",
"[",
":app_review_information",
"]",
"||=",
"{",
"}",
"REVIEW_INFORMATION_VALUES",
".",
"values",
".",
"each",
"do",
"|",
"option_name",
"|",
"path",
"=",
"File",
".",
"join",
"(",
"options",
"[",
":metadata_path",
"]",
",",
"REVIEW_INFORMATION_DIR",
",",
"\"#{option_name}.txt\"",
")",
"next",
"unless",
"File",
".",
"exist?",
"(",
"path",
")",
"next",
"if",
"options",
"[",
":app_review_information",
"]",
"[",
"option_name",
"]",
".",
"to_s",
".",
"length",
">",
"0",
"UI",
".",
"message",
"(",
"\"Loading '#{path}'...\"",
")",
"options",
"[",
":app_review_information",
"]",
"[",
"option_name",
"]",
"||=",
"File",
".",
"read",
"(",
"path",
")",
"end",
"end"
] | Loads the metadata files and stores them into the options object | [
"Loads",
"the",
"metadata",
"files",
"and",
"stores",
"them",
"into",
"the",
"options",
"object"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/deliver/lib/deliver/upload_metadata.rb#L284-L331 | train |
fastlane/fastlane | deliver/lib/deliver/upload_metadata.rb | Deliver.UploadMetadata.normalize_language_keys | def normalize_language_keys(options)
(LOCALISED_VERSION_VALUES + LOCALISED_APP_VALUES).each do |key|
current = options[key]
next unless current && current.kind_of?(Hash)
current.keys.each do |language|
current[language.to_s] = current.delete(language)
end
end
options
end | ruby | def normalize_language_keys(options)
(LOCALISED_VERSION_VALUES + LOCALISED_APP_VALUES).each do |key|
current = options[key]
next unless current && current.kind_of?(Hash)
current.keys.each do |language|
current[language.to_s] = current.delete(language)
end
end
options
end | [
"def",
"normalize_language_keys",
"(",
"options",
")",
"(",
"LOCALISED_VERSION_VALUES",
"+",
"LOCALISED_APP_VALUES",
")",
".",
"each",
"do",
"|",
"key",
"|",
"current",
"=",
"options",
"[",
"key",
"]",
"next",
"unless",
"current",
"&&",
"current",
".",
"kind_of?",
"(",
"Hash",
")",
"current",
".",
"keys",
".",
"each",
"do",
"|",
"language",
"|",
"current",
"[",
"language",
".",
"to_s",
"]",
"=",
"current",
".",
"delete",
"(",
"language",
")",
"end",
"end",
"options",
"end"
] | Normalizes languages keys from symbols to strings | [
"Normalizes",
"languages",
"keys",
"from",
"symbols",
"to",
"strings"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/deliver/lib/deliver/upload_metadata.rb#L336-L347 | train |
fastlane/fastlane | spaceship/lib/spaceship/du/utilities.rb | Spaceship.Utilities.resolution | def resolution(path)
return FastImage.size(path) if content_type(path).start_with?("image")
return video_resolution(path) if content_type(path).start_with?("video")
raise "Cannot find resolution of file #{path}"
end | ruby | def resolution(path)
return FastImage.size(path) if content_type(path).start_with?("image")
return video_resolution(path) if content_type(path).start_with?("video")
raise "Cannot find resolution of file #{path}"
end | [
"def",
"resolution",
"(",
"path",
")",
"return",
"FastImage",
".",
"size",
"(",
"path",
")",
"if",
"content_type",
"(",
"path",
")",
".",
"start_with?",
"(",
"\"image\"",
")",
"return",
"video_resolution",
"(",
"path",
")",
"if",
"content_type",
"(",
"path",
")",
".",
"start_with?",
"(",
"\"video\"",
")",
"raise",
"\"Cannot find resolution of file #{path}\"",
"end"
] | Identifies the resolution of a video or an image.
Supports all video and images required by DU-UTC right now
@param path (String) the path to the file | [
"Identifies",
"the",
"resolution",
"of",
"a",
"video",
"or",
"an",
"image",
".",
"Supports",
"all",
"video",
"and",
"images",
"required",
"by",
"DU",
"-",
"UTC",
"right",
"now"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/spaceship/lib/spaceship/du/utilities.rb#L25-L29 | train |
fastlane/fastlane | fastlane/lib/fastlane/server/socket_server_action_command_executor.rb | Fastlane.SocketServerActionCommandExecutor.run_action_requiring_special_handling | def run_action_requiring_special_handling(command: nil, parameter_map: nil, action_return_type: nil)
action_return = nil
closure_argument_value = nil # only used if the action uses it
case command.method_name
when "sh"
error_callback = proc { |string_value| closure_argument_value = string_value }
command_param = parameter_map[:command]
log_param = parameter_map[:log]
action_return = Fastlane::FastFile.sh(command_param, log: log_param, error_callback: error_callback)
end
command_return = ActionCommandReturn.new(
return_value: action_return,
return_value_type: action_return_type,
closure_argument_value: closure_argument_value
)
return command_return
end | ruby | def run_action_requiring_special_handling(command: nil, parameter_map: nil, action_return_type: nil)
action_return = nil
closure_argument_value = nil # only used if the action uses it
case command.method_name
when "sh"
error_callback = proc { |string_value| closure_argument_value = string_value }
command_param = parameter_map[:command]
log_param = parameter_map[:log]
action_return = Fastlane::FastFile.sh(command_param, log: log_param, error_callback: error_callback)
end
command_return = ActionCommandReturn.new(
return_value: action_return,
return_value_type: action_return_type,
closure_argument_value: closure_argument_value
)
return command_return
end | [
"def",
"run_action_requiring_special_handling",
"(",
"command",
":",
"nil",
",",
"parameter_map",
":",
"nil",
",",
"action_return_type",
":",
"nil",
")",
"action_return",
"=",
"nil",
"closure_argument_value",
"=",
"nil",
"# only used if the action uses it",
"case",
"command",
".",
"method_name",
"when",
"\"sh\"",
"error_callback",
"=",
"proc",
"{",
"|",
"string_value",
"|",
"closure_argument_value",
"=",
"string_value",
"}",
"command_param",
"=",
"parameter_map",
"[",
":command",
"]",
"log_param",
"=",
"parameter_map",
"[",
":log",
"]",
"action_return",
"=",
"Fastlane",
"::",
"FastFile",
".",
"sh",
"(",
"command_param",
",",
"log",
":",
"log_param",
",",
"error_callback",
":",
"error_callback",
")",
"end",
"command_return",
"=",
"ActionCommandReturn",
".",
"new",
"(",
"return_value",
":",
"action_return",
",",
"return_value_type",
":",
"action_return_type",
",",
"closure_argument_value",
":",
"closure_argument_value",
")",
"return",
"command_return",
"end"
] | Some actions have special handling in fast_file.rb, that means we can't directly call the action
but we have to use the same logic that is in fast_file.rb instead.
That's where this switch statement comes into play | [
"Some",
"actions",
"have",
"special",
"handling",
"in",
"fast_file",
".",
"rb",
"that",
"means",
"we",
"can",
"t",
"directly",
"call",
"the",
"action",
"but",
"we",
"have",
"to",
"use",
"the",
"same",
"logic",
"that",
"is",
"in",
"fast_file",
".",
"rb",
"instead",
".",
"That",
"s",
"where",
"this",
"switch",
"statement",
"comes",
"into",
"play"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane/lib/fastlane/server/socket_server_action_command_executor.rb#L80-L99 | train |
fastlane/fastlane | gym/lib/gym/runner.rb | Gym.Runner.build_app | def build_app
command = BuildCommandGenerator.generate
print_command(command, "Generated Build Command") if FastlaneCore::Globals.verbose?
FastlaneCore::CommandExecutor.execute(command: command,
print_all: true,
print_command: !Gym.config[:silent],
error: proc do |output|
ErrorHandler.handle_build_error(output)
end)
mark_archive_as_built_by_gym(BuildCommandGenerator.archive_path)
UI.success("Successfully stored the archive. You can find it in the Xcode Organizer.") unless Gym.config[:archive_path].nil?
UI.verbose("Stored the archive in: " + BuildCommandGenerator.archive_path)
post_build_app
end | ruby | def build_app
command = BuildCommandGenerator.generate
print_command(command, "Generated Build Command") if FastlaneCore::Globals.verbose?
FastlaneCore::CommandExecutor.execute(command: command,
print_all: true,
print_command: !Gym.config[:silent],
error: proc do |output|
ErrorHandler.handle_build_error(output)
end)
mark_archive_as_built_by_gym(BuildCommandGenerator.archive_path)
UI.success("Successfully stored the archive. You can find it in the Xcode Organizer.") unless Gym.config[:archive_path].nil?
UI.verbose("Stored the archive in: " + BuildCommandGenerator.archive_path)
post_build_app
end | [
"def",
"build_app",
"command",
"=",
"BuildCommandGenerator",
".",
"generate",
"print_command",
"(",
"command",
",",
"\"Generated Build Command\"",
")",
"if",
"FastlaneCore",
"::",
"Globals",
".",
"verbose?",
"FastlaneCore",
"::",
"CommandExecutor",
".",
"execute",
"(",
"command",
":",
"command",
",",
"print_all",
":",
"true",
",",
"print_command",
":",
"!",
"Gym",
".",
"config",
"[",
":silent",
"]",
",",
"error",
":",
"proc",
"do",
"|",
"output",
"|",
"ErrorHandler",
".",
"handle_build_error",
"(",
"output",
")",
"end",
")",
"mark_archive_as_built_by_gym",
"(",
"BuildCommandGenerator",
".",
"archive_path",
")",
"UI",
".",
"success",
"(",
"\"Successfully stored the archive. You can find it in the Xcode Organizer.\"",
")",
"unless",
"Gym",
".",
"config",
"[",
":archive_path",
"]",
".",
"nil?",
"UI",
".",
"verbose",
"(",
"\"Stored the archive in: \"",
"+",
"BuildCommandGenerator",
".",
"archive_path",
")",
"post_build_app",
"end"
] | Builds the app and prepares the archive | [
"Builds",
"the",
"app",
"and",
"prepares",
"the",
"archive"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/gym/lib/gym/runner.rb#L90-L105 | train |
fastlane/fastlane | gym/lib/gym/runner.rb | Gym.Runner.post_build_app | def post_build_app
command = BuildCommandGenerator.post_build
return if command.empty?
print_command(command, "Generated Post-Build Command") if FastlaneCore::Globals.verbose?
FastlaneCore::CommandExecutor.execute(command: command,
print_all: true,
print_command: !Gym.config[:silent],
error: proc do |output|
ErrorHandler.handle_build_error(output)
end)
end | ruby | def post_build_app
command = BuildCommandGenerator.post_build
return if command.empty?
print_command(command, "Generated Post-Build Command") if FastlaneCore::Globals.verbose?
FastlaneCore::CommandExecutor.execute(command: command,
print_all: true,
print_command: !Gym.config[:silent],
error: proc do |output|
ErrorHandler.handle_build_error(output)
end)
end | [
"def",
"post_build_app",
"command",
"=",
"BuildCommandGenerator",
".",
"post_build",
"return",
"if",
"command",
".",
"empty?",
"print_command",
"(",
"command",
",",
"\"Generated Post-Build Command\"",
")",
"if",
"FastlaneCore",
"::",
"Globals",
".",
"verbose?",
"FastlaneCore",
"::",
"CommandExecutor",
".",
"execute",
"(",
"command",
":",
"command",
",",
"print_all",
":",
"true",
",",
"print_command",
":",
"!",
"Gym",
".",
"config",
"[",
":silent",
"]",
",",
"error",
":",
"proc",
"do",
"|",
"output",
"|",
"ErrorHandler",
".",
"handle_build_error",
"(",
"output",
")",
"end",
")",
"end"
] | Post-processing of build_app | [
"Post",
"-",
"processing",
"of",
"build_app"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/gym/lib/gym/runner.rb#L108-L120 | train |
fastlane/fastlane | gym/lib/gym/runner.rb | Gym.Runner.move_ipa | def move_ipa
FileUtils.mv(PackageCommandGenerator.ipa_path, File.expand_path(Gym.config[:output_directory]), force: true)
ipa_path = File.expand_path(File.join(Gym.config[:output_directory], File.basename(PackageCommandGenerator.ipa_path)))
UI.success("Successfully exported and signed the ipa file:")
UI.message(ipa_path)
ipa_path
end | ruby | def move_ipa
FileUtils.mv(PackageCommandGenerator.ipa_path, File.expand_path(Gym.config[:output_directory]), force: true)
ipa_path = File.expand_path(File.join(Gym.config[:output_directory], File.basename(PackageCommandGenerator.ipa_path)))
UI.success("Successfully exported and signed the ipa file:")
UI.message(ipa_path)
ipa_path
end | [
"def",
"move_ipa",
"FileUtils",
".",
"mv",
"(",
"PackageCommandGenerator",
".",
"ipa_path",
",",
"File",
".",
"expand_path",
"(",
"Gym",
".",
"config",
"[",
":output_directory",
"]",
")",
",",
"force",
":",
"true",
")",
"ipa_path",
"=",
"File",
".",
"expand_path",
"(",
"File",
".",
"join",
"(",
"Gym",
".",
"config",
"[",
":output_directory",
"]",
",",
"File",
".",
"basename",
"(",
"PackageCommandGenerator",
".",
"ipa_path",
")",
")",
")",
"UI",
".",
"success",
"(",
"\"Successfully exported and signed the ipa file:\"",
")",
"UI",
".",
"message",
"(",
"ipa_path",
")",
"ipa_path",
"end"
] | Moves over the binary and dsym file to the output directory
@return (String) The path to the resulting ipa file | [
"Moves",
"over",
"the",
"binary",
"and",
"dsym",
"file",
"to",
"the",
"output",
"directory"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/gym/lib/gym/runner.rb#L173-L180 | train |
fastlane/fastlane | gym/lib/gym/runner.rb | Gym.Runner.copy_mac_app | def copy_mac_app
exe_name = Gym.project.build_settings(key: "EXECUTABLE_NAME")
app_path = File.join(BuildCommandGenerator.archive_path, "Products/Applications/#{exe_name}.app")
UI.crash!("Couldn't find application in '#{BuildCommandGenerator.archive_path}'") unless File.exist?(app_path)
FileUtils.cp_r(app_path, File.expand_path(Gym.config[:output_directory]), remove_destination: true)
app_path = File.join(Gym.config[:output_directory], File.basename(app_path))
UI.success("Successfully exported the .app file:")
UI.message(app_path)
app_path
end | ruby | def copy_mac_app
exe_name = Gym.project.build_settings(key: "EXECUTABLE_NAME")
app_path = File.join(BuildCommandGenerator.archive_path, "Products/Applications/#{exe_name}.app")
UI.crash!("Couldn't find application in '#{BuildCommandGenerator.archive_path}'") unless File.exist?(app_path)
FileUtils.cp_r(app_path, File.expand_path(Gym.config[:output_directory]), remove_destination: true)
app_path = File.join(Gym.config[:output_directory], File.basename(app_path))
UI.success("Successfully exported the .app file:")
UI.message(app_path)
app_path
end | [
"def",
"copy_mac_app",
"exe_name",
"=",
"Gym",
".",
"project",
".",
"build_settings",
"(",
"key",
":",
"\"EXECUTABLE_NAME\"",
")",
"app_path",
"=",
"File",
".",
"join",
"(",
"BuildCommandGenerator",
".",
"archive_path",
",",
"\"Products/Applications/#{exe_name}.app\"",
")",
"UI",
".",
"crash!",
"(",
"\"Couldn't find application in '#{BuildCommandGenerator.archive_path}'\"",
")",
"unless",
"File",
".",
"exist?",
"(",
"app_path",
")",
"FileUtils",
".",
"cp_r",
"(",
"app_path",
",",
"File",
".",
"expand_path",
"(",
"Gym",
".",
"config",
"[",
":output_directory",
"]",
")",
",",
"remove_destination",
":",
"true",
")",
"app_path",
"=",
"File",
".",
"join",
"(",
"Gym",
".",
"config",
"[",
":output_directory",
"]",
",",
"File",
".",
"basename",
"(",
"app_path",
")",
")",
"UI",
".",
"success",
"(",
"\"Successfully exported the .app file:\"",
")",
"UI",
".",
"message",
"(",
"app_path",
")",
"app_path",
"end"
] | Copies the .app from the archive into the output directory | [
"Copies",
"the",
".",
"app",
"from",
"the",
"archive",
"into",
"the",
"output",
"directory"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/gym/lib/gym/runner.rb#L201-L210 | train |
fastlane/fastlane | gym/lib/gym/runner.rb | Gym.Runner.move_manifest | def move_manifest
if File.exist?(PackageCommandGenerator.manifest_path)
FileUtils.mv(PackageCommandGenerator.manifest_path, File.expand_path(Gym.config[:output_directory]), force: true)
manifest_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.manifest_path))
UI.success("Successfully exported the manifest.plist file:")
UI.message(manifest_path)
manifest_path
end
end | ruby | def move_manifest
if File.exist?(PackageCommandGenerator.manifest_path)
FileUtils.mv(PackageCommandGenerator.manifest_path, File.expand_path(Gym.config[:output_directory]), force: true)
manifest_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.manifest_path))
UI.success("Successfully exported the manifest.plist file:")
UI.message(manifest_path)
manifest_path
end
end | [
"def",
"move_manifest",
"if",
"File",
".",
"exist?",
"(",
"PackageCommandGenerator",
".",
"manifest_path",
")",
"FileUtils",
".",
"mv",
"(",
"PackageCommandGenerator",
".",
"manifest_path",
",",
"File",
".",
"expand_path",
"(",
"Gym",
".",
"config",
"[",
":output_directory",
"]",
")",
",",
"force",
":",
"true",
")",
"manifest_path",
"=",
"File",
".",
"join",
"(",
"File",
".",
"expand_path",
"(",
"Gym",
".",
"config",
"[",
":output_directory",
"]",
")",
",",
"File",
".",
"basename",
"(",
"PackageCommandGenerator",
".",
"manifest_path",
")",
")",
"UI",
".",
"success",
"(",
"\"Successfully exported the manifest.plist file:\"",
")",
"UI",
".",
"message",
"(",
"manifest_path",
")",
"manifest_path",
"end",
"end"
] | Move the manifest.plist if exists into the output directory | [
"Move",
"the",
"manifest",
".",
"plist",
"if",
"exists",
"into",
"the",
"output",
"directory"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/gym/lib/gym/runner.rb#L213-L222 | train |
fastlane/fastlane | gym/lib/gym/runner.rb | Gym.Runner.move_app_thinning | def move_app_thinning
if File.exist?(PackageCommandGenerator.app_thinning_path)
FileUtils.mv(PackageCommandGenerator.app_thinning_path, File.expand_path(Gym.config[:output_directory]), force: true)
app_thinning_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.app_thinning_path))
UI.success("Successfully exported the app-thinning.plist file:")
UI.message(app_thinning_path)
app_thinning_path
end
end | ruby | def move_app_thinning
if File.exist?(PackageCommandGenerator.app_thinning_path)
FileUtils.mv(PackageCommandGenerator.app_thinning_path, File.expand_path(Gym.config[:output_directory]), force: true)
app_thinning_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.app_thinning_path))
UI.success("Successfully exported the app-thinning.plist file:")
UI.message(app_thinning_path)
app_thinning_path
end
end | [
"def",
"move_app_thinning",
"if",
"File",
".",
"exist?",
"(",
"PackageCommandGenerator",
".",
"app_thinning_path",
")",
"FileUtils",
".",
"mv",
"(",
"PackageCommandGenerator",
".",
"app_thinning_path",
",",
"File",
".",
"expand_path",
"(",
"Gym",
".",
"config",
"[",
":output_directory",
"]",
")",
",",
"force",
":",
"true",
")",
"app_thinning_path",
"=",
"File",
".",
"join",
"(",
"File",
".",
"expand_path",
"(",
"Gym",
".",
"config",
"[",
":output_directory",
"]",
")",
",",
"File",
".",
"basename",
"(",
"PackageCommandGenerator",
".",
"app_thinning_path",
")",
")",
"UI",
".",
"success",
"(",
"\"Successfully exported the app-thinning.plist file:\"",
")",
"UI",
".",
"message",
"(",
"app_thinning_path",
")",
"app_thinning_path",
"end",
"end"
] | Move the app-thinning.plist file into the output directory | [
"Move",
"the",
"app",
"-",
"thinning",
".",
"plist",
"file",
"into",
"the",
"output",
"directory"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/gym/lib/gym/runner.rb#L225-L234 | train |
fastlane/fastlane | gym/lib/gym/runner.rb | Gym.Runner.move_app_thinning_size_report | 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 | 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 | [
"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"
] | Move the App Thinning Size Report.txt file into the output directory | [
"Move",
"the",
"App",
"Thinning",
"Size",
"Report",
".",
"txt",
"file",
"into",
"the",
"output",
"directory"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/gym/lib/gym/runner.rb#L237-L246 | train |
fastlane/fastlane | gym/lib/gym/runner.rb | Gym.Runner.move_apps_folder | 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 | 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 | [
"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"
] | Move the Apps folder to the output directory | [
"Move",
"the",
"Apps",
"folder",
"to",
"the",
"output",
"directory"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/gym/lib/gym/runner.rb#L249-L258 | train |
fastlane/fastlane | fastlane/lib/fastlane/swift_fastlane_api_generator.rb | Fastlane.SwiftFastlaneAPIGenerator.determine_api_version | 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 | 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 | [
"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"
] | compares the new file content to the old and figures out what api_version the new content should be | [
"compares",
"the",
"new",
"file",
"content",
"to",
"the",
"old",
"and",
"figures",
"out",
"what",
"api_version",
"the",
"new",
"content",
"should",
"be"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane/lib/fastlane/swift_fastlane_api_generator.rb#L223-L246 | train |
fastlane/fastlane | fastlane/lib/fastlane/swift_fastlane_api_generator.rb | Fastlane.SwiftFastlaneAPIGenerator.increment_api_version_string | 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 | 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 | [
"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"
] | expects format to be "X.Y.Z" where each value is a number | [
"expects",
"format",
"to",
"be",
"X",
".",
"Y",
".",
"Z",
"where",
"each",
"value",
"is",
"a",
"number"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane/lib/fastlane/swift_fastlane_api_generator.rb#L249-L269 | train |
fastlane/fastlane | credentials_manager/lib/credentials_manager/appfile_config.rb | CredentialsManager.AppfileConfig.for_lane | 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 | 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 | [
"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"
] | Override Appfile configuration for a specific lane.
lane_name - Symbol representing a lane name. (Can be either :name, 'name' or 'platform name')
block - Block to execute to override configuration values.
Discussion If received lane name does not match the lane name available as environment variable, no changes will
be applied. | [
"Override",
"Appfile",
"configuration",
"for",
"a",
"specific",
"lane",
"."
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/credentials_manager/lib/credentials_manager/appfile_config.rb#L152-L166 | train |
fastlane/fastlane | fastlane/lib/fastlane/swift_runner_upgrader.rb | Fastlane.SwiftRunnerUpgrader.file_needs_update? | 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 | 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 | [
"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"
] | compares source file against the target file's FastlaneRunnerAPIVersion and returned `true` if there is a difference | [
"compares",
"source",
"file",
"against",
"the",
"target",
"file",
"s",
"FastlaneRunnerAPIVersion",
"and",
"returned",
"true",
"if",
"there",
"is",
"a",
"difference"
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane/lib/fastlane/swift_runner_upgrader.rb#L80-L107 | train |
fastlane/fastlane | fastlane/lib/fastlane/swift_runner_upgrader.rb | Fastlane.SwiftRunnerUpgrader.copy_file_if_needed! | 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 | 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 | [
"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"
] | currently just copies file, even if not needed. | [
"currently",
"just",
"copies",
"file",
"even",
"if",
"not",
"needed",
"."
] | 457c5d647c77f0e078dafa5129da616914e002c5 | https://github.com/fastlane/fastlane/blob/457c5d647c77f0e078dafa5129da616914e002c5/fastlane/lib/fastlane/swift_runner_upgrader.rb#L110-L128 | train |
apache/thrift | lib/rb/lib/thrift/server/thread_pool_server.rb | Thrift.ThreadPoolServer.serve | 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 | 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 | [
"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"
] | exceptions that happen in worker threads simply cause that thread
to die and another to be spawned in its place. | [
"exceptions",
"that",
"happen",
"in",
"worker",
"threads",
"simply",
"cause",
"that",
"thread",
"to",
"die",
"and",
"another",
"to",
"be",
"spawned",
"in",
"its",
"place",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/server/thread_pool_server.rb#L42-L73 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.write_json_char | 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 | 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 | [
"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"
] | Write the character ch as part of a JSON string, escaping as appropriate. | [
"Write",
"the",
"character",
"ch",
"as",
"part",
"of",
"a",
"JSON",
"string",
"escaping",
"as",
"appropriate",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L262-L297 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.write_json_string | 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 | 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 | [
"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"
] | Write out the contents of the string str as a JSON string, escaping characters as appropriate. | [
"Write",
"out",
"the",
"contents",
"of",
"the",
"string",
"str",
"as",
"a",
"JSON",
"string",
"escaping",
"characters",
"as",
"appropriate",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L300-L307 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.write_json_base64 | def write_json_base64(str)
@context.write(trans)
trans.write(@@kJSONStringDelimiter)
trans.write(Base64.strict_encode64(str))
trans.write(@@kJSONStringDelimiter)
end | ruby | def write_json_base64(str)
@context.write(trans)
trans.write(@@kJSONStringDelimiter)
trans.write(Base64.strict_encode64(str))
trans.write(@@kJSONStringDelimiter)
end | [
"def",
"write_json_base64",
"(",
"str",
")",
"@context",
".",
"write",
"(",
"trans",
")",
"trans",
".",
"write",
"(",
"@@kJSONStringDelimiter",
")",
"trans",
".",
"write",
"(",
"Base64",
".",
"strict_encode64",
"(",
"str",
")",
")",
"trans",
".",
"write",
"(",
"@@kJSONStringDelimiter",
")",
"end"
] | Write out the contents of the string as JSON string, base64-encoding
the string's contents, and escaping as appropriate | [
"Write",
"out",
"the",
"contents",
"of",
"the",
"string",
"as",
"JSON",
"string",
"base64",
"-",
"encoding",
"the",
"string",
"s",
"contents",
"and",
"escaping",
"as",
"appropriate"
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L311-L316 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.write_json_double | 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 | 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 | [
"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"
] | Convert the given double to a JSON string, which is either the number,
"NaN" or "Infinity" or "-Infinity". | [
"Convert",
"the",
"given",
"double",
"to",
"a",
"JSON",
"string",
"which",
"is",
"either",
"the",
"number",
"NaN",
"or",
"Infinity",
"or",
"-",
"Infinity",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L334-L359 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.read_json_escape_char | 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 | 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 | [
"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"
] | Decodes the four hex parts of a JSON escaped string character and returns
the character via out.
Note - this only supports Unicode characters in the BMP (U+0000 to U+FFFF);
characters above the BMP are encoded as two escape sequences (surrogate pairs),
which is not yet implemented | [
"Decodes",
"the",
"four",
"hex",
"parts",
"of",
"a",
"JSON",
"escaped",
"string",
"character",
"and",
"returns",
"the",
"character",
"via",
"out",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L495-L505 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.read_json_string | 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 | 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 | [
"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"
] | Decodes a JSON string, including unescaping, and returns the string via str | [
"Decodes",
"a",
"JSON",
"string",
"including",
"unescaping",
"and",
"returns",
"the",
"string",
"via",
"str"
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L508-L546 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.read_json_base64 | 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 | 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 | [
"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"
] | Reads a block of base64 characters, decoding it, and returns via str | [
"Reads",
"a",
"block",
"of",
"base64",
"characters",
"decoding",
"it",
"and",
"returns",
"via",
"str"
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L549-L559 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.read_json_numeric_chars | 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 | 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 | [
"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"
] | Reads a sequence of characters, stopping at the first one that is not
a valid JSON numeric character. | [
"Reads",
"a",
"sequence",
"of",
"characters",
"stopping",
"at",
"the",
"first",
"one",
"that",
"is",
"not",
"a",
"valid",
"JSON",
"numeric",
"character",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L563-L574 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.read_json_integer | 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 | 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 | [
"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"
] | Reads a sequence of characters and assembles them into a number,
returning them via num | [
"Reads",
"a",
"sequence",
"of",
"characters",
"and",
"assembles",
"them",
"into",
"a",
"number",
"returning",
"them",
"via",
"num"
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L578-L596 | train |
apache/thrift | lib/rb/lib/thrift/protocol/json_protocol.rb | Thrift.JsonProtocol.read_json_double | 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 ([email protected])
# 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 | 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 ([email protected])
# 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 | [
"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"
] | Reads a JSON number or string and interprets it as a double. | [
"Reads",
"a",
"JSON",
"number",
"or",
"string",
"and",
"interprets",
"it",
"as",
"a",
"double",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/json_protocol.rb#L599-L635 | train |
apache/thrift | lib/rb/lib/thrift/protocol/base_protocol.rb | Thrift.BaseProtocol.write_field | 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 | 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 | [
"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"
] | Writes a field based on the field information, field ID and value.
field_info - A Hash containing the definition of the field:
:name - The name of the field.
:type - The type of the field, which must be a Thrift::Types constant.
:binary - A Boolean flag that indicates if Thrift::Types::STRING is a binary string (string without encoding).
fid - The ID of the field.
value - The field's value to write; object type varies based on :type.
Returns nothing. | [
"Writes",
"a",
"field",
"based",
"on",
"the",
"field",
"information",
"field",
"ID",
"and",
"value",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/base_protocol.rb#L225-L243 | train |
apache/thrift | lib/rb/lib/thrift/protocol/base_protocol.rb | Thrift.BaseProtocol.write_type | 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 | 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 | [
"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"
] | Writes a field value based on the field information.
field_info - A Hash containing the definition of the field:
:type - The Thrift::Types constant that determines how the value is written.
:binary - A Boolean flag that indicates if Thrift::Types::STRING is a binary string (string without encoding).
value - The field's value to write; object type varies based on field_info[:type].
Returns nothing. | [
"Writes",
"a",
"field",
"value",
"based",
"on",
"the",
"field",
"information",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/base_protocol.rb#L253-L284 | train |
apache/thrift | lib/rb/lib/thrift/protocol/base_protocol.rb | Thrift.BaseProtocol.read_type | 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 | 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 | [
"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"
] | Reads a field value based on the field information.
field_info - A Hash containing the pertinent data to write:
:type - The Thrift::Types constant that determines how the value is written.
:binary - A flag that indicates if Thrift::Types::STRING is a binary string (string without encoding).
Returns the value read; object type varies based on field_info[:type]. | [
"Reads",
"a",
"field",
"value",
"based",
"on",
"the",
"field",
"information",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/base_protocol.rb#L293-L322 | train |
apache/thrift | lib/rb/lib/thrift/protocol/compact_protocol.rb | Thrift.CompactProtocol.write_field_begin_internal | 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 | 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 | [
"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"
] | The workhorse of writeFieldBegin. It has the option of doing a
'type override' of the type header. This is used specifically in the
boolean field case. | [
"The",
"workhorse",
"of",
"writeFieldBegin",
".",
"It",
"has",
"the",
"option",
"of",
"doing",
"a",
"type",
"override",
"of",
"the",
"type",
"header",
".",
"This",
"is",
"used",
"specifically",
"in",
"the",
"boolean",
"field",
"case",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/compact_protocol.rb#L140-L158 | train |
apache/thrift | lib/rb/lib/thrift/protocol/compact_protocol.rb | Thrift.CompactProtocol.write_collection_begin | 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 | 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 | [
"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"
] | Abstract method for writing the start of lists and sets. List and sets on
the wire differ only by the type indicator. | [
"Abstract",
"method",
"for",
"writing",
"the",
"start",
"of",
"lists",
"and",
"sets",
".",
"List",
"and",
"sets",
"on",
"the",
"wire",
"differ",
"only",
"by",
"the",
"type",
"indicator",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/protocol/compact_protocol.rb#L359-L366 | train |
apache/thrift | lib/rb/lib/thrift/transport/buffered_transport.rb | Thrift.BufferedTransport.read_into_buffer | 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 | 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 | [
"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"
] | Reads a number of bytes from the transport into the buffer passed.
buffer - The String (byte buffer) to write data to; this is assumed to have a BINARY encoding.
size - The number of bytes to read from the transport and write to the buffer.
Returns the number of bytes read. | [
"Reads",
"a",
"number",
"of",
"bytes",
"from",
"the",
"transport",
"into",
"the",
"buffer",
"passed",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/transport/buffered_transport.rb#L77-L93 | train |
apache/thrift | lib/rb/benchmark/server.rb | Server.BenchmarkHandler.fibonacci | 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 | def fibonacci(n)
seq = [1, 1]
3.upto(n) do
seq << seq[-1] + seq[-2]
end
seq[n-1] # n is 1-based
end | [
"def",
"fibonacci",
"(",
"n",
")",
"seq",
"=",
"[",
"1",
",",
"1",
"]",
"3",
".",
"upto",
"(",
"n",
")",
"do",
"seq",
"<<",
"seq",
"[",
"-",
"1",
"]",
"+",
"seq",
"[",
"-",
"2",
"]",
"end",
"seq",
"[",
"n",
"-",
"1",
"]",
"# n is 1-based",
"end"
] | 1-based index into the fibonacci sequence | [
"1",
"-",
"based",
"index",
"into",
"the",
"fibonacci",
"sequence"
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/benchmark/server.rb#L30-L36 | train |
apache/thrift | lib/rb/lib/thrift/transport/framed_transport.rb | Thrift.FramedTransport.flush | 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 | 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 | [
"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"
] | Writes the output buffer to the stream in the format of a 4-byte length
followed by the actual data. | [
"Writes",
"the",
"output",
"buffer",
"to",
"the",
"stream",
"in",
"the",
"format",
"of",
"a",
"4",
"-",
"byte",
"length",
"followed",
"by",
"the",
"actual",
"data",
"."
] | 27d8387c49a49fcf193893f834e9766ae0b051c1 | https://github.com/apache/thrift/blob/27d8387c49a49fcf193893f834e9766ae0b051c1/lib/rb/lib/thrift/transport/framed_transport.rb#L91-L100 | train |
huginn/huginn | app/concerns/liquid_interpolatable.rb | LiquidInterpolatable.Filters.to_uri | 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 | 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 | [
"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"
] | Parse an input into a URI object, optionally resolving it
against a base URI if given.
A URI object will have the following properties: scheme,
userinfo, host, port, registry, path, opaque, query, and
fragment. | [
"Parse",
"an",
"input",
"into",
"a",
"URI",
"object",
"optionally",
"resolving",
"it",
"against",
"a",
"base",
"URI",
"if",
"given",
"."
] | 01e18fef7b6bd827a5d48a89391e460b5fb1bee3 | https://github.com/huginn/huginn/blob/01e18fef7b6bd827a5d48a89391e460b5fb1bee3/app/concerns/liquid_interpolatable.rb#L142-L151 | train |
huginn/huginn | app/concerns/liquid_interpolatable.rb | LiquidInterpolatable.Filters.to_xpath | 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 | 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 | [
"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"
] | Escape a string for use in XPath expression | [
"Escape",
"a",
"string",
"for",
"use",
"in",
"XPath",
"expression"
] | 01e18fef7b6bd827a5d48a89391e460b5fb1bee3 | https://github.com/huginn/huginn/blob/01e18fef7b6bd827a5d48a89391e460b5fb1bee3/app/concerns/liquid_interpolatable.rb#L218-L232 | train |
huginn/huginn | app/models/agents/website_agent.rb | Agents.WebsiteAgent.store_payload! | 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 | 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 | [
"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"
] | This method returns true if the result should be stored as a new event.
If mode is set to 'on_change', this method may return false and update an existing
event to expire further in the future. | [
"This",
"method",
"returns",
"true",
"if",
"the",
"result",
"should",
"be",
"stored",
"as",
"a",
"new",
"event",
".",
"If",
"mode",
"is",
"set",
"to",
"on_change",
"this",
"method",
"may",
"return",
"false",
"and",
"update",
"an",
"existing",
"event",
"to",
"expire",
"further",
"in",
"the",
"future",
"."
] | 01e18fef7b6bd827a5d48a89391e460b5fb1bee3 | https://github.com/huginn/huginn/blob/01e18fef7b6bd827a5d48a89391e460b5fb1bee3/app/models/agents/website_agent.rb#L507-L522 | train |
hashicorp/vagrant | lib/vagrant/batch_action.rb | Vagrant.BatchAction.run | 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 | 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 | [
"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"
] | Run all the queued up actions, parallelizing if possible.
This will parallelize if and only if the provider of every machine
supports parallelization and parallelization is possible from
initialization of the class. | [
"Run",
"all",
"the",
"queued",
"up",
"actions",
"parallelizing",
"if",
"possible",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/batch_action.rb#L39-L163 | train |
hashicorp/vagrant | lib/vagrant/registry.rb | Vagrant.Registry.get | def get(key)
return nil if [email protected]?(key)
return @results_cache[key] if @results_cache.key?(key)
@results_cache[key] = @items[key].call
end | ruby | def get(key)
return nil if [email protected]?(key)
return @results_cache[key] if @results_cache.key?(key)
@results_cache[key] = @items[key].call
end | [
"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"
] | Get a value by the given key.
This will evaluate the block given to `register` and return the
resulting value. | [
"Get",
"a",
"value",
"by",
"the",
"given",
"key",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/registry.rb#L24-L28 | train |
hashicorp/vagrant | lib/vagrant/registry.rb | Vagrant.Registry.merge | def merge(other)
self.class.new.tap do |result|
result.merge!(self)
result.merge!(other)
end
end | ruby | def merge(other)
self.class.new.tap do |result|
result.merge!(self)
result.merge!(other)
end
end | [
"def",
"merge",
"(",
"other",
")",
"self",
".",
"class",
".",
"new",
".",
"tap",
"do",
"|",
"result",
"|",
"result",
".",
"merge!",
"(",
"self",
")",
"result",
".",
"merge!",
"(",
"other",
")",
"end",
"end"
] | Merge one registry with another and return a completely new
registry. Note that the result cache is completely busted, so
any gets on the new registry will result in a cache miss. | [
"Merge",
"one",
"registry",
"with",
"another",
"and",
"return",
"a",
"completely",
"new",
"registry",
".",
"Note",
"that",
"the",
"result",
"cache",
"is",
"completely",
"busted",
"so",
"any",
"gets",
"on",
"the",
"new",
"registry",
"will",
"result",
"in",
"a",
"cache",
"miss",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/registry.rb#L71-L76 | train |
hashicorp/vagrant | lib/vagrant/bundler.rb | Vagrant.Bundler.init! | 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 | 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 | [
"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"
] | Initializes Bundler and the various gem paths so that we can begin
loading gems. | [
"Initializes",
"Bundler",
"and",
"the",
"various",
"gem",
"paths",
"so",
"that",
"we",
"can",
"begin",
"loading",
"gems",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/bundler.rb#L55-L120 | train |
hashicorp/vagrant | lib/vagrant/bundler.rb | Vagrant.Bundler.update | def update(plugins, specific, **opts)
specific ||= []
update = opts.merge({gems: specific.empty? ? true : specific})
internal_install(plugins, update)
end | ruby | def update(plugins, specific, **opts)
specific ||= []
update = opts.merge({gems: specific.empty? ? true : specific})
internal_install(plugins, update)
end | [
"def",
"update",
"(",
"plugins",
",",
"specific",
",",
"**",
"opts",
")",
"specific",
"||=",
"[",
"]",
"update",
"=",
"opts",
".",
"merge",
"(",
"{",
"gems",
":",
"specific",
".",
"empty?",
"?",
"true",
":",
"specific",
"}",
")",
"internal_install",
"(",
"plugins",
",",
"update",
")",
"end"
] | Update updates the given plugins, or every plugin if none is given.
@param [Hash] plugins
@param [Array<String>] specific Specific plugin names to update. If
empty or nil, all plugins will be updated. | [
"Update",
"updates",
"the",
"given",
"plugins",
"or",
"every",
"plugin",
"if",
"none",
"is",
"given",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/bundler.rb#L159-L163 | train |
hashicorp/vagrant | lib/vagrant/bundler.rb | Vagrant.Bundler.clean | 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 | 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 | [
"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"
] | Clean removes any unused gems. | [
"Clean",
"removes",
"any",
"unused",
"gems",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/bundler.rb#L166-L247 | train |
hashicorp/vagrant | lib/vagrant/bundler.rb | Vagrant.Bundler.validate_configured_sources! | 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 | 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 | [
"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"
] | Iterates each configured RubyGem source to validate that it is properly
available. If source is unavailable an exception is raised. | [
"Iterates",
"each",
"configured",
"RubyGem",
"source",
"to",
"validate",
"that",
"it",
"is",
"properly",
"available",
".",
"If",
"source",
"is",
"unavailable",
"an",
"exception",
"is",
"raised",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/bundler.rb#L426-L443 | train |
hashicorp/vagrant | lib/vagrant/bundler.rb | Vagrant.Bundler.generate_builtin_set | 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 | 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 | [
"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"
] | Generate the builtin resolver set | [
"Generate",
"the",
"builtin",
"resolver",
"set"
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/bundler.rb#L446-L455 | train |
hashicorp/vagrant | lib/vagrant/bundler.rb | Vagrant.Bundler.activate_solution | 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 | 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 | [
"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",
"(",
"/",
"/",
")",
"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"
] | Activate a given solution | [
"Activate",
"a",
"given",
"solution"
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/bundler.rb#L483-L526 | train |
hashicorp/vagrant | lib/vagrant/machine_index.rb | Vagrant.MachineIndex.delete | 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 | 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 | [
"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"
] | Initializes a MachineIndex at the given file location.
@param [Pathname] data_dir Path to the directory where data for the
index can be stored. This folder should exist and must be writable.
Deletes a machine by UUID.
The machine being deleted with this UUID must either be locked
by this index or must be unlocked.
@param [Entry] entry The entry to delete.
@return [Boolean] true if delete is successful | [
"Initializes",
"a",
"MachineIndex",
"at",
"the",
"given",
"file",
"location",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine_index.rb#L64-L87 | train |
hashicorp/vagrant | lib/vagrant/machine_index.rb | Vagrant.MachineIndex.find_by_prefix | def find_by_prefix(prefix)
@machines.each do |uuid, data|
return data.merge("id" => uuid) if uuid.start_with?(prefix)
end
nil
end | ruby | def find_by_prefix(prefix)
@machines.each do |uuid, data|
return data.merge("id" => uuid) if uuid.start_with?(prefix)
end
nil
end | [
"def",
"find_by_prefix",
"(",
"prefix",
")",
"@machines",
".",
"each",
"do",
"|",
"uuid",
",",
"data",
"|",
"return",
"data",
".",
"merge",
"(",
"\"id\"",
"=>",
"uuid",
")",
"if",
"uuid",
".",
"start_with?",
"(",
"prefix",
")",
"end",
"nil",
"end"
] | Finds a machine where the UUID is prefixed by the given string.
@return [Hash] | [
"Finds",
"a",
"machine",
"where",
"the",
"UUID",
"is",
"prefixed",
"by",
"the",
"given",
"string",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine_index.rb#L239-L245 | train |
hashicorp/vagrant | lib/vagrant/machine_index.rb | Vagrant.MachineIndex.lock_machine | 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 | 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 | [
"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"
] | Locks a machine exclusively to us, returning the file handle
that holds the lock.
If the lock cannot be acquired, then nil is returned.
This should be called within an index lock.
@return [File] | [
"Locks",
"a",
"machine",
"exclusively",
"to",
"us",
"returning",
"the",
"file",
"handle",
"that",
"holds",
"the",
"lock",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine_index.rb#L255-L264 | train |
hashicorp/vagrant | lib/vagrant/machine_index.rb | Vagrant.MachineIndex.unlocked_release | 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 | 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 | [
"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"
] | Releases a local lock on a machine. This does not acquire any locks
so make sure to lock around it.
@param [String] id | [
"Releases",
"a",
"local",
"lock",
"on",
"a",
"machine",
".",
"This",
"does",
"not",
"acquire",
"any",
"locks",
"so",
"make",
"sure",
"to",
"lock",
"around",
"it",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine_index.rb#L270-L282 | train |
hashicorp/vagrant | lib/vagrant/machine_index.rb | Vagrant.MachineIndex.unlocked_reload | 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 | 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 | [
"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"
] | This will reload the data without locking the index. It is assumed
the caller with lock the index outside of this call.
@param [File] f | [
"This",
"will",
"reload",
"the",
"data",
"without",
"locking",
"the",
"index",
".",
"It",
"is",
"assumed",
"the",
"caller",
"with",
"lock",
"the",
"index",
"outside",
"of",
"this",
"call",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine_index.rb#L288-L305 | train |
hashicorp/vagrant | lib/vagrant/machine_index.rb | Vagrant.MachineIndex.with_index_lock | 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 | def with_index_lock
lock_path = "#{@index_file}.lock"
File.open(lock_path, "w+") do |f|
f.flock(File::LOCK_EX)
yield
end
end | [
"def",
"with_index_lock",
"lock_path",
"=",
"\"#{@index_file}.lock\"",
"File",
".",
"open",
"(",
"lock_path",
",",
"\"w+\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"flock",
"(",
"File",
"::",
"LOCK_EX",
")",
"yield",
"end",
"end"
] | This will hold a lock to the index so it can be read or updated. | [
"This",
"will",
"hold",
"a",
"lock",
"to",
"the",
"index",
"so",
"it",
"can",
"be",
"read",
"or",
"updated",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine_index.rb#L319-L325 | train |
hashicorp/vagrant | lib/vagrant/box_metadata.rb | Vagrant.BoxMetadata.version | 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 | 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 | [
"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"
] | Loads the metadata associated with the box from the given
IO.
@param [IO] io An IO object to read the metadata from.
Returns data about a single version that is included in this
metadata.
@param [String] version The version to return, this can also
be a constraint.
@return [Version] The matching version or nil if a matching
version was not found. | [
"Loads",
"the",
"metadata",
"associated",
"with",
"the",
"box",
"from",
"the",
"given",
"IO",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_metadata.rb#L51-L67 | train |
hashicorp/vagrant | lib/vagrant/cli.rb | Vagrant.CLI.help | 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 | 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 | [
"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"
] | This prints out the help for the CLI. | [
"This",
"prints",
"out",
"the",
"help",
"for",
"the",
"CLI",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/cli.rb#L78-L119 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.action_runner | 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 | 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 | [
"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"
] | Action runner for executing actions in the context of this environment.
@return [Action::Runner] | [
"Action",
"runner",
"for",
"executing",
"actions",
"in",
"the",
"context",
"of",
"this",
"environment",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L201-L217 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.active_machines | 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 | 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 | [
"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"
] | Returns a list of machines that this environment is currently
managing that physically have been created.
An "active" machine is a machine that Vagrant manages that has
been created. The machine itself may be in any state such as running,
suspended, etc. but if a machine is "active" then it exists.
Note that the machines in this array may no longer be present in
the Vagrantfile of this environment. In this case the machine can
be considered an "orphan." Determining which machines are orphan
and which aren't is not currently a supported feature, but will
be in a future version.
@return [Array<String, Symbol>] | [
"Returns",
"a",
"list",
"of",
"machines",
"that",
"this",
"environment",
"is",
"currently",
"managing",
"that",
"physically",
"have",
"been",
"created",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L233-L265 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.batch | 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 | 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 | [
"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"
] | This creates a new batch action, yielding it, and then running it
once the block is called.
This handles the case where batch actions are disabled by the
VAGRANT_NO_PARALLEL environmental variable. | [
"This",
"creates",
"a",
"new",
"batch",
"action",
"yielding",
"it",
"and",
"then",
"running",
"it",
"once",
"the",
"block",
"is",
"called",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L272-L284 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.hook | 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 | 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 | [
"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"
] | This defines a hook point where plugin action hooks that are registered
against the given name will be run in the context of this environment.
@param [Symbol] name Name of the hook.
@param [Action::Runner] action_runner A custom action runner for running hooks. | [
"This",
"defines",
"a",
"hook",
"point",
"where",
"plugin",
"action",
"hooks",
"that",
"are",
"registered",
"against",
"the",
"given",
"name",
"will",
"be",
"run",
"in",
"the",
"context",
"of",
"this",
"environment",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L520-L528 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.host | 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 | 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 | [
"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"
] | Returns the host object associated with this environment.
@return [Class] | [
"Returns",
"the",
"host",
"object",
"associated",
"with",
"this",
"environment",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L533-L564 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.lock | 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 | 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 | [
"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"
] | This acquires a process-level lock with the given name.
The lock file is held within the data directory of this environment,
so make sure that all environments that are locking are sharing
the same data directory.
This will raise Errors::EnvironmentLockedError if the lock can't
be obtained.
@param [String] name Name of the lock, since multiple locks can
be held at one time. | [
"This",
"acquires",
"a",
"process",
"-",
"level",
"lock",
"with",
"the",
"given",
"name",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L577-L645 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.push | 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 | 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 | [
"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"
] | This executes the push with the given name, raising any exceptions that
occur.
Precondition: the push is not nil and exists. | [
"This",
"executes",
"the",
"push",
"with",
"the",
"given",
"name",
"raising",
"any",
"exceptions",
"that",
"occur",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L651-L673 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.machine | 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 | 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 | [
"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"
] | This returns a machine with the proper provider for this environment.
The machine named by `name` must be in this environment.
@param [Symbol] name Name of the machine (as configured in the
Vagrantfile).
@param [Symbol] provider The provider that this machine should be
backed by.
@param [Boolean] refresh If true, then if there is a cached version
it is reloaded.
@return [Machine] | [
"This",
"returns",
"a",
"machine",
"with",
"the",
"proper",
"provider",
"for",
"this",
"environment",
".",
"The",
"machine",
"named",
"by",
"name",
"must",
"be",
"in",
"this",
"environment",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L692-L719 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.setup_local_data_path | 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 | 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 | [
"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"
] | This creates the local data directory and show an error if it
couldn't properly be created. | [
"This",
"creates",
"the",
"local",
"data",
"directory",
"and",
"show",
"an",
"error",
"if",
"it",
"couldn",
"t",
"properly",
"be",
"created",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L889-L921 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.process_configured_plugins | 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 | 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 | [
"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"
] | Check for any local plugins defined within the Vagrantfile. If
found, validate they are available. If they are not available,
request to install them, or raise an exception
@return [Hash] plugin list for loading | [
"Check",
"for",
"any",
"local",
"plugins",
"defined",
"within",
"the",
"Vagrantfile",
".",
"If",
"found",
"validate",
"they",
"are",
"available",
".",
"If",
"they",
"are",
"not",
"available",
"request",
"to",
"install",
"them",
"or",
"raise",
"an",
"exception"
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L930-L984 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.copy_insecure_private_key | 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 | 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 | [
"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"
] | This method copies the private key into the home directory if it
doesn't already exist.
This must be done because `ssh` requires that the key is chmod
0600, but if Vagrant is installed as a separate user, then the
effective uid won't be able to read the key. So the key is copied
to the home directory and chmod 0600. | [
"This",
"method",
"copies",
"the",
"private",
"key",
"into",
"the",
"home",
"directory",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L993-L1017 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.find_vagrantfile | 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 | 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 | [
"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"
] | Finds the Vagrantfile in the given directory.
@param [Pathname] path Path to search in.
@return [Pathname] | [
"Finds",
"the",
"Vagrantfile",
"in",
"the",
"given",
"directory",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L1023-L1031 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.upgrade_home_path_v1_1 | 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 | 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 | [
"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"
] | This upgrades a home directory that was in the v1.1 format to the
v1.5 format. It will raise exceptions if anything fails. | [
"This",
"upgrades",
"a",
"home",
"directory",
"that",
"was",
"in",
"the",
"v1",
".",
"1",
"format",
"to",
"the",
"v1",
".",
"5",
"format",
".",
"It",
"will",
"raise",
"exceptions",
"if",
"anything",
"fails",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L1041-L1049 | train |
hashicorp/vagrant | lib/vagrant/environment.rb | Vagrant.Environment.upgrade_v1_dotfile | 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 | 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 | [
"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"
] | This upgrades a Vagrant 1.0.x "dotfile" to the new V2 format.
This is a destructive process. Once the upgrade is complete, the
old dotfile is removed, and the environment becomes incompatible for
Vagrant 1.0 environments.
@param [Pathname] path The path to the dotfile | [
"This",
"upgrades",
"a",
"Vagrant",
"1",
".",
"0",
".",
"x",
"dotfile",
"to",
"the",
"new",
"V2",
"format",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/environment.rb#L1058-L1114 | train |
hashicorp/vagrant | lib/vagrant/guest.rb | Vagrant.Guest.detect! | 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 | 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 | [
"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"
] | This will detect the proper guest OS for the machine and set up
the class to actually execute capabilities. | [
"This",
"will",
"detect",
"the",
"proper",
"guest",
"OS",
"for",
"the",
"machine",
"and",
"set",
"up",
"the",
"class",
"to",
"actually",
"execute",
"capabilities",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/guest.rb#L32-L39 | train |
hashicorp/vagrant | lib/vagrant/vagrantfile.rb | Vagrant.Vagrantfile.machine | 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 | 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 | [
"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"
] | Initializes by loading a Vagrantfile.
@param [Config::Loader] loader Configuration loader that should
already be configured with the proper Vagrantfile locations.
This usually comes from {Vagrant::Environment}
@param [Array<Symbol>] keys The Vagrantfiles to load and the
order to load them in (keys within the loader).
Returns a {Machine} for the given name and provider that
is represented by this Vagrantfile.
@param [Symbol] name Name of the machine.
@param [Symbol] provider The provider the machine should
be backed by (required for provider overrides).
@param [BoxCollection] boxes BoxCollection to look up the
box Vagrantfile.
@param [Pathname] data_path Path where local machine data
can be stored.
@param [Environment] env The environment running this machine
@return [Machine] | [
"Initializes",
"by",
"loading",
"a",
"Vagrantfile",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/vagrantfile.rb#L45-L83 | train |
hashicorp/vagrant | lib/vagrant/vagrantfile.rb | Vagrant.Vagrantfile.machine_names_and_options | def machine_names_and_options
{}.tap do |r|
@config.vm.defined_vms.each do |name, subvm|
r[name] = subvm.options || {}
end
end
end | ruby | def machine_names_and_options
{}.tap do |r|
@config.vm.defined_vms.each do |name, subvm|
r[name] = subvm.options || {}
end
end
end | [
"def",
"machine_names_and_options",
"{",
"}",
".",
"tap",
"do",
"|",
"r",
"|",
"@config",
".",
"vm",
".",
"defined_vms",
".",
"each",
"do",
"|",
"name",
",",
"subvm",
"|",
"r",
"[",
"name",
"]",
"=",
"subvm",
".",
"options",
"||",
"{",
"}",
"end",
"end",
"end"
] | Returns a list of the machine names as well as the options that
were specified for that machine.
@return [Hash<Symbol, Hash>] | [
"Returns",
"a",
"list",
"of",
"the",
"machine",
"names",
"as",
"well",
"as",
"the",
"options",
"that",
"were",
"specified",
"for",
"that",
"machine",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/vagrantfile.rb#L273-L279 | train |
hashicorp/vagrant | lib/vagrant/vagrantfile.rb | Vagrant.Vagrantfile.primary_machine_name | 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 | 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 | [
"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"
] | Returns the name of the machine that is designated as the
"primary."
In the case of a single-machine environment, this is just the
single machine name. In the case of a multi-machine environment,
then this is the machine that is marked as primary, or nil if
no primary machine was specified.
@return [Symbol] | [
"Returns",
"the",
"name",
"of",
"the",
"machine",
"that",
"is",
"designated",
"as",
"the",
"primary",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/vagrantfile.rb#L290-L301 | train |
hashicorp/vagrant | lib/vagrant/machine.rb | Vagrant.Machine.action | 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 | 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 | [
"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"
] | Initialize a new machine.
@param [String] name Name of the virtual machine.
@param [Class] provider The provider backing this machine. This is
currently expected to be a V1 `provider` plugin.
@param [Object] provider_config The provider-specific configuration for
this machine.
@param [Hash] provider_options The provider-specific options from the
plugin definition.
@param [Object] config The configuration for this machine.
@param [Pathname] data_dir The directory where machine-specific data
can be stored. This directory is ensured to exist.
@param [Box] box The box that is backing this virtual machine.
@param [Environment] env The environment that this machine is a
part of.
This calls an action on the provider. The provider may or may not
actually implement the action.
@param [Symbol] name Name of the action to run.
@param [Hash] extra_env This data will be passed into the action runner
as extra data set on the environment hash for the middleware
runner. | [
"Initialize",
"a",
"new",
"machine",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine.rb#L162-L221 | train |
hashicorp/vagrant | lib/vagrant/machine.rb | Vagrant.Machine.action_raw | 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 | 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 | [
"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"
] | This calls a raw callable in the proper context of the machine using
the middleware stack.
@param [Symbol] name Name of the action
@param [Proc] callable
@param [Hash] extra_env Extra env for the action env.
@return [Hash] The resulting env | [
"This",
"calls",
"a",
"raw",
"callable",
"in",
"the",
"proper",
"context",
"of",
"the",
"machine",
"using",
"the",
"middleware",
"stack",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine.rb#L230-L239 | train |
hashicorp/vagrant | lib/vagrant/machine.rb | Vagrant.Machine.id= | 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 | 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 | [
"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"
] | This sets the unique ID associated with this machine. This will
persist this ID so that in the future Vagrant will be able to find
this machine again. The unique ID must be absolutely unique to the
virtual machine, and can be used by providers for finding the
actual machine associated with this instance.
**WARNING:** Only providers should ever use this method.
@param [String] value The ID. | [
"This",
"sets",
"the",
"unique",
"ID",
"associated",
"with",
"this",
"machine",
".",
"This",
"will",
"persist",
"this",
"ID",
"so",
"that",
"in",
"the",
"future",
"Vagrant",
"will",
"be",
"able",
"to",
"find",
"this",
"machine",
"again",
".",
"The",
"unique",
"ID",
"must",
"be",
"absolutely",
"unique",
"to",
"the",
"virtual",
"machine",
"and",
"can",
"be",
"used",
"by",
"providers",
"for",
"finding",
"the",
"actual",
"machine",
"associated",
"with",
"this",
"instance",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine.rb#L287-L373 | train |
hashicorp/vagrant | lib/vagrant/machine.rb | Vagrant.Machine.reload | 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 | 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 | [
"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"
] | This reloads the ID of the underlying machine. | [
"This",
"reloads",
"the",
"ID",
"of",
"the",
"underlying",
"machine",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine.rb#L394-L414 | train |
hashicorp/vagrant | lib/vagrant/machine.rb | Vagrant.Machine.state | 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 | 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 | [
"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"
] | Returns the state of this machine. The state is queried from the
backing provider, so it can be any arbitrary symbol.
@return [MachineState] | [
"Returns",
"the",
"state",
"of",
"this",
"machine",
".",
"The",
"state",
"is",
"queried",
"from",
"the",
"backing",
"provider",
"so",
"it",
"can",
"be",
"any",
"arbitrary",
"symbol",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine.rb#L531-L554 | train |
hashicorp/vagrant | lib/vagrant/machine.rb | Vagrant.Machine.check_cwd | 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 | 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 | [
"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"
] | Checks the current directory for a given machine
and displays a warning if that machine has moved
from its previous location on disk. If the machine
has moved, it prints a warning to the user. | [
"Checks",
"the",
"current",
"directory",
"for",
"a",
"given",
"machine",
"and",
"displays",
"a",
"warning",
"if",
"that",
"machine",
"has",
"moved",
"from",
"its",
"previous",
"location",
"on",
"disk",
".",
"If",
"the",
"machine",
"has",
"moved",
"it",
"prints",
"a",
"warning",
"to",
"the",
"user",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/machine.rb#L593-L613 | train |
hashicorp/vagrant | lib/vagrant/box_collection.rb | Vagrant.BoxCollection.all | 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 | 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 | [
"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"
] | This returns an array of all the boxes on the system, given by
their name and their provider.
@return [Array] Array of `[name, version, provider]` of the boxes
installed on this system. | [
"This",
"returns",
"an",
"array",
"of",
"all",
"the",
"boxes",
"on",
"the",
"system",
"given",
"by",
"their",
"name",
"and",
"their",
"provider",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L215-L263 | train |
hashicorp/vagrant | lib/vagrant/box_collection.rb | Vagrant.BoxCollection.find | 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 | 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 | [
"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"
] | Find a box in the collection with the given name and provider.
@param [String] name Name of the box (logical name).
@param [Array] providers Providers that the box implements.
@param [String] version Version constraints to adhere to. Example:
"~> 1.0" or "= 1.0, ~> 1.1"
@return [Box] The box found, or `nil` if not found. | [
"Find",
"a",
"box",
"in",
"the",
"collection",
"with",
"the",
"given",
"name",
"and",
"provider",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L272-L335 | train |
hashicorp/vagrant | lib/vagrant/box_collection.rb | Vagrant.BoxCollection.upgrade_v1_1_v1_5 | 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 | 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 | [
"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"
] | This upgrades a v1.1 - v1.4 box directory structure up to a v1.5
directory structure. This will raise exceptions if it fails in any
way. | [
"This",
"upgrades",
"a",
"v1",
".",
"1",
"-",
"v1",
".",
"4",
"box",
"directory",
"structure",
"up",
"to",
"a",
"v1",
".",
"5",
"directory",
"structure",
".",
"This",
"will",
"raise",
"exceptions",
"if",
"it",
"fails",
"in",
"any",
"way",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L340-L370 | train |
hashicorp/vagrant | lib/vagrant/box_collection.rb | Vagrant.BoxCollection.clean | def clean(name)
return false if exists?(name)
path = File.join(directory, dir_name(name))
FileUtils.rm_rf(path)
end | ruby | def clean(name)
return false if exists?(name)
path = File.join(directory, dir_name(name))
FileUtils.rm_rf(path)
end | [
"def",
"clean",
"(",
"name",
")",
"return",
"false",
"if",
"exists?",
"(",
"name",
")",
"path",
"=",
"File",
".",
"join",
"(",
"directory",
",",
"dir_name",
"(",
"name",
")",
")",
"FileUtils",
".",
"rm_rf",
"(",
"path",
")",
"end"
] | Cleans the directory for a box by removing the folders that are
empty. | [
"Cleans",
"the",
"directory",
"for",
"a",
"box",
"by",
"removing",
"the",
"folders",
"that",
"are",
"empty",
"."
] | c22a145c59790c098f95d50141d9afb48e1ef55f | https://github.com/hashicorp/vagrant/blob/c22a145c59790c098f95d50141d9afb48e1ef55f/lib/vagrant/box_collection.rb#L374-L378 | train |
Subsets and Splits