idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
200
def sort_input ( input , property , order ) input . map { | item | [ item_property ( item , property ) , item ] } . sort! do | a_info , b_info | a_property = a_info . first b_property = b_info . first if ! a_property . nil? && b_property . nil? - order elsif a_property . nil? && ! b_property . nil? + order else a_property <=> b_property || a_property . to_s <=> b_property . to_s end end . map! ( & :last ) end
Sort the input Enumerable by the given property . If the property doesn t exist return the sort order respective of which item doesn t have the property . We also utilize the Schwartzian transform to make this more efficient .
201
def compare_property_vs_target ( property , target ) case target when NilClass return true if property . nil? when Liquid :: Expression :: MethodLiteral return true if Array ( property ) . join == target . to_s else Array ( property ) . each do | prop | return true if prop . to_s == target . to_s end end false end
where filter helper
202
def entries return [ ] unless exists? @entries ||= Utils . safe_glob ( collection_dir , [ "**" , "*" ] , File :: FNM_DOTMATCH ) . map do | entry | entry [ "#{collection_dir}/" ] = "" entry end end
All the entries in this collection .
203
def collection_dir ( * files ) return directory if files . empty? site . in_source_dir ( container , relative_directory , * files ) end
The full path to the directory containing the collection with optional subpaths .
204
def add ( path ) return true unless File . exist? ( path ) metadata [ path ] = { "mtime" => File . mtime ( path ) , "deps" => [ ] , } cache [ path ] = true end
Add a path to the metadata
205
def add_dependency ( path , dependency ) return if metadata [ path ] . nil? || disabled unless metadata [ path ] [ "deps" ] . include? dependency metadata [ path ] [ "deps" ] << dependency add ( dependency ) unless metadata . include? ( dependency ) end regenerate? dependency end
Add a dependency of a path
206
def write_metadata unless disabled? Jekyll . logger . debug "Writing Metadata:" , ".jekyll-metadata" File . binwrite ( metadata_file , Marshal . dump ( metadata ) ) end end
Write the metadata to disk
207
def fetch_value ( path ) specifics = @data [ 'data' ] . select { | a | path . include? ( a [ 'filter' ] ) } default = @data [ 'default' ] values = default . clone specifics . each do | specific | values = values . fastlane_deep_merge ( specific ) end change_paths_to_absolutes! ( values ) validate_values ( values ) values end
Fetches the finished configuration for a given path . This will try to look for a specific value and fallback to a default value if nothing was found
208
def change_paths_to_absolutes! ( values ) values . each do | key , value | if value . kind_of? ( Hash ) change_paths_to_absolutes! ( value ) elsif value . kind_of? ( Array ) value . each do | current | change_paths_to_absolutes! ( current ) if current . kind_of? ( Hash ) end else if [ 'font' , 'background' ] . include? ( key ) if @path containing_folder = File . expand_path ( '..' , @path ) value . replace ( File . join ( containing_folder , value ) ) end end end end end
Use absolute paths instead of relative
209
def provisioning_profiles_via_xcode_api ( mac : false ) req = request ( :post ) do | r | r . url ( "https://developerservices2.apple.com/services/#{PROTOCOL_VERSION}/#{platform_slug(mac)}/listProvisioningProfiles.action" ) r . params = { teamId : team_id , includeInactiveProfiles : true , onlyCountLists : true } end result = parse_response ( req , 'provisioningProfiles' ) csrf_cache [ Spaceship :: Portal :: ProvisioningProfile ] = self . csrf_tokens result end
this endpoint is used by Xcode to fetch provisioning profiles . The response is an xml plist but has the added benefit of containing the appId of each provisioning profile .
210
def ensure_csrf ( klass ) if csrf_cache [ klass ] self . csrf_tokens = csrf_cache [ klass ] return end self . csrf_tokens = nil block_given? ? yield : klass . all csrf_cache [ klass ] = self . csrf_tokens end
Ensures that there are csrf tokens for the appropriate entity type Relies on store_csrf_tokens to set csrf_tokens to the appropriate value then stores that in the correct place in cache This method also takes a block if you want to send a custom request instead of calling . all on the given klass . This is used for provisioning profiles .
211
def put_into_frame rotation = self . rotation_for_device_orientation frame . rotate ( - rotation ) @image . rotate ( - rotation ) if self . debug_mode filename = File . basename ( @frame_path , ".*" ) filename . sub! ( 'Apple' , '' ) width = screenshot . size [ 0 ] font_size = width / 20 offset_top = offset [ 'offset' ] . split ( "+" ) [ 2 ] . to_f annotate_offset = "+0+#{offset_top}" frame . combine_options do | c | c . gravity ( 'North' ) c . undercolor ( '#00000080' ) c . fill ( 'white' ) c . pointsize ( font_size ) c . annotate ( annotate_offset . to_s , filename . to_s ) end end @image = frame . composite ( image , "png" ) do | c | c . compose ( "DstOver" ) c . geometry ( offset [ 'offset' ] ) end frame . rotate ( rotation ) @image . rotate ( rotation ) end
puts the screenshot into the frame
212
def modify_offset ( multiplicator ) hash = offset [ 'offset' ] x = hash . split ( "+" ) [ 1 ] . to_f * multiplicator y = hash . split ( "+" ) [ 2 ] . to_f * multiplicator new_offset = "+#{x.round}+#{y.round}" @offset_information [ 'offset' ] = new_offset end
Everything below is related to title background etc . and is not used in the easy mode
213
def horizontal_frame_padding padding = fetch_config [ 'padding' ] if padding . kind_of? ( String ) && padding . split ( 'x' ) . length == 2 padding = padding . split ( 'x' ) [ 0 ] padding = padding . to_i unless padding . end_with? ( '%' ) end return scale_padding ( padding ) end
Horizontal adding around the frames
214
def title_min_height @title_min_height ||= begin height = fetch_config [ 'title_min_height' ] || 0 if height . kind_of? ( String ) && height . end_with? ( '%' ) height = ( [ image . width , image . height ] . min * height . to_f * 0.01 ) . ceil end height end end
Minimum height for the title
215
def generate_background background = MiniMagick :: Image . open ( fetch_config [ 'background' ] ) if background . height != screenshot . size [ 1 ] background . resize ( "#{screenshot.size[0]}x#{screenshot.size[1]}^" ) background . merge! ( [ "-gravity" , "center" , "-crop" , "#{screenshot.size[0]}x#{screenshot.size[1]}+0+0" ] ) end background end
Returns a correctly sized background image
216
def resize_frame! screenshot_width = self . screenshot . portrait? ? screenshot . size [ 0 ] : screenshot . size [ 1 ] multiplicator = ( screenshot_width . to_f / offset [ 'width' ] . to_f ) new_frame_width = multiplicator * frame . width frame . resize ( "#{new_frame_width.round}x" ) modify_offset ( multiplicator ) end
Resize the frame as it s too low quality by default
217
def put_title_into_background_stacked ( background , title , keyword ) resize_text ( title ) resize_text ( keyword ) vertical_padding = vertical_frame_padding spacing_between_title_and_keyword = ( actual_font_size / 2 ) title_left_space = ( background . width / 2.0 - title . width / 2.0 ) . round keyword_left_space = ( background . width / 2.0 - keyword . width / 2.0 ) . round self . space_to_device += title . height + keyword . height + spacing_between_title_and_keyword + vertical_padding if title_below_image keyword_top = background . height - effective_text_height / 2 - ( keyword . height + spacing_between_title_and_keyword + title . height ) / 2 else keyword_top = device_top ( background ) / 2 - spacing_between_title_and_keyword / 2 - keyword . height end title_top = keyword_top + keyword . height + spacing_between_title_and_keyword background = background . composite ( keyword , "png" ) do | c | c . compose ( "Over" ) c . geometry ( "+#{keyword_left_space}+#{keyword_top}" ) end background = background . composite ( title , "png" ) do | c | c . compose ( "Over" ) c . geometry ( "+#{title_left_space}+#{title_top}" ) end background end
Add the title above or below the device
218
def build_text_images ( max_width , max_height , stack_title ) words = [ :keyword , :title ] . keep_if { | a | fetch_text ( a ) } results = { } trim_boxes = { } top_vertical_trim_offset = Float :: INFINITY bottom_vertical_trim_offset = 0 words . each do | key | empty_path = File . join ( Frameit :: ROOT , "lib/assets/empty.png" ) text_image = MiniMagick :: Image . open ( empty_path ) image_height = max_height text_image . combine_options do | i | i . resize ( "#{max_width * 5.0}x#{image_height}!" ) end current_font = font ( key ) text = fetch_text ( key ) UI . verbose ( "Using #{current_font} as font the #{key} of #{screenshot.path}" ) if current_font UI . verbose ( "Adding text '#{text}'" ) text . gsub! ( '\n' , "\n" ) text . gsub! ( / \\ / ) { | s | "\\#{s}" } interline_spacing = fetch_config [ 'interline_spacing' ] text_image . combine_options do | i | i . font ( current_font ) if current_font i . gravity ( "Center" ) i . pointsize ( actual_font_size ) i . draw ( "text 0,0 '#{text}'" ) i . interline_spacing ( interline_spacing ) if interline_spacing i . fill ( fetch_config [ key . to_s ] [ 'color' ] ) end results [ key ] = text_image calculated_trim_box = text_image . identify do | b | b . format ( "%@" ) end trim_box = Frameit :: Trimbox . new ( calculated_trim_box ) if trim_box . offset_y < top_vertical_trim_offset top_vertical_trim_offset = trim_box . offset_y end if ( trim_box . offset_y + trim_box . height ) > bottom_vertical_trim_offset bottom_vertical_trim_offset = trim_box . offset_y + trim_box . height end trim_boxes [ key ] = trim_box end words . each do | key | trim_box = trim_boxes [ key ] unless stack_title if trim_box . offset_y > top_vertical_trim_offset trim_box . height += trim_box . offset_y - top_vertical_trim_offset trim_box . offset_y = top_vertical_trim_offset UI . verbose ( "Trim box for key \"#{key}\" is adjusted to align top: #{trim_box}\n" ) end if ( trim_box . offset_y + trim_box . height ) < bottom_vertical_trim_offset trim_box . height = bottom_vertical_trim_offset - trim_box . offset_y UI . verbose ( "Trim box for key \"#{key}\" is adjusted to align bottom: #{trim_box}\n" ) end end results [ key ] . crop ( trim_box . string_format ) end results end
This will build up to 2 individual images with the title and optional keyword which will then be added to the real image
219
def fetch_text ( type ) UI . user_error! ( "Valid parameters :keyword, :title" ) unless [ :keyword , :title ] . include? ( type ) strings_path = File . join ( File . expand_path ( ".." , screenshot . path ) , "#{type}.strings" ) if File . exist? ( strings_path ) parsed = StringsParser . parse ( strings_path ) text_array = parsed . find { | k , v | screenshot . path . upcase . include? ( k . upcase ) } return text_array . last if text_array && text_array . last . length > 0 end UI . verbose ( "Falling back to text in Framefile.json as there was nothing specified in the #{type}.strings file" ) text = fetch_config [ type . to_s ] [ 'text' ] if fetch_config [ type . to_s ] && fetch_config [ type . to_s ] [ 'text' ] && fetch_config [ type . to_s ] [ 'text' ] . length > 0 return text end
Fetches the title + keyword for this particular screenshot
220
def font ( key ) single_font = fetch_config [ key . to_s ] [ 'font' ] return single_font if single_font fonts = fetch_config [ key . to_s ] [ 'fonts' ] if fonts fonts . each do | font | if font [ 'supported' ] font [ 'supported' ] . each do | language | if screenshot . path . include? ( language ) return font [ "font" ] end end else UI . verbose ( "Found a font with no list of supported languages, using this now" ) return font [ "font" ] end end end UI . verbose ( "No custom font specified for #{screenshot}, using the default one" ) return nil end
The font we want to use
221
def transporter_for_selected_team ( options ) generic_transporter = FastlaneCore :: ItunesTransporter . new ( options [ :username ] , nil , false , options [ :itc_provider ] ) return generic_transporter unless options [ :itc_provider ] . nil? && Spaceship :: Tunes . client . teams . count > 1 begin team = Spaceship :: Tunes . client . teams . find { | t | t [ 'contentProvider' ] [ 'contentProviderId' ] . to_s == Spaceship :: Tunes . client . team_id } name = team [ 'contentProvider' ] [ 'name' ] provider_id = generic_transporter . provider_ids [ name ] UI . verbose ( "Inferred provider id #{provider_id} for team #{name}." ) return FastlaneCore :: ItunesTransporter . new ( options [ :username ] , nil , false , provider_id ) rescue => ex UI . verbose ( "Couldn't infer a provider short name for team with id #{Spaceship::Tunes.client.team_id} automatically: #{ex}. Proceeding without provider short name." ) return generic_transporter end end
If itc_provider was explicitly specified use it . If there are multiple teams infer the provider from the selected team name . If there are fewer than two teams don t infer the provider .
222
def update_request_headers ( req ) req . headers [ "X-Apple-Id-Session-Id" ] = @x_apple_id_session_id req . headers [ "X-Apple-Widget-Key" ] = self . itc_service_key req . headers [ "Accept" ] = "application/json" req . headers [ "scnt" ] = @scnt end
Responsible for setting all required header attributes for the requests to succeed
223
def upload ( app_id , dir ) actual_dir = File . join ( dir , "#{app_id}.itmsp" ) UI . message ( "Going to upload updated app to App Store Connect" ) UI . success ( "This might take a few minutes. Please don't interrupt the script." ) command = @transporter_executor . build_upload_command ( @user , @password , actual_dir , @provider_short_name ) UI . verbose ( @transporter_executor . build_upload_command ( @user , 'YourPassword' , actual_dir , @provider_short_name ) ) begin result = @transporter_executor . execute ( command , ItunesTransporter . hide_transporter_output? ) rescue TransporterRequiresApplicationSpecificPasswordError => ex handle_two_step_failure ( ex ) return upload ( app_id , dir ) end if result UI . header ( "Successfully uploaded package to App Store Connect. It might take a few minutes until it's visible online." ) FileUtils . rm_rf ( actual_dir ) unless Helper . test? else handle_error ( @password ) end result end
Uploads the modified package back to App Store Connect
224
def load_password_for_transporter if ENV [ TWO_FACTOR_ENV_VARIABLE ] . to_s . length > 0 UI . message ( "Fetching password for transporter from environment variable named `#{TWO_FACTOR_ENV_VARIABLE}`" ) return ENV [ TWO_FACTOR_ENV_VARIABLE ] end account_manager = CredentialsManager :: AccountManager . new ( user : @user , prefix : TWO_STEP_HOST_PREFIX , note : "application-specific" ) password = account_manager . password ( ask_if_missing : false ) return password if password . to_s . length > 0 account_manager = CredentialsManager :: AccountManager . new ( user : @user ) return account_manager . password ( ask_if_missing : true ) end
Returns the password to be used with the transporter
225
def handle_two_step_failure ( ex ) if ENV [ TWO_FACTOR_ENV_VARIABLE ] . to_s . length > 0 UI . error ( "" ) UI . error ( "Application specific password you provided using" ) UI . error ( "environment variable #{TWO_FACTOR_ENV_VARIABLE}" ) UI . error ( "is invalid, please make sure it's correct" ) UI . error ( "" ) UI . user_error! ( "Invalid application specific password provided" ) end a = CredentialsManager :: AccountManager . new ( user : @user , prefix : TWO_STEP_HOST_PREFIX , note : "application-specific" ) if a . password ( ask_if_missing : false ) . to_s . length > 0 UI . error ( "Application specific password seems wrong" ) UI . error ( "Please make sure to follow the instructions" ) a . remove_from_keychain end UI . error ( "" ) UI . error ( "Your account has 2 step verification enabled" ) UI . error ( "Please go to https://appleid.apple.com/account/manage" ) UI . error ( "and generate an application specific password for" ) UI . error ( "the iTunes Transporter, which is used to upload builds" ) UI . error ( "" ) UI . error ( "To set the application specific password on a CI machine using" ) UI . error ( "an environment variable, you can set the" ) UI . error ( "#{TWO_FACTOR_ENV_VARIABLE} variable" ) @password = a . password ( ask_if_missing : true ) return true end
Tells the user how to get an application specific password
226
def prefixed_working_directory ( working_directory ) if self . storage_mode == "git" return working_directory elsif self . storage_mode == "google_cloud" @_folder_prefix ||= self . currently_used_team_id if @_folder_prefix . nil? 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
Used when creating a new certificate or profile
227
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 = { } 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 if self . app_identifier . to_s . length == 0 ask_for_bundle_identifier end end
Helpers Every installation setup that needs an Xcode project should call this method
228
def team_id = ( team_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 } . to_json req . headers [ 'Content-Type' ] = 'application/json' end handle_itc_response ( response . body ) @current_team_id = team_id end
Set a new team ID which will be used from now on
229
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
Returns preferred path for storing cookie for two step verification .
230
def paging page = 0 results = [ ] loop do page += 1 current = yield ( page ) results += current break if ( current || [ ] ) . count < page_size end return results end
Handles the paging for you ... for free Just pass a block and use the parameter as page number
231
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 ) rescue InvalidUserCredentialsError => ex raise ex unless keychain_entry if keychain_entry . invalid_credentials login ( user ) else raise ex end end end
Authenticates with Apple s web services . This method has to be called once to generate a valid session . The session will automatically be used from then on .
232
def send_shared_login_request ( user , password ) if load_session_from_file begin return true if fetch_olympus_session rescue puts ( "Available session is not valid any more. Continuing with normal login." ) end end if load_session_from_env begin return true if fetch_olympus_session rescue puts ( "Session loaded from environment variable is not valid. Continuing with normal login." ) end end data = { accountName : user , password : password , rememberMe : true } begin important_cookie = @cookie . store . entries . find { | a | a . name . include? ( "DES" ) } if important_cookie modified_cookie = self . cookie 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 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 handle_two_step_or_factor ( response ) fetch_olympus_session return true else if ( response . body || "" ) . include? ( 'invalid="true"' ) raise InvalidUserCredentialsError . new , "Invalid username and password combination. Used '#{user}' as the username." elsif response . status == 412 && AUTH_TYPES . include? ( response . body [ "authType" ] ) 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
This method is used for both the Apple Dev Portal and App Store Connect This will also handle 2 step verification and 2 factor authentication
233
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
Get contract messages from App Store Connect s olympus endpoint
234
def raise_insufficient_permission_error! ( additional_error_string : nil , caller_location : 2 ) calling_method_name = caller_locations ( caller_location , 2 ) . first . label . sub ( "block in" , "" ) . delete ( "!" ) . strip 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
This also gets called from subclasses
235
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
Actually sends the request to the remote server Automatically retries the request up to 3 times if something goes wrong
236
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
Returns a path relative to FastlaneFolder . path This is needed as the Preview . html file is located inside FastlaneFolder . path
237
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 ) export_path = File . join ( export_path , "Preview.html" ) File . write ( export_path , html ) return export_path end
Renders all data available to quickly see if everything was correctly generated .
238
def sh ( * command , log : true , error_callback : nil , & b ) FastFile . sh ( * command , log : log , error_callback : error_callback , & b ) end
Execute shell command
239
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}'" ) output = Helper . backticks ( "xcrun simctl addmedia #{device_udid} #{path.shellescape} &> /dev/null" ) if output . include? ( 'usage: simctl' ) Helper . backticks ( "xcrun simctl add#{media_type} #{device_udid} #{path.shellescape} &> /dev/null" ) end end end end
pass an array of device types
240
def append_lane ( lane ) lane . compact! new_lines = "\n\n" if self . is_swift_fastfile new_lines = "" unless self . fastfile_content . include? ( "lane() {" ) self . fastfile_content . gsub! ( "[[LANES]]" , "#{new_lines}\t#{lane.join("\n\t")}[[LANES]]" ) else new_lines = "" unless self . fastfile_content . include? ( "lane :" ) self . fastfile_content . gsub! ( "[[LANES]]" , "#{new_lines} #{lane.join("\n ")}[[LANES]]" ) end end
Append a lane to the current Fastfile template we re generating
241
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
This method is responsible for ensuring there is a working Gemfile and that fastlane is defined as a dependency while also having rubygems as a gem source
242
def run program :name , 'CredentialsManager' program :version , Fastlane :: VERSION program :description , 'Manage credentials for fastlane tools.' 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 :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
Parses command options and executes actions
243
def add ( username , password ) CredentialsManager :: AccountManager . new ( user : username , password : password ) . add_to_keychain end
Add entry to Apple Keychain using AccountManager
244
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 ) return File . read ( deliverfile_path ) end
This method takes care of creating a new deliver folder containing the app metadata and screenshots folders
245
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
Checks if the gem name is still free on RubyGems
246
def fix_plugin_name ( name ) name = name . to_s . downcase fixes = { / \- / => '_' , / / => '' , / / => '' , / / => '' } fixes . each do | regex , replacement | name = name . gsub ( regex , replacement ) end name end
Applies a series of replacement rules to turn the requested plugin name into one that is acceptable returning that suggestion
247
def installed_identities available = request_valid_identities ids = { } available . split ( "\n" ) . each do | current | begin sha1 = current . match ( / / ) . to_s name = current . match ( / \" \" / ) [ 1 ] ids [ sha1 ] = name rescue nil end end ids end
Hash of available signing identities
248
def save @google_api . update_listing_for_language ( language : language , title : title , short_description : short_description , full_description : full_description , video : video ) end
Initializes the listing to use the given api client language and fills it with the current listing if available Updates the listing in the current edit
249
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
Call this method to ask the user to re - enter the credentials
250
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
Use env variables from this method to augment internet password item with additional data . These variables are used by Xamarin Studio to authenticate Apple developers .
251
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
Called just as the investigation has begun .
252
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
Called once the inspector has received a report with more than one issue .
253
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? 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? self . team_id = t_id return self . team_id end 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 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 return self . team_id end end end
Shows a team selection for the user in the terminal . This should not be called on CI systems
254
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
Sometimes we get errors or info nested in our data This method allows you to pass in a set of keys to check for along with the name of the sub_section of your original data where we should check Returns a mapping of keys to data array if we find anything otherwise empty map
255
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 primary_language ||= "English" platform ||= "ios" r = request ( :get , "ra/apps/create/v2/?platformString=#{platform}" ) data = parse_response ( r , 'data' ) 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 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
Creates a new application on App Store Connect
256
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
Returns an array of all available pricing tiers
257
def supported_territories data = supported_countries data . map { | country | Spaceship :: Tunes :: Territory . factory ( country ) } end
Returns an array of all supported territories
258
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
Uploads a watch icon
259
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
Uploads an In - App - Purchase Review screenshot
260
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
Uploads a screenshot
261
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
Uploads an iMessage screenshot
262
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
Uploads the trailer preview
263
def ref_data r = request ( :get , '/WebObjects/iTunesConnect.woa/ra/apps/version/ref' ) data = parse_response ( r , 'data' ) Spaceship :: Tunes :: AppVersionRef . factory ( data ) end
Fetches the App Version Reference information from ITC
264
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
All build trains even if there is no TestFlight
265
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
updates an In - App - Purchases - Family
266
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
updates an In - App - Purchases
267
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 ) type ||= "consumable" r = request ( :get , "ra/apps/#{app_id}/iaps/#{type}/template" ) data = parse_response ( r , 'data' ) 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 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_file = UploadFile . from_path ( review_screenshot ) screenshot_data = upload_purchase_review_screenshot ( app_id , upload_file ) data [ "versions" ] [ 0 ] [ "reviewScreenshot" ] = screenshot_data end 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
Creates an In - App - Purchases
268
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
generates group hash used in the analytics time_series API . Using rank = DESCENDING and limit = 3 as this is what the App Store Connect analytics dashboard uses .
269
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 ) 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 end end
This is its own method so that it can re - try if the tests fail randomly
270
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
Returns true if it succeeded
271
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 ] 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
Verifies the default value is also valid
272
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 options . each do | key , val | option = self . verify_options_key! ( key ) option . verify! ( val ) end self . config_file_options = options . merge ( self . config_file_options ) verify_conflicts raise wrapped_exception unless wrapped_exception . nil? configuration_file end
This method takes care of parsing and using the configuration file as values Call this once you know where the config file might be located Take a look at how gym uses this method
273
def method_missing ( method_sym , * arguments , & _block ) self . runner . trigger_action_by_name ( method_sym , FastlaneCore :: FastlaneFolder . path , true , * arguments ) end
Allows the user to call an action from an action
274
def language @language = Produce . config [ :language ] converted = Spaceship :: Tunes :: LanguageConverter . from_itc_readable_to_itc ( @language ) @language = converted if converted unless AvailableDefaultLanguages . all_languages . include? ( @language ) UI . user_error! ( "Please enter one of available languages: #{AvailableDefaultLanguages.all_languages}" ) end return @language end
Makes sure to get the value for the language Instead of using the user s value UK English spaceship should send English_UK to the server
275
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
lookup if an alias exists
276
def trigger_action_by_name ( method_sym , custom_dir , from_action , * arguments ) class_ref = class_reference_from_action_name ( method_sym ) unless class_ref class_ref = class_reference_from_action_alias ( method_sym ) 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 begin return self . try_switch_to_lane ( method_sym , arguments ) rescue LaneNotAvailableError end if class_ref if class_ref . respond_to? ( :run ) 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 if Fastlane . plugin_manager . plugin_is_added_as_dependency? ( PluginManager . plugin_prefix + method_sym . to_s ) 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 ) 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 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
This is being called from method_missing from the Fastfile It s also used when an action is called from another action
277
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
Called internally to setup the runner object
278
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
Makes sure a Fastfile is available Shows an appropriate message to the user if that s not the case return true if the Fastfile is available
279
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
Make sure the version on App Store Connect matches the one in the ipa If not the new version will automatically be created
280
def upload_metadata upload_metadata = UploadMetadata . new upload_screenshots = UploadScreenshots . new screenshots = upload_screenshots . collect_screenshots ( options ) upload_metadata . load_from_filesystem ( options ) upload_metadata . assign_defaults ( options ) prepare_app_icons ( options ) validate_html ( screenshots ) upload_metadata . upload ( options ) upload_screenshots . upload ( options , screenshots ) UploadPriceTier . new . upload ( options ) UploadAssets . new . upload ( options ) end
Upload all metadata screenshots pricing information etc . to App Store Connect
281
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
Upload the binary to App Store Connect
282
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? ( '.' ) 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
Upload binary apk and obb and corresponding change logs with client
283
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
returns only language directories from metadata_path
284
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
searches for obbs in the directory where the apk is located and upload at most one main and one patch file . Do nothing if it finds more than one of either of them .
285
def generate ( options , command : nil ) always_trace! used_switches = [ ] options . each do | option | next if option . description . to_s . empty? 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 if type == Hash type = option . is_string ? String : nil end if type == Fastlane :: Boolean type = nil end 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? args = [ short_switch , long_switch , ( type || String ) , description ] . compact if command command . option ( * args ) else global_option ( * args ) end end end
Calls the appropriate methods for commander to show the available parameters
286
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 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
Intialize with values from Scan . config matching these param names
287
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
Aborts the current edit deleting all pending changes
288
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
Commits the current edit saving all pending changes on Google Play
289
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 raise end end
Returns the listing for the given language filled with the current values if it already exists
290
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
Get a list of all APK version codes - returns the list of version codes
291
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
Get a list of all AAB version codes - returns the list of version codes
292
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
Get list of version codes for track
293
def available_gems return [ ] unless gemfile_path dsl = Bundler :: Dsl . evaluate ( gemfile_path , nil , true ) return dsl . dependencies . map ( & :name ) end
Returns an array of gems that are added to the Gemfile or Pluginfile
294
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
Check if a plugin is added as dependency to either the Gemfile or the Pluginfile
295
def attach_plugins_to_gemfile! ( path_to_gemfile ) content = gemfile_content || ( AUTOGENERATED_LINE + GEMFILE_SOURCE_LINE ) content += "\ngem 'fastlane'\n" unless available_gems . include? ( 'fastlane' ) content += "\n#{self.class.code_to_attach}\n" File . write ( path_to_gemfile , content ) end
Modify the user s Gemfile to load the plugins
296
def print_plugin_information ( references ) rows = references . collect do | current | if current [ 1 ] [ :actions ] . empty? [ 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
Prints a table all the plugins that were loaded
297
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 end
Some device commands fail if executed against a device path that does not exist so this helper method provides a way to conditionally execute a block only if the provided path exists on the device .
298
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
Return an array of packages that are installed on the device
299
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 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 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 raw_certs . each do | current_cert | 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
Fetches a profile matching the user s search requirements