_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q10500
Match.Runner.prefixed_working_directory
train
def prefixed_working_directory(working_directory) if self.storage_mode == "git" return working_directory elsif self.storage_mode == "google_cloud" # We fall back to "*", which means certificates and profiles # from all teams that use this bucket would be installed. This is not ideal, but # unless the user provides a `team_id`, we can't know which one to use # This only happens if `readonly` is activated, and no `team_id` was provided @_folder_prefix ||= self.currently_used_team_id if @_folder_prefix.nil? # We use a `@_folder_prefix` variable, to keep state between multiple calls of this # method, as the value won't change. This way the warning is only printed once UI.important("Looks like you run `match` in `readonly` mode, and didn't provide a `team_id`. This will still work, however it is recommended to provide a `team_id` in your Appfile or Matchfile") @_folder_prefix = "*" end return File.join(working_directory, @_folder_prefix) else UI.crash!("No implementation for `prefixed_working_directory`") end end
ruby
{ "resource": "" }
q10501
Fastlane.SetupIos.find_and_setup_xcode_project
train
def find_and_setup_xcode_project(ask_for_scheme: true) UI.message("Parsing your local Xcode project to find the available schemes and the app identifier") config = {} # this is needed as the first method call will store information in there if self.project_path.end_with?("xcworkspace") config[:workspace] = self.project_path else config[:project] = self.project_path end FastlaneCore::Project.detect_projects(config) self.project = FastlaneCore::Project.new(config) if ask_for_scheme self.scheme = self.project.select_scheme(preferred_to_include: self.project.project_name) end self.app_identifier = self.project.default_app_identifier # These two vars need to be accessed in order to be set if self.app_identifier.to_s.length == 0 ask_for_bundle_identifier end end
ruby
{ "resource": "" }
q10502
Spaceship.Client.team_id=
train
def team_id=(team_id) # First, we verify the team actually exists, because otherwise iTC would return the # following confusing error message # # invalid content provider id # available_teams = teams.collect do |team| { team_id: (team["contentProvider"] || {})["contentProviderId"], team_name: (team["contentProvider"] || {})["name"] } end result = available_teams.find do |available_team| team_id.to_s == available_team[:team_id].to_s end unless result error_string = "Could not set team ID to '#{team_id}', only found the following available teams:\n\n#{available_teams.map { |team| "- #{team[:team_id]} (#{team[:team_name]})" }.join("\n")}\n" raise Tunes::Error.new, error_string end response = request(:post) do |req| req.url("ra/v1/session/webSession") req.body = { contentProviderId: team_id, dsId: user_detail_data.ds_id # https://github.com/fastlane/fastlane/issues/6711 }.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(response.body) @current_team_id = team_id end
ruby
{ "resource": "" }
q10503
Spaceship.Client.persistent_cookie_path
train
def persistent_cookie_path if ENV["SPACESHIP_COOKIE_PATH"] path = File.expand_path(File.join(ENV["SPACESHIP_COOKIE_PATH"], "spaceship", self.user, "cookie")) else [File.join(self.fastlane_user_dir, "spaceship"), "~/.spaceship", "/var/tmp/spaceship", "#{Dir.tmpdir}/spaceship"].each do |dir| dir_parts = File.split(dir) if directory_accessible?(File.expand_path(dir_parts.first)) path = File.expand_path(File.join(dir, self.user, "cookie")) break end end end return path end
ruby
{ "resource": "" }
q10504
Spaceship.Client.paging
train
def paging page = 0 results = [] loop do page += 1 current = yield(page) results += current break if (current || []).count < page_size # no more results end return results end
ruby
{ "resource": "" }
q10505
Spaceship.Client.login
train
def login(user = nil, password = nil) if user.to_s.empty? || password.to_s.empty? require 'credentials_manager/account_manager' puts("Reading keychain entry, because either user or password were empty") if Spaceship::Globals.verbose? keychain_entry = CredentialsManager::AccountManager.new(user: user, password: password) user ||= keychain_entry.user password = keychain_entry.password end if user.to_s.strip.empty? || password.to_s.strip.empty? raise NoUserCredentialsError.new, "No login data provided" end self.user = user @password = password begin do_login(user, password) # calls `send_login_request` in sub class (which then will redirect back here to `send_shared_login_request`, below) rescue InvalidUserCredentialsError => ex raise ex unless keychain_entry if keychain_entry.invalid_credentials login(user) else raise ex end end end
ruby
{ "resource": "" }
q10506
Spaceship.Client.send_shared_login_request
train
def send_shared_login_request(user, password) # Check if we have a cached/valid session # # Background: # December 4th 2017 Apple introduced a rate limit - which is of course fine by itself - # but unfortunately also rate limits successful logins. If you call multiple tools in a # lane (e.g. call match 5 times), this would lock you out of the account for a while. # By loading existing sessions and checking if they're valid, we're sending less login requests. # More context on why this change was necessary https://github.com/fastlane/fastlane/pull/11108 # # If there was a successful manual login before, we have a session on disk if load_session_from_file # Check if the session is still valid here begin # We use the olympus session to determine if the old session is still valid # As this will raise an exception if the old session has expired # If the old session is still valid, we don't have to do anything else in this method # that's why we return true return true if fetch_olympus_session rescue # If the `fetch_olympus_session` method raises an exception # we'll land here, and therefore continue doing a full login process # This happens if the session we loaded from the cache isn't valid any more # which is common, as the session automatically invalidates after x hours (we don't know x) # In this case we don't actually care about the exact exception, and why it was failing # because either way, we'll have to do a fresh login, where we do the actual error handling puts("Available session is not valid any more. Continuing with normal login.") end end # # The user can pass the session via environment variable (Mainly used in CI environments) if load_session_from_env # see above begin # see above return true if fetch_olympus_session rescue puts("Session loaded from environment variable is not valid. Continuing with normal login.") # see above end end # # After this point, we sure have no valid session any more and have to create a new one # data = { accountName: user, password: password, rememberMe: true } begin # The below workaround is only needed for 2 step verified machines # Due to escaping of cookie values we have a little workaround here # By default the cookie jar would generate the following header # DES5c148...=HSARM.......xaA/O69Ws/CHfQ==SRVT # However we need the following # DES5c148...="HSARM.......xaA/O69Ws/CHfQ==SRVT" # There is no way to get the cookie jar value with " around the value # so we manually modify the cookie (only this one) to be properly escaped # Afterwards we pass this value manually as a header # It's not enough to just modify @cookie, it needs to be done after self.cookie # as a string operation important_cookie = @cookie.store.entries.find { |a| a.name.include?("DES") } if important_cookie modified_cookie = self.cookie # returns a string of all cookies unescaped_important_cookie = "#{important_cookie.name}=#{important_cookie.value}" escaped_important_cookie = "#{important_cookie.name}=\"#{important_cookie.value}\"" modified_cookie.gsub!(unescaped_important_cookie, escaped_important_cookie) end response = request(:post) do |req| req.url("https://idmsa.apple.com/appleauth/auth/signin") req.body = data.to_json req.headers['Content-Type'] = 'application/json' req.headers['X-Requested-With'] = 'XMLHttpRequest' req.headers['X-Apple-Widget-Key'] = self.itc_service_key req.headers['Accept'] = 'application/json, text/javascript' req.headers["Cookie"] = modified_cookie if modified_cookie end rescue UnauthorizedAccessError raise InvalidUserCredentialsError.new, "Invalid username and password combination. Used '#{user}' as the username." end # Now we know if the login is successful or if we need to do 2 factor case response.status when 403 raise InvalidUserCredentialsError.new, "Invalid username and password combination. Used '#{user}' as the username." when 200 fetch_olympus_session return response when 409 # 2 step/factor is enabled for this account, first handle that handle_two_step_or_factor(response) # and then get the olympus session fetch_olympus_session return true else if (response.body || "").include?('invalid="true"') # User Credentials are wrong raise InvalidUserCredentialsError.new, "Invalid username and password combination. Used '#{user}' as the username." elsif response.status == 412 && AUTH_TYPES.include?(response.body["authType"]) # Need to acknowledge Apple ID and Privacy statement - https://github.com/fastlane/fastlane/issues/12577 # Looking for status of 412 might be enough but might be safer to keep looking only at what is being reported raise AppleIDAndPrivacyAcknowledgementNeeded.new, "Need to acknowledge to Apple's Apple ID and Privacy statement. Please manually log into https://appleid.apple.com (or https://appstoreconnect.apple.com) to acknowledge the statement." elsif (response['Set-Cookie'] || "").include?("itctx") raise "Looks like your Apple ID is not enabled for App Store Connect, make sure to be able to login online" else info = [response.body, response['Set-Cookie']] raise Tunes::Error.new, info.join("\n") end end end
ruby
{ "resource": "" }
q10507
Spaceship.Client.fetch_program_license_agreement_messages
train
def fetch_program_license_agreement_messages all_messages = [] messages_request = request(:get, "https://appstoreconnect.apple.com/olympus/v1/contractMessages") body = messages_request.body if body body = JSON.parse(body) if body.kind_of?(String) body.map do |messages| all_messages.push(messages["message"]) end end return all_messages end
ruby
{ "resource": "" }
q10508
Spaceship.Client.raise_insufficient_permission_error!
train
def raise_insufficient_permission_error!(additional_error_string: nil, caller_location: 2) # get the method name of the request that failed # `block in` is used very often for requests when surrounded for paging or retrying blocks # The ! is part of some methods when they modify or delete a resource, so we don't want to show it # Using `sub` instead of `delete` as we don't want to allow multiple matches calling_method_name = caller_locations(caller_location, 2).first.label.sub("block in", "").delete("!").strip # calling the computed property self.team_id can get us into an exception handling loop team_id = @current_team_id ? "(Team ID #{@current_team_id}) " : "" error_message = "User #{self.user} #{team_id}doesn't have enough permission for the following action: #{calling_method_name}" error_message += " (#{additional_error_string})" if additional_error_string.to_s.length > 0 raise InsufficientPermissions, error_message end
ruby
{ "resource": "" }
q10509
Spaceship.Client.send_request
train
def send_request(method, url_or_path, params, headers, &block) with_retry do response = @client.send(method, url_or_path, params, headers, &block) log_response(method, url_or_path, response, headers, &block) resp_hash = response.to_hash if resp_hash[:status] == 401 msg = "Auth lost" logger.warn(msg) raise UnauthorizedAccessError.new, "Unauthorized Access" end if response.body.to_s.include?("<title>302 Found</title>") raise AppleTimeoutError.new, "Apple 302 detected - this might be temporary server error, check https://developer.apple.com/system-status/ to see if there is a known downtime" end if response.body.to_s.include?("<h3>Bad Gateway</h3>") raise BadGatewayError.new, "Apple 502 detected - this might be temporary server error, try again later" end return response end end
ruby
{ "resource": "" }
q10510
Deliver.HtmlGenerator.render_relative_path
train
def render_relative_path(export_path, path) export_path = Pathname.new(export_path) path = Pathname.new(path).relative_path_from(export_path) return path.to_path end
ruby
{ "resource": "" }
q10511
Deliver.HtmlGenerator.render
train
def render(options, screenshots, export_path = nil) @screenshots = screenshots || [] @options = options @export_path = export_path @app_name = (options[:name]['en-US'] || options[:name].values.first) if options[:name] @app_name ||= options[:app].name @languages = options[:description].keys if options[:description] @languages ||= options[:app].latest_version.description.languages html_path = File.join(Deliver::ROOT, "lib/assets/summary.html.erb") html = ERB.new(File.read(html_path)).result(binding) # https://web.archive.org/web/20160430190141/www.rrn.dk/rubys-erb-templating-system export_path = File.join(export_path, "Preview.html") File.write(export_path, html) return export_path end
ruby
{ "resource": "" }
q10512
Fastlane.FastFile.sh
train
def sh(*command, log: true, error_callback: nil, &b) FastFile.sh(*command, log: log, error_callback: error_callback, &b) end
ruby
{ "resource": "" }
q10513
Snapshot.SimulatorLauncherBase.add_media
train
def add_media(device_types, media_type, paths) media_type = media_type.to_s device_types.each do |device_type| UI.verbose("Adding #{media_type}s to #{device_type}...") device_udid = TestCommandGenerator.device_udid(device_type) UI.message("Launch Simulator #{device_type}") Helper.backticks("xcrun instruments -w #{device_udid} &> /dev/null") paths.each do |path| UI.message("Adding '#{path}'") # Attempting addmedia since addphoto and addvideo are deprecated output = Helper.backticks("xcrun simctl addmedia #{device_udid} #{path.shellescape} &> /dev/null") # Run legacy addphoto and addvideo if addmedia isn't found # Output will be empty strin gif it was a success # Output will contain "usage: simctl" if command not found if output.include?('usage: simctl') Helper.backticks("xcrun simctl add#{media_type} #{device_udid} #{path.shellescape} &> /dev/null") end end end end
ruby
{ "resource": "" }
q10514
Fastlane.Setup.append_lane
train
def append_lane(lane) lane.compact! # remove nil values new_lines = "\n\n" if self.is_swift_fastfile new_lines = "" unless self.fastfile_content.include?("lane() {") # the first lane we don't want new lines self.fastfile_content.gsub!("[[LANES]]", "#{new_lines}\t#{lane.join("\n\t")}[[LANES]]") else new_lines = "" unless self.fastfile_content.include?("lane :") # the first lane we don't want new lines self.fastfile_content.gsub!("[[LANES]]", "#{new_lines} #{lane.join("\n ")}[[LANES]]") end end
ruby
{ "resource": "" }
q10515
Fastlane.Setup.add_or_update_gemfile
train
def add_or_update_gemfile(update_gemfile_if_needed: false) if gemfile_exists? ensure_gemfile_valid!(update_gemfile_if_needed: update_gemfile_if_needed) else if update_gemfile_if_needed || UI.confirm("It is recommended to run fastlane with a Gemfile set up, do you want fastlane to create one for you?") setup_gemfile! end end return gemfile_path end
ruby
{ "resource": "" }
q10516
CredentialsManager.CLI.run
train
def run program :name, 'CredentialsManager' program :version, Fastlane::VERSION program :description, 'Manage credentials for fastlane tools.' # Command to add entry to Keychain command :add do |c| c.syntax = 'fastlane fastlane-credentials add' c.description = 'Adds a fastlane credential to the keychain.' c.option('--username username', String, 'Username to add.') c.option('--password password', String, 'Password to add.') c.action do |args, options| username = options.username || ask('Username: ') password = options.password || ask('Password: ') { |q| q.echo = '*' } add(username, password) puts("Credential #{username}:#{'*' * password.length} added to keychain.") end end # Command to remove credential from Keychain command :remove do |c| c.syntax = 'fastlane fastlane-credentials remove' c.description = 'Removes a fastlane credential from the keychain.' c.option('--username username', String, 'Username to remove.') c.action do |args, options| username = options.username || ask('Username: ') remove(username) end end run! end
ruby
{ "resource": "" }
q10517
CredentialsManager.CLI.add
train
def add(username, password) CredentialsManager::AccountManager.new( user: username, password: password ).add_to_keychain end
ruby
{ "resource": "" }
q10518
Deliver.Setup.generate_deliver_file
train
def generate_deliver_file(deliver_path, options) v = options[:app].latest_version metadata_path = options[:metadata_path] || File.join(deliver_path, 'metadata') generate_metadata_files(v, metadata_path) # Generate the final Deliverfile here return File.read(deliverfile_path) end
ruby
{ "resource": "" }
q10519
Fastlane.PluginInfoCollector.gem_name_taken?
train
def gem_name_taken?(name) require 'open-uri' require 'json' url = "https://rubygems.org/api/v1/gems/#{name}.json" response = JSON.parse(open(url).read) return !!response['version'] rescue false end
ruby
{ "resource": "" }
q10520
Fastlane.PluginInfoCollector.fix_plugin_name
train
def fix_plugin_name(name) name = name.to_s.downcase fixes = { /[\- ]/ => '_', # dashes and spaces become underscores /[^a-z0-9_]/ => '', # anything other than lower case letters, numbers and underscores is removed /fastlane[_]?/ => '', # 'fastlane' or 'fastlane_' is removed /plugin[_]?/ => '' # 'plugin' or 'plugin_' is removed } fixes.each do |regex, replacement| name = name.gsub(regex, replacement) end name end
ruby
{ "resource": "" }
q10521
Sigh.Resign.installed_identities
train
def installed_identities available = request_valid_identities ids = {} available.split("\n").each do |current| begin sha1 = current.match(/[a-zA-Z0-9]{40}/).to_s name = current.match(/.*\"(.*)\"/)[1] ids[sha1] = name rescue nil end # the last line does not match end ids end
ruby
{ "resource": "" }
q10522
Supply.Listing.save
train
def save @google_api.update_listing_for_language(language: language, title: title, short_description: short_description, full_description: full_description, video: video) end
ruby
{ "resource": "" }
q10523
CredentialsManager.AccountManager.invalid_credentials
train
def invalid_credentials(force: false) puts("The login credentials for '#{user}' seem to be wrong".red) if fetch_password_from_env puts("The password was taken from the environment variable") puts("Please make sure it is correct") return false end if force || agree("Do you want to re-enter your password? (y/n)", true) puts("Removing Keychain entry for user '#{user}'...".yellow) if mac? remove_from_keychain ask_for_login return true end false end
ruby
{ "resource": "" }
q10524
CredentialsManager.AccountManager.options
train
def options hash = {} hash[:p] = ENV["FASTLANE_PATH"] if ENV["FASTLANE_PATH"] hash[:P] = ENV["FASTLANE_PORT"] if ENV["FASTLANE_PORT"] hash[:r] = ENV["FASTLANE_PROTOCOL"] if ENV["FASTLANE_PROTOCOL"] hash.empty? ? nil : hash end
ruby
{ "resource": "" }
q10525
Fastlane.InspectorReporter.inspector_started_query
train
def inspector_started_query(query, inspector) puts("") puts("Looking for related GitHub issues on #{inspector.repo_owner}/#{inspector.repo_name}...") puts("Search query: #{query}") if FastlaneCore::Globals.verbose? puts("") end
ruby
{ "resource": "" }
q10526
Fastlane.InspectorReporter.inspector_successfully_received_report
train
def inspector_successfully_received_report(report, inspector) report.issues[0..(NUMBER_OF_ISSUES_INLINE - 1)].each { |issue| print_issue_full(issue) } if report.issues.count > NUMBER_OF_ISSUES_INLINE report.url.sub!('\'', '%27') puts("and #{report.total_results - NUMBER_OF_ISSUES_INLINE} more at: #{report.url}") puts("") end print_open_link_hint end
ruby
{ "resource": "" }
q10527
Spaceship.TunesClient.select_team
train
def select_team(team_id: nil, team_name: nil) t_id = (team_id || ENV['FASTLANE_ITC_TEAM_ID'] || '').strip t_name = (team_name || ENV['FASTLANE_ITC_TEAM_NAME'] || '').strip if t_name.length > 0 && t_id.length.zero? # we prefer IDs over names, they are unique puts("Looking for App Store Connect Team with name #{t_name}") if Spaceship::Globals.verbose? teams.each do |t| t_id = t['contentProvider']['contentProviderId'].to_s if t['contentProvider']['name'].casecmp(t_name).zero? end puts("Could not find team with name '#{t_name}', trying to fallback to default team") if t_id.length.zero? end t_id = teams.first['contentProvider']['contentProviderId'].to_s if teams.count == 1 if t_id.length > 0 puts("Looking for App Store Connect Team with ID #{t_id}") if Spaceship::Globals.verbose? # actually set the team id here self.team_id = t_id return self.team_id end # user didn't specify a team... #thisiswhywecanthavenicethings loop do puts("Multiple #{'App Store Connect teams'.yellow} found, please enter the number of the team you want to use: ") if ENV["FASTLANE_HIDE_TEAM_INFORMATION"].to_s.length == 0 puts("Note: to automatically choose the team, provide either the App Store Connect Team ID, or the Team Name in your fastlane/Appfile:") puts("Alternatively you can pass the team name or team ID using the `FASTLANE_ITC_TEAM_ID` or `FASTLANE_ITC_TEAM_NAME` environment variable") first_team = teams.first["contentProvider"] puts("") puts(" itc_team_id \"#{first_team['contentProviderId']}\"") puts("") puts("or") puts("") puts(" itc_team_name \"#{first_team['name']}\"") puts("") end # We're not using highline here, as spaceship doesn't have a dependency to fastlane_core or highline teams.each_with_index do |team, i| puts("#{i + 1}) \"#{team['contentProvider']['name']}\" (#{team['contentProvider']['contentProviderId']})") end unless Spaceship::Client::UserInterface.interactive? puts("Multiple teams found on App Store Connect, Your Terminal is running in non-interactive mode! Cannot continue from here.") puts("Please check that you set FASTLANE_ITC_TEAM_ID or FASTLANE_ITC_TEAM_NAME to the right value.") raise "Multiple App Store Connect Teams found; unable to choose, terminal not interactive!" end selected = ($stdin.gets || '').strip.to_i - 1 team_to_use = teams[selected] if selected >= 0 if team_to_use self.team_id = team_to_use['contentProvider']['contentProviderId'].to_s # actually set the team id here return self.team_id end end end
ruby
{ "resource": "" }
q10528
Spaceship.TunesClient.fetch_errors_in_data
train
def fetch_errors_in_data(data_section: nil, sub_section_name: nil, keys: nil) if data_section && sub_section_name sub_section = data_section[sub_section_name] else sub_section = data_section end unless sub_section return {} end error_map = {} keys.each do |key| errors = sub_section.fetch(key, []) error_map[key] = errors if errors.count > 0 end return error_map end
ruby
{ "resource": "" }
q10529
Spaceship.TunesClient.create_application!
train
def create_application!(name: nil, primary_language: nil, version: nil, sku: nil, bundle_id: nil, bundle_id_suffix: nil, company_name: nil, platform: nil, itunes_connect_users: nil) puts("The `version` parameter is deprecated. Use `Spaceship::Tunes::Application.ensure_version!` method instead") if version # First, we need to fetch the data from Apple, which we then modify with the user's values primary_language ||= "English" platform ||= "ios" r = request(:get, "ra/apps/create/v2/?platformString=#{platform}") data = parse_response(r, 'data') # Now fill in the values we have # some values are nil, that's why there is a hash data['name'] = { value: name } data['bundleId'] = { value: bundle_id } data['primaryLanguage'] = { value: primary_language } data['primaryLocaleCode'] = { value: primary_language.to_itc_locale } data['vendorId'] = { value: sku } data['bundleIdSuffix'] = { value: bundle_id_suffix } data['companyName'] = { value: company_name } if company_name data['enabledPlatformsForCreation'] = { value: [platform] } data['initialPlatform'] = platform data['enabledPlatformsForCreation'] = { value: [platform] } unless itunes_connect_users.nil? data['iTunesConnectUsers']['grantedAllUsers'] = false data['iTunesConnectUsers']['grantedUsers'] = data['iTunesConnectUsers']['availableUsers'].select { |user| itunes_connect_users.include?(user['username']) } end # Now send back the modified hash r = request(:post) do |req| req.url('ra/apps/create/v2') req.body = data.to_json req.headers['Content-Type'] = 'application/json' end data = parse_response(r, 'data') handle_itc_response(data) end
ruby
{ "resource": "" }
q10530
Spaceship.TunesClient.pricing_tiers
train
def pricing_tiers @pricing_tiers ||= begin r = request(:get, 'ra/apps/pricing/matrix') data = parse_response(r, 'data')['pricingTiers'] data.map { |tier| Spaceship::Tunes::PricingTier.factory(tier) } end end
ruby
{ "resource": "" }
q10531
Spaceship.TunesClient.supported_territories
train
def supported_territories data = supported_countries data.map { |country| Spaceship::Tunes::Territory.factory(country) } end
ruby
{ "resource": "" }
q10532
Spaceship.TunesClient.upload_watch_icon
train
def upload_watch_icon(app_version, upload_image) raise "app_version is required" unless app_version raise "upload_image is required" unless upload_image du_client.upload_watch_icon(app_version, upload_image, content_provider_id, sso_token_for_image) end
ruby
{ "resource": "" }
q10533
Spaceship.TunesClient.upload_purchase_review_screenshot
train
def upload_purchase_review_screenshot(app_id, upload_image) data = du_client.upload_purchase_review_screenshot(app_id, upload_image, content_provider_id, sso_token_for_image) { "value" => { "assetToken" => data["token"], "sortOrder" => 0, "type" => du_client.get_picture_type(upload_image), "originalFileName" => upload_image.file_name, "size" => data["length"], "height" => data["height"], "width" => data["width"], "checksum" => data["md5"] } } end
ruby
{ "resource": "" }
q10534
Spaceship.TunesClient.upload_screenshot
train
def upload_screenshot(app_version, upload_image, device, is_messages) raise "app_version is required" unless app_version raise "upload_image is required" unless upload_image raise "device is required" unless device du_client.upload_screenshot(app_version, upload_image, content_provider_id, sso_token_for_image, device, is_messages) end
ruby
{ "resource": "" }
q10535
Spaceship.TunesClient.upload_messages_screenshot
train
def upload_messages_screenshot(app_version, upload_image, device) raise "app_version is required" unless app_version raise "upload_image is required" unless upload_image raise "device is required" unless device du_client.upload_messages_screenshot(app_version, upload_image, content_provider_id, sso_token_for_image, device) end
ruby
{ "resource": "" }
q10536
Spaceship.TunesClient.upload_trailer_preview
train
def upload_trailer_preview(app_version, upload_trailer_preview, device) raise "app_version is required" unless app_version raise "upload_trailer_preview is required" unless upload_trailer_preview raise "device is required" unless device du_client.upload_trailer_preview(app_version, upload_trailer_preview, content_provider_id, sso_token_for_image, device) end
ruby
{ "resource": "" }
q10537
Spaceship.TunesClient.ref_data
train
def ref_data r = request(:get, '/WebObjects/iTunesConnect.woa/ra/apps/version/ref') data = parse_response(r, 'data') Spaceship::Tunes::AppVersionRef.factory(data) end
ruby
{ "resource": "" }
q10538
Spaceship.TunesClient.all_build_trains
train
def all_build_trains(app_id: nil, platform: 'ios') platform = 'ios' if platform.nil? r = request(:get, "ra/apps/#{app_id}/buildHistory?platform=#{platform}") handle_itc_response(r.body) end
ruby
{ "resource": "" }
q10539
Spaceship.TunesClient.update_iap_family!
train
def update_iap_family!(app_id: nil, family_id: nil, data: nil) with_tunes_retry do r = request(:put) do |req| req.url("ra/apps/#{app_id}/iaps/family/#{family_id}/") req.body = data.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(r.body) end end
ruby
{ "resource": "" }
q10540
Spaceship.TunesClient.update_iap!
train
def update_iap!(app_id: nil, purchase_id: nil, data: nil) with_tunes_retry do r = request(:put) do |req| req.url("ra/apps/#{app_id}/iaps/#{purchase_id}") req.body = data.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(r.body) end end
ruby
{ "resource": "" }
q10541
Spaceship.TunesClient.create_iap!
train
def create_iap!(app_id: nil, type: nil, versions: nil, reference_name: nil, product_id: nil, cleared_for_sale: true, review_notes: nil, review_screenshot: nil, pricing_intervals: nil, family_id: nil, subscription_duration: nil, subscription_free_trial: nil) # Load IAP Template based on Type type ||= "consumable" r = request(:get, "ra/apps/#{app_id}/iaps/#{type}/template") data = parse_response(r, 'data') # Now fill in the values we have # some values are nil, that's why there is a hash data['familyId'] = family_id.to_s if family_id data['productId'] = { value: product_id } data['referenceName'] = { value: reference_name } data['clearedForSale'] = { value: cleared_for_sale } data['pricingDurationType'] = { value: subscription_duration } if subscription_duration data['freeTrialDurationType'] = { value: subscription_free_trial } if subscription_free_trial # pricing tier if pricing_intervals data['pricingIntervals'] = [] pricing_intervals.each do |interval| data['pricingIntervals'] << { value: { country: interval[:country] || "WW", tierStem: interval[:tier].to_s, priceTierEndDate: interval[:end_date], priceTierEffectiveDate: interval[:begin_date] } } end end versions_array = [] versions.each do |k, v| versions_array << { value: { description: { value: v[:description] }, name: { value: v[:name] }, localeCode: k.to_s } } end data["versions"][0]["details"]["value"] = versions_array data['versions'][0]["reviewNotes"] = { value: review_notes } if review_screenshot # Upload Screenshot: upload_file = UploadFile.from_path(review_screenshot) screenshot_data = upload_purchase_review_screenshot(app_id, upload_file) data["versions"][0]["reviewScreenshot"] = screenshot_data end # Now send back the modified hash r = request(:post) do |req| req.url("ra/apps/#{app_id}/iaps") req.body = data.to_json req.headers['Content-Type'] = 'application/json' end handle_itc_response(r.body) end
ruby
{ "resource": "" }
q10542
Spaceship.TunesClient.group_for_view_by
train
def group_for_view_by(view_by, measures) if view_by.nil? || measures.nil? return nil else return { metric: measures.first, dimension: view_by, rank: "DESCENDING", limit: 3 } end end
ruby
{ "resource": "" }
q10543
Snapshot.SimulatorLauncherXcode8.run_for_device_and_language
train
def run_for_device_and_language(language, locale, device, launch_arguments, retries = 0) return launch_one_at_a_time(language, locale, device, launch_arguments) rescue => ex UI.error(ex.to_s) # show the reason for failure to the user, but still maybe retry if retries < launcher_config.number_of_retries UI.important("Tests failed, re-trying #{retries + 1} out of #{launcher_config.number_of_retries + 1} times") run_for_device_and_language(language, locale, device, launch_arguments, retries + 1) else UI.error("Backtrace:\n\t#{ex.backtrace.join("\n\t")}") if FastlaneCore::Globals.verbose? self.collected_errors << ex raise ex if launcher_config.stop_after_first_error return false # for the results end end
ruby
{ "resource": "" }
q10544
Snapshot.SimulatorLauncherXcode8.launch_one_at_a_time
train
def launch_one_at_a_time(language, locale, device_type, launch_arguments) prepare_for_launch([device_type], language, locale, launch_arguments) add_media([device_type], :photo, launcher_config.add_photos) if launcher_config.add_photos add_media([device_type], :video, launcher_config.add_videos) if launcher_config.add_videos open_simulator_for_device(device_type) command = TestCommandGeneratorXcode8.generate(device_type: device_type, language: language, locale: locale) if locale UI.header("#{device_type} - #{language} (#{locale})") else UI.header("#{device_type} - #{language}") end execute(command: command, language: language, locale: locale, device_type: device_type, launch_args: launch_arguments) raw_output = File.read(TestCommandGeneratorXcode8.xcodebuild_log_path(device_type: device_type, language: language, locale: locale)) dir_name = locale || language return Collector.fetch_screenshots(raw_output, dir_name, device_type, launch_arguments.first) end
ruby
{ "resource": "" }
q10545
FastlaneCore.Configuration.verify_default_value_matches_verify_block
train
def verify_default_value_matches_verify_block @available_options.each do |item| next unless item.verify_block && item.default_value begin unless @values[item.key] # this is important to not verify if there already is a value there item.verify_block.call(item.default_value) end rescue => ex UI.error(ex) UI.user_error!("Invalid default value for #{item.key}, doesn't match verify_block") end end end
ruby
{ "resource": "" }
q10546
FastlaneCore.Configuration.load_configuration_file
train
def load_configuration_file(config_file_name = nil, block_for_missing = nil, skip_printing_values = false) return unless config_file_name self.config_file_name = config_file_name path = FastlaneCore::Configuration.find_configuration_file_path(config_file_name: config_file_name) return if path.nil? begin configuration_file = ConfigurationFile.new(self, path, block_for_missing, skip_printing_values) options = configuration_file.options rescue FastlaneCore::ConfigurationFile::ExceptionWhileParsingError => e options = e.recovered_options wrapped_exception = e.wrapped_exception end # Make sure all the values set in the config file pass verification options.each do |key, val| option = self.verify_options_key!(key) option.verify!(val) end # Merge the new options into the old ones, keeping all previously set keys self.config_file_options = options.merge(self.config_file_options) verify_conflicts # important, since user can set conflicting options in configuration file # Now that everything is verified, re-raise an exception that was raised in the config file raise wrapped_exception unless wrapped_exception.nil? configuration_file end
ruby
{ "resource": "" }
q10547
Fastlane.OtherAction.method_missing
train
def method_missing(method_sym, *arguments, &_block) # We have to go inside the fastlane directory # since in the fastlane runner.rb we do the following # custom_dir = ".." # Dir.chdir(custom_dir) do # this goes one folder up, since we're inside the "fastlane" # folder at that point # Since we call an action from an action we need to go inside # the fastlane folder too self.runner.trigger_action_by_name(method_sym, FastlaneCore::FastlaneFolder.path, true, *arguments) end
ruby
{ "resource": "" }
q10548
Produce.ItunesConnect.language
train
def language @language = Produce.config[:language] converted = Spaceship::Tunes::LanguageConverter.from_itc_readable_to_itc(@language) @language = converted if converted # overwrite it with the actual value unless AvailableDefaultLanguages.all_languages.include?(@language) UI.user_error!("Please enter one of available languages: #{AvailableDefaultLanguages.all_languages}") end return @language end
ruby
{ "resource": "" }
q10549
Fastlane.Runner.find_alias
train
def find_alias(action_name) Actions.alias_actions.each do |key, v| next unless Actions.alias_actions[key] next unless Actions.alias_actions[key].include?(action_name) return key end nil end
ruby
{ "resource": "" }
q10550
Fastlane.Runner.trigger_action_by_name
train
def trigger_action_by_name(method_sym, custom_dir, from_action, *arguments) # First, check if there is a predefined method in the actions folder class_ref = class_reference_from_action_name(method_sym) unless class_ref class_ref = class_reference_from_action_alias(method_sym) # notify action that it has been used by alias if class_ref.respond_to?(:alias_used) orig_action = method_sym.to_s arguments = [{}] if arguments.empty? class_ref.alias_used(orig_action, arguments.first) end end # It's important to *not* have this code inside the rescue block # otherwise all NameErrors will be caught and the error message is # confusing begin return self.try_switch_to_lane(method_sym, arguments) rescue LaneNotAvailableError # We don't actually handle this here yet # We just try to use a user configured lane first # and only if there is none, we're gonna check for the # built-in actions end if class_ref if class_ref.respond_to?(:run) # Action is available, now execute it return self.execute_action(method_sym, class_ref, arguments, custom_dir: custom_dir, from_action: from_action) else UI.user_error!("Action '#{method_sym}' of class '#{class_name}' was found, but has no `run` method.") end end # No lane, no action, let's at least show the correct error message if Fastlane.plugin_manager.plugin_is_added_as_dependency?(PluginManager.plugin_prefix + method_sym.to_s) # That's a plugin, but for some reason we can't find it UI.user_error!("Plugin '#{method_sym}' was not properly loaded, make sure to follow the plugin docs for troubleshooting: #{PluginManager::TROUBLESHOOTING_URL}") elsif Fastlane::Actions.formerly_bundled_actions.include?(method_sym.to_s) # This was a formerly bundled action which is now a plugin. UI.verbose(caller.join("\n")) UI.user_error!("The action '#{method_sym}' is no longer bundled with fastlane. You can install it using `fastlane add_plugin #{method_sym}`") else # So there is no plugin under that name, so just show the error message generated by the lane switch UI.verbose(caller.join("\n")) UI.user_error!("Could not find action, lane or variable '#{method_sym}'. Check out the documentation for more details: https://docs.fastlane.tools/actions") end end
ruby
{ "resource": "" }
q10551
Fastlane.Runner.add_lane
train
def add_lane(lane, override = false) lanes[lane.platform] ||= {} if !override && lanes[lane.platform][lane.name] UI.user_error!("Lane '#{lane.name}' was defined multiple times!") end lanes[lane.platform][lane.name] = lane end
ruby
{ "resource": "" }
q10552
Fastlane.CommandsGenerator.ensure_fastfile
train
def ensure_fastfile return true if FastlaneCore::FastlaneFolder.setup? create = UI.confirm('Could not find fastlane in current directory. Make sure to have your fastlane configuration files inside a folder called "fastlane". Would you like to set fastlane up?') if create Fastlane::Setup.start end return false end
ruby
{ "resource": "" }
q10553
Deliver.Runner.verify_version
train
def verify_version app_version = options[:app_version] UI.message("Making sure the latest version on App Store Connect matches '#{app_version}' from the ipa file...") changed = options[:app].ensure_version!(app_version, platform: options[:platform]) if changed UI.success("Successfully set the version to '#{app_version}'") else UI.success("'#{app_version}' is the latest version on App Store Connect") end end
ruby
{ "resource": "" }
q10554
Deliver.Runner.upload_metadata
train
def upload_metadata upload_metadata = UploadMetadata.new upload_screenshots = UploadScreenshots.new # First, collect all the things for the HTML Report screenshots = upload_screenshots.collect_screenshots(options) upload_metadata.load_from_filesystem(options) # Assign "default" values to all languages upload_metadata.assign_defaults(options) # Handle app icon / watch icon prepare_app_icons(options) # Validate validate_html(screenshots) # Commit upload_metadata.upload(options) upload_screenshots.upload(options, screenshots) UploadPriceTier.new.upload(options) UploadAssets.new.upload(options) # e.g. app icon end
ruby
{ "resource": "" }
q10555
Deliver.Runner.upload_binary
train
def upload_binary UI.message("Uploading binary to App Store Connect") if options[:ipa] package_path = FastlaneCore::IpaUploadPackageBuilder.new.generate( app_id: options[:app].apple_id, ipa_path: options[:ipa], package_path: "/tmp", platform: options[:platform] ) elsif options[:pkg] package_path = FastlaneCore::PkgUploadPackageBuilder.new.generate( app_id: options[:app].apple_id, pkg_path: options[:pkg], package_path: "/tmp", platform: options[:platform] ) end transporter = transporter_for_selected_team result = transporter.upload(options[:app].apple_id, package_path) UI.user_error!("Could not upload binary to App Store Connect. Check out the error above", show_github_issues: true) unless result end
ruby
{ "resource": "" }
q10556
Supply.Uploader.upload_binary_data
train
def upload_binary_data(apk_path) apk_version_code = nil if apk_path UI.message("Preparing apk at path '#{apk_path}' for upload...") apk_version_code = client.upload_apk(apk_path) UI.user_error!("Could not upload #{apk_path}") unless apk_version_code if Supply.config[:obb_main_references_version] && Supply.config[:obb_main_file_size] update_obb(apk_version_code, 'main', Supply.config[:obb_main_references_version], Supply.config[:obb_main_file_size]) end if Supply.config[:obb_patch_references_version] && Supply.config[:obb_patch_file_size] update_obb(apk_version_code, 'patch', Supply.config[:obb_patch_references_version], Supply.config[:obb_patch_file_size]) end upload_obbs(apk_path, apk_version_code) if metadata_path all_languages.each do |language| next if language.start_with?('.') # e.g. . or .. or hidden folders upload_changelog(language, apk_version_code) end end else UI.message("No apk file found, you can pass the path to your apk using the `apk` option") end apk_version_code end
ruby
{ "resource": "" }
q10557
Supply.Uploader.all_languages
train
def all_languages Dir.entries(metadata_path) .select { |f| File.directory?(File.join(metadata_path, f)) } .reject { |f| f.start_with?('.') } .sort { |x, y| x <=> y } end
ruby
{ "resource": "" }
q10558
Supply.Uploader.upload_obbs
train
def upload_obbs(apk_path, apk_version_code) expansion_paths = find_obbs(apk_path) ['main', 'patch'].each do |type| if expansion_paths[type] upload_obb(expansion_paths[type], type, apk_version_code) end end end
ruby
{ "resource": "" }
q10559
FastlaneCore.CommanderGenerator.generate
train
def generate(options, command: nil) # First, enable `always_trace`, to show the stack trace always_trace! used_switches = [] options.each do |option| next if option.description.to_s.empty? # "private" options next unless option.display_in_shell short_switch = option.short_option key = option.key validate_short_switch(used_switches, short_switch, key) type = option.data_type # We added type: Hash to code generation, but Ruby's OptionParser doesn't like that # so we need to switch that to something that is supported, luckily, we have an `is_string` # property and if that is false, we'll default to nil if type == Hash type = option.is_string ? String : nil end # Boolean is a fastlane thing, it's either TrueClass, or FalseClass, but we won't know # that until runtime, so nil is the best we get if type == Fastlane::Boolean type = nil end # This is an important bit of trickery to solve the boolean option situation. # # Typically, boolean command line flags do not accept trailing values. If the flag # is present, the value is true, if it is missing, the value is false. fastlane # supports this style of flag. For example, you can specify a flag like `--clean`, # and the :clean option will be true. # # However, fastlane also supports another boolean flag style that accepts trailing # values much like options for Strings and other value types. That looks like # `--include_bitcode false` The problem is that this does not work out of the box # for Commander and OptionsParser. So, we need to get tricky. # # The value_appendix below acts as a placeholder in the switch definition that # states that we expect to have a trailing value for our options. When an option # declares a data type, we use the name of that data type in all caps like: # "--devices ARRAY". When the data type is nil, this implies that we're going # to be doing some special handling on that value. One special thing we do # automatically in Configuration is to coerce special Strings into boolean values. # # If the data type is nil, the trick we do is to specify a value placeholder, but # we wrap it in [] brackets to mark it as optional. That means that the trailing # value may or may not be present for this flag. If the flag is present, but the # value is not, we get a value of `true`. Perfect for the boolean flag base-case! # If the value is there, we'll actually get it back as a String, which we can # later coerce into a boolean. # # In this way we support handling boolean flags with or without trailing values. value_appendix = (type || '[VALUE]').to_s.upcase long_switch = "--#{option.key} #{value_appendix}" description = option.description description += " (#{option.env_name})" unless option.env_name.to_s.empty? # We compact this array here to remove the short_switch variable if it is nil. # Passing a nil value to global_option has been shown to create problems with # option parsing! # # See: https://github.com/fastlane/fastlane_core/pull/89 # # If we don't have a data type for this option, we tell it to act like a String. # This allows us to get a reasonable value for boolean options that can be # automatically coerced or otherwise handled by the ConfigItem for others. args = [short_switch, long_switch, (type || String), description].compact if command command.option(*args) else # This is the call to Commander to set up the option we've been building. global_option(*args) end end end
ruby
{ "resource": "" }
q10560
Scan.XCPrettyReporterOptionsGenerator.generate_reporter_options
train
def generate_reporter_options reporter = [] valid_types = @output_types & SUPPORTED_REPORT_TYPES valid_types.each do |raw_type| type = raw_type.strip output_path = File.join(File.expand_path(@output_directory), determine_output_file_name(type)) reporter << "--report #{type}" reporter << "--output '#{output_path}'" if type == "html" && @open_report Scan.cache[:open_html_report_path] = output_path end end # adds another junit reporter in case the user does not specify one # this will be used to generate a results table and then discarded require 'tempfile' @temp_junit_report = Tempfile.new("junit_report") Scan.cache[:temp_junit_report] = @temp_junit_report.path reporter << "--report junit" reporter << "--output '#{Scan.cache[:temp_junit_report]}'" return reporter end
ruby
{ "resource": "" }
q10561
Supply.Client.abort_current_edit
train
def abort_current_edit ensure_active_edit! call_google_api { client.delete_edit(current_package_name, current_edit.id) } self.current_edit = nil self.current_package_name = nil end
ruby
{ "resource": "" }
q10562
Supply.Client.commit_current_edit!
train
def commit_current_edit! ensure_active_edit! call_google_api { client.commit_edit(current_package_name, current_edit.id) } self.current_edit = nil self.current_package_name = nil end
ruby
{ "resource": "" }
q10563
Supply.Client.listing_for_language
train
def listing_for_language(language) ensure_active_edit! begin result = client.get_listing( current_package_name, current_edit.id, language ) return Listing.new(self, language, result) rescue Google::Apis::ClientError => e return Listing.new(self, language) if e.status_code == 404 # create a new empty listing raise end end
ruby
{ "resource": "" }
q10564
Supply.Client.apks_version_codes
train
def apks_version_codes ensure_active_edit! result = call_google_api { client.list_apks(current_package_name, current_edit.id) } return Array(result.apks).map(&:version_code) end
ruby
{ "resource": "" }
q10565
Supply.Client.aab_version_codes
train
def aab_version_codes ensure_active_edit! result = call_google_api { client.list_edit_bundles(current_package_name, current_edit.id) } return Array(result.bundles).map(&:version_code) end
ruby
{ "resource": "" }
q10566
Supply.Client.track_version_codes
train
def track_version_codes(track) ensure_active_edit! begin result = client.get_track( current_package_name, current_edit.id, track ) return result.version_codes || [] rescue Google::Apis::ClientError => e return [] if e.status_code == 404 && e.to_s.include?("trackEmpty") raise end end
ruby
{ "resource": "" }
q10567
Fastlane.PluginManager.available_gems
train
def available_gems return [] unless gemfile_path dsl = Bundler::Dsl.evaluate(gemfile_path, nil, true) return dsl.dependencies.map(&:name) end
ruby
{ "resource": "" }
q10568
Fastlane.PluginManager.plugin_is_added_as_dependency?
train
def plugin_is_added_as_dependency?(plugin_name) UI.user_error!("fastlane plugins must start with '#{self.class.plugin_prefix}' string") unless plugin_name.start_with?(self.class.plugin_prefix) return available_plugins.include?(plugin_name) end
ruby
{ "resource": "" }
q10569
Fastlane.PluginManager.attach_plugins_to_gemfile!
train
def attach_plugins_to_gemfile!(path_to_gemfile) content = gemfile_content || (AUTOGENERATED_LINE + GEMFILE_SOURCE_LINE) # We have to make sure fastlane is also added to the Gemfile, since we now use # bundler to run fastlane content += "\ngem 'fastlane'\n" unless available_gems.include?('fastlane') content += "\n#{self.class.code_to_attach}\n" File.write(path_to_gemfile, content) end
ruby
{ "resource": "" }
q10570
Fastlane.PluginManager.print_plugin_information
train
def print_plugin_information(references) rows = references.collect do |current| if current[1][:actions].empty? # Something is wrong with this plugin, no available actions [current[0].red, current[1][:version_number], "No actions found".red] else [current[0], current[1][:version_number], current[1][:actions].join("\n")] end end require 'terminal-table' puts(Terminal::Table.new({ rows: FastlaneCore::PrintTable.transform_output(rows), title: "Used plugins".green, headings: ["Plugin", "Version", "Action"] })) puts("") end
ruby
{ "resource": "" }
q10571
Screengrab.Runner.if_device_path_exists
train
def if_device_path_exists(device_serial, device_path) return if run_adb_command("adb -s #{device_serial} shell ls #{device_path}", print_all: false, print_command: false).include?('No such file') yield(device_path) rescue # Some versions of ADB will have a non-zero exit status for this, which will cause the executor to raise. # We can safely ignore that and treat it as if it returned 'No such file' end
ruby
{ "resource": "" }
q10572
Screengrab.Runner.installed_packages
train
def installed_packages(device_serial) packages = run_adb_command("adb -s #{device_serial} shell pm list packages", print_all: true, print_command: true) packages.split("\n").map { |package| package.gsub("package:", "") } end
ruby
{ "resource": "" }
q10573
Sigh.Runner.fetch_profiles
train
def fetch_profiles UI.message("Fetching profiles...") results = profile_type.find_by_bundle_id(bundle_id: Sigh.config[:app_identifier], mac: Sigh.config[:platform].to_s == 'macos', sub_platform: Sigh.config[:platform].to_s == 'tvos' ? 'tvOS' : nil) results = results.find_all do |current_profile| if current_profile.valid? || Sigh.config[:force] true else UI.message("Provisioning Profile '#{current_profile.name}' is not valid, skipping this one...") false end end # Take the provisioning profile name into account results = filter_profiles_by_name(results) if Sigh.config[:provisioning_name].to_s.length > 0 return results if Sigh.config[:skip_certificate_verification] UI.message("Verifying certificates...") return results.find_all do |current_profile| installed = false # Attempts to download all certificates from this profile # for checking if they are installed. # `cert.download_raw` can fail if the user is a # "member" and not an a "admin" raw_certs = current_profile.certificates.map do |cert| begin raw_cert = cert.download_raw rescue => error UI.important("Cannot download cert #{cert.id} - #{error.message}") raw_cert = nil end { downloaded: raw_cert, cert: cert } end # Makes sure we have the certificate installed on the local machine raw_certs.each do |current_cert| # Skip certificates that failed to download next unless current_cert[:downloaded] file = Tempfile.new('cert') file.write(current_cert[:downloaded]) file.close if FastlaneCore::CertChecker.installed?(file.path) installed = true else UI.message("Certificate for Provisioning Profile '#{current_profile.name}' not available locally: #{current_cert[:cert].id}, skipping this one...") end end installed && current_profile.certificate_valid? end end
ruby
{ "resource": "" }
q10574
Sigh.Runner.create_profile!
train
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
{ "resource": "" }
q10575
Sigh.Runner.certificate_to_use
train
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
{ "resource": "" }
q10576
Sigh.Runner.download_profile
train
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
{ "resource": "" }
q10577
Sigh.Runner.ensure_app_exists!
train
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
{ "resource": "" }
q10578
Sigh.DownloadAll.download_all
train
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
{ "resource": "" }
q10579
Fastlane.SocketServer.handle_control_command
train
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
{ "resource": "" }
q10580
Fastlane.SocketServer.send_response
train
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
{ "resource": "" }
q10581
Fastlane.SocketServer.execute_action_command
train
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
{ "resource": "" }
q10582
FastlaneCore.Project.schemes
train
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
{ "resource": "" }
q10583
FastlaneCore.Project.select_scheme
train
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
{ "resource": "" }
q10584
FastlaneCore.Project.configurations
train
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
{ "resource": "" }
q10585
FastlaneCore.Project.default_build_settings
train
def default_build_settings(key: nil, optional: true) options[:scheme] ||= schemes.first if is_workspace build_settings(key: key, optional: optional) end
ruby
{ "resource": "" }
q10586
Match.Nuke.print_tables
train
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
{ "resource": "" }
q10587
Deliver.UploadMetadata.upload
train
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
{ "resource": "" }
q10588
Deliver.UploadMetadata.upload_individual_item
train
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
{ "resource": "" }
q10589
Deliver.UploadMetadata.verify_available_languages!
train
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
{ "resource": "" }
q10590
Deliver.UploadMetadata.load_from_filesystem
train
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
{ "resource": "" }
q10591
Deliver.UploadMetadata.normalize_language_keys
train
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
{ "resource": "" }
q10592
Spaceship.Utilities.resolution
train
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
{ "resource": "" }
q10593
Fastlane.SocketServerActionCommandExecutor.run_action_requiring_special_handling
train
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
{ "resource": "" }
q10594
Gym.Runner.build_app
train
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
{ "resource": "" }
q10595
Gym.Runner.post_build_app
train
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
{ "resource": "" }
q10596
Gym.Runner.move_ipa
train
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
{ "resource": "" }
q10597
Gym.Runner.copy_mac_app
train
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
{ "resource": "" }
q10598
Gym.Runner.move_manifest
train
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
{ "resource": "" }
q10599
Gym.Runner.move_app_thinning
train
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
{ "resource": "" }