repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/cert/lib/cert/runner.rb | cert/lib/cert/runner.rb | require 'fileutils'
require 'fastlane_core/globals'
require 'fastlane_core/cert_checker'
require 'fastlane_core/keychain_importer'
require 'fastlane_core/print_table'
require 'spaceship'
require_relative 'module'
module Cert
class Runner
def launch
run
if Helper.mac?
UI.message("Verifying the certificate is properly installed locally...")
installed = FastlaneCore::CertChecker.installed?(ENV["CER_FILE_PATH"], in_keychain: ENV["CER_KEYCHAIN_PATH"])
UI.user_error!("Could not find the newly generated certificate installed", show_github_issues: true) unless installed
UI.success("Successfully installed certificate #{ENV['CER_CERTIFICATE_ID']}")
else
UI.message("Skipping verifying certificates as it would not work on this operating system.")
end
return ENV["CER_FILE_PATH"]
end
def login
if (api_token = Spaceship::ConnectAPI::Token.from(hash: Cert.config[:api_key], filepath: Cert.config[:api_key_path]))
UI.message("Creating authorization token for App Store Connect API")
Spaceship::ConnectAPI.token = api_token
elsif !Spaceship::ConnectAPI.token.nil?
UI.message("Using existing authorization token for App Store Connect API")
else
# Username is now optional since addition of App Store Connect API Key
# Force asking for username to prompt user if not already set
Cert.config.fetch(:username, force_ask: true)
UI.message("Starting login with user '#{Cert.config[:username]}'")
Spaceship::ConnectAPI.login(Cert.config[:username], nil, use_portal: true, use_tunes: false)
UI.message("Successfully logged in")
end
end
def run
FileUtils.mkdir_p(Cert.config[:output_path])
FastlaneCore::PrintTable.print_values(config: Cert.config, hide_keys: [:output_path], title: "Summary for cert #{Fastlane::VERSION}")
login
should_create = Cert.config[:force]
unless should_create
cert_path = find_existing_cert if Helper.mac?
should_create = cert_path.nil?
end
return unless should_create
if create_certificate # no certificate here, creating a new one
return # success
else
UI.user_error!("Something went wrong when trying to create a new certificate...")
end
end
# Command method for the :revoke_expired sub-command
def revoke_expired_certs!
FastlaneCore::PrintTable.print_values(config: Cert.config, hide_keys: [:output_path], title: "Summary for cert #{Fastlane::VERSION}")
login
to_revoke = expired_certs
if to_revoke.empty?
UI.success("No expired certificates were found to revoke! 👍")
return
end
revoke_count = 0
to_revoke.each do |certificate|
begin
UI.message("#{certificate.id} #{certificate.display_name} has expired, revoking...")
certificate.delete!
revoke_count += 1
rescue => e
UI.error("An error occurred while revoking #{certificate.id} #{certificate.display_name}")
UI.error("#{e.message}\n#{e.backtrace.join("\n")}") if FastlaneCore::Globals.verbose?
end
end
UI.success("#{revoke_count} expired certificate#{'s' if revoke_count != 1} #{revoke_count == 1 ? 'has' : 'have'} been revoked! 👍")
end
def expired_certs
certificates.reject(&:valid?)
end
def find_existing_cert
certificates.each do |certificate|
unless certificate.certificate_content
next
end
path = store_certificate(certificate, Cert.config[:filename])
private_key_path = File.expand_path(File.join(Cert.config[:output_path], "#{certificate.id}.p12"))
# As keychain is specific to macOS, this will likely fail on non macOS systems.
# See also: https://github.com/fastlane/fastlane/pull/14462
keychain = File.expand_path(Cert.config[:keychain_path]) unless Cert.config[:keychain_path].nil?
if FastlaneCore::CertChecker.installed?(path, in_keychain: keychain)
# This certificate is installed on the local machine
ENV["CER_CERTIFICATE_ID"] = certificate.id
ENV["CER_FILE_PATH"] = path
ENV["CER_KEYCHAIN_PATH"] = keychain
UI.success("Found the certificate #{certificate.id} (#{certificate.display_name}) which is installed on the local machine. Using this one.")
return path
elsif File.exist?(private_key_path)
password = Cert.config[:keychain_password]
FastlaneCore::KeychainImporter.import_file(private_key_path, keychain, keychain_password: password, skip_set_partition_list: Cert.config[:skip_set_partition_list])
FastlaneCore::KeychainImporter.import_file(path, keychain, keychain_password: password, skip_set_partition_list: Cert.config[:skip_set_partition_list])
ENV["CER_CERTIFICATE_ID"] = certificate.id
ENV["CER_FILE_PATH"] = path
ENV["CER_KEYCHAIN_PATH"] = keychain
UI.success("Found the cached certificate #{certificate.id} (#{certificate.display_name}). Using this one.")
return path
else
UI.error("Certificate #{certificate.id} (#{certificate.display_name}) can't be found on your local computer")
end
File.delete(path) # as apparently this certificate is pretty useless without a private key
end
UI.important("Couldn't find an existing certificate... creating a new one")
return nil
end
# All certificates of this type
def certificates
filter = {
certificateType: certificate_types.join(",")
}
return Spaceship::ConnectAPI::Certificate.all(filter: filter)
end
# The kind of certificate we're interested in (for creating)
def certificate_type
return certificate_types.first
end
# The kind of certificates we're interested in (for listing)
def certificate_types
if Cert.config[:type]
case Cert.config[:type].to_sym
when :mac_installer_distribution
return [Spaceship::ConnectAPI::Certificate::CertificateType::MAC_INSTALLER_DISTRIBUTION]
when :developer_id_application
return [
Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_APPLICATION_G2,
Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_APPLICATION
]
when :developer_id_kext
return [Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_KEXT]
when :developer_id_installer
if !Spaceship::ConnectAPI.token.nil?
raise "As of 2021-11-09, the App Store Connect API does not allow accessing DEVELOPER_ID_INSTALLER with the API Key. Please file an issue on GitHub if this has changed and needs to be updated"
else
return [Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_INSTALLER]
end
else
UI.user_error("Unaccepted value for :type - #{Cert.config[:type]}")
end
end
# Check if apple certs (Xcode 11 and later) should be used
if Cert.config[:generate_apple_certs]
cert_type = Spaceship::ConnectAPI::Certificate::CertificateType::DISTRIBUTION
cert_type = Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DISTRIBUTION if Spaceship::ConnectAPI.client.in_house? # Enterprise doesn't use Apple Distribution
cert_type = Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPMENT if Cert.config[:development]
else
case Cert.config[:platform].to_s
when 'ios', 'tvos'
cert_type = Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DISTRIBUTION
cert_type = Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DISTRIBUTION if Spaceship::ConnectAPI.client.in_house?
cert_type = Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DEVELOPMENT if Cert.config[:development]
when 'macos'
cert_type = Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DISTRIBUTION
cert_type = Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DEVELOPMENT if Cert.config[:development]
end
end
return [cert_type]
end
def create_certificate
# Create a new certificate signing request
csr, pkey = Spaceship::ConnectAPI::Certificate.create_certificate_signing_request
# Use the signing request to create a new (development|distribution) certificate
begin
certificate = Spaceship::ConnectAPI::Certificate.create(
certificate_type: certificate_type,
csr_content: csr.to_pem
)
rescue => ex
type_name = (Cert.config[:development] ? "Development" : "Distribution")
if ex.to_s.include?("You already have a current")
UI.user_error!("Could not create another #{type_name} certificate, reached the maximum number of available #{type_name} certificates.", show_github_issues: true)
elsif ex.to_s.include?("You are not allowed to perform this operation.") && type_name == "Distribution"
UI.user_error!("You do not have permission to create this certificate. Only Team Admins can create Distribution certificates\n 🔍 See https://developer.apple.com/library/content/documentation/IDEs/Conceptual/AppDistributionGuide/ManagingYourTeam/ManagingYourTeam.html for more information.")
end
raise ex
end
# Store all that onto the filesystem
request_path = File.expand_path(File.join(Cert.config[:output_path], "#{certificate.id}.certSigningRequest"))
File.write(request_path, csr.to_pem)
private_key_path = File.expand_path(File.join(Cert.config[:output_path], "#{certificate.id}.p12"))
File.write(private_key_path, pkey)
cert_path = store_certificate(certificate, Cert.config[:filename])
if Helper.mac?
# Import all the things into the Keychain
keychain = File.expand_path(Cert.config[:keychain_path])
password = Cert.config[:keychain_password]
FastlaneCore::KeychainImporter.import_file(private_key_path, keychain, keychain_password: password, skip_set_partition_list: Cert.config[:skip_set_partition_list])
FastlaneCore::KeychainImporter.import_file(cert_path, keychain, keychain_password: password, skip_set_partition_list: Cert.config[:skip_set_partition_list])
else
UI.message("Skipping importing certificates as it would not work on this operating system.")
end
# Environment variables for the fastlane action
ENV["CER_CERTIFICATE_ID"] = certificate.id
ENV["CER_FILE_PATH"] = cert_path
if Helper.mac?
UI.success("Successfully generated #{certificate.id} which was imported to the local machine.")
else
UI.success("Successfully generated #{certificate.id}")
end
return cert_path
end
def store_certificate(certificate, filename = nil)
cert_name = filename ? filename : certificate.id
cert_name = "#{cert_name}.cer" unless File.extname(cert_name) == ".cer"
path = File.expand_path(File.join(Cert.config[:output_path], cert_name))
raw_data = Base64.decode64(certificate.certificate_content)
File.write(path, raw_data.force_encoding("UTF-8"))
return path
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/cert/lib/cert/module.rb | cert/lib/cert/module.rb | require 'fastlane_core/helper'
require 'fastlane/boolean'
module Cert
# Use this to just setup the configuration attribute and set it later somewhere else
class << self
attr_accessor :config
end
Helper = FastlaneCore::Helper # you gotta love Ruby: Helper.* should use the Helper class contained in FastlaneCore
UI = FastlaneCore::UI
Boolean = Fastlane::Boolean
ROOT = Pathname.new(File.expand_path('../../..', __FILE__))
ENV['FASTLANE_TEAM_ID'] ||= ENV["CERT_TEAM_ID"]
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/spec/commands_generator_spec.rb | sigh/spec/commands_generator_spec.rb | require 'sigh/commands_generator'
require 'sigh/repair'
describe Sigh::CommandsGenerator do
describe "resign option handling" do
let(:resign) do
resign = Sigh::Resign.new
expect(Sigh::Resign).to receive(:new).and_return(resign)
resign
end
def expect_resign_run(options)
expect(resign).to receive(:run) do |actual_options, actual_args|
expect(actual_options).to match_commander_options(options)
expect(actual_args).to eq([])
end
end
it "signing_identity short flag is not shadowed by cert_id short flag from tool options" do
stub_commander_runner_args(['resign', '-i', 'abcd'])
options = Commander::Command::Options.new
options.signing_identity = 'abcd'
expect_resign_run(options)
Sigh::CommandsGenerator.start
end
it "provisioning_profile short flag is not shadowed by platform short flag from tool options" do
stub_commander_runner_args(['resign', '-p', 'abcd'])
options = Commander::Command::Options.new
options.provisioning_profile = [['abcd']]
expect_resign_run(options)
Sigh::CommandsGenerator.start
end
end
describe "renew option handling" do
it "cert_id short flag from tool options can be used" do
# leaving out the command name defaults to 'renew'
stub_commander_runner_args(['-i', 'abcd'])
# start takes no params, but we want to expect the call and prevent
# actual execution of the method
expect(Sigh::Manager).to receive(:start)
Sigh::CommandsGenerator.start
expect(Sigh.config[:cert_id]).to eq('abcd')
end
it "platform short flag is not shadowed by cert_id short flag from tool options" do
# leaving out the command name defaults to 'renew'
stub_commander_runner_args(['-p', 'tvos'])
# start takes no params, but we want to expect the call and prevent
# actual execution of the method
expect(Sigh::Manager).to receive(:start)
Sigh::CommandsGenerator.start
expect(Sigh.config[:platform]).to eq('tvos')
end
end
describe "download_all option handling" do
it "cert_id short flag from tool options can be used" do
# leaving out the command name defaults to 'renew'
stub_commander_runner_args(['download_all', '-i', 'abcd'])
# download_all takes no params, but we want to expect the call and prevent
# actual execution of the method
expect(Sigh::Manager).to receive(:download_all)
Sigh::CommandsGenerator.start
expect(Sigh.config[:cert_id]).to eq('abcd')
end
it "username short flag from tool options can be used" do
# leaving out the command name defaults to 'renew'
stub_commander_runner_args(['download_all', '-u', 'me@it.com'])
# download_all takes no params, but we want to expect the call and prevent
# actual execution of the method
expect(Sigh::Manager).to receive(:download_all)
Sigh::CommandsGenerator.start
expect(Sigh.config[:username]).to eq('me@it.com')
end
end
describe "repair option handling" do
let(:repair) do
repair = Sigh::Repair.new
expect(Sigh::Repair).to receive(:new).and_return(repair)
repair
end
it "username short flag from tool options can be used" do
# leaving out the command name defaults to 'renew'
stub_commander_runner_args(['repair', '-u', 'me@it.com'])
# repair_all takes no params, but we want to expect the call and prevent
# actual execution of the method
expect(repair).to receive(:repair_all)
Sigh::CommandsGenerator.start
expect(Sigh.config[:username]).to eq('me@it.com')
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/spec/resign_spec.rb | sigh/spec/resign_spec.rb | describe Sigh do
describe Sigh::Resign do
IDENTITY_1_NAME = "iPhone Developer: ed.belarus@gmail.com (ABCDEFGHIJ)"
IDENTITY_1_SHA1 = "T123XXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYYYYYY"
IDENTITY_2_NAME = "iPhone Distribution: Some Company LLC (F12345678F)"
IDENTITY_2_SHA1 = "TXXXZZZ123456789098765432101234567890987"
IDENTITY_3_NAME = "iPhone Distribution: Some Company LLC (F12345678F)"
IDENTITY_3_SHA1 = "TB67GKJDDWEHHKEYW67G6DK8654HF6AZMJDG875D"
VALID_IDENTITIES_OUTPUT = "
1) #{IDENTITY_1_SHA1} \"#{IDENTITY_1_NAME}\"
2) #{IDENTITY_2_SHA1} \"#{IDENTITY_2_NAME}\"
3) #{IDENTITY_3_SHA1} \"#{IDENTITY_3_NAME}\"
3 valid identities found"
before do
@resign = Sigh::Resign.new
end
it "Create provisioning options from hash" do
tmp_path = Dir.mktmpdir
provisioning_profiles = {
"at.fastlane" => "#{tmp_path}/folder/mobile.mobileprovision",
"at.fastlane.today" => "#{tmp_path}/folder/mobile.today.mobileprovision"
}
provisioning_options = @resign.create_provisioning_options(provisioning_profiles)
expect(provisioning_options).to eq("-p at.fastlane=#{tmp_path}/folder/mobile.mobileprovision -p at.fastlane.today=#{tmp_path}/folder/mobile.today.mobileprovision")
end
it "Create provisioning options from array" do
tmp_path = Dir.mktmpdir
provisioning_profiles = ["#{tmp_path}/folder/mobile.mobileprovision"]
provisioning_options = @resign.create_provisioning_options(provisioning_profiles)
expect(provisioning_options).to eq("-p #{tmp_path}/folder/mobile.mobileprovision")
end
it "Installed identities parser" do
stub_request_valid_identities(@resign, VALID_IDENTITIES_OUTPUT)
actualresult = @resign.installed_identities
expect(actualresult.keys.count).to eq(3)
expect(actualresult[IDENTITY_1_SHA1]).to eq(IDENTITY_1_NAME)
expect(actualresult[IDENTITY_2_SHA1]).to eq(IDENTITY_2_NAME)
expect(actualresult[IDENTITY_3_SHA1]).to eq(IDENTITY_3_NAME)
end
it "Installed identities descriptions" do
stub_request_valid_identities(@resign, VALID_IDENTITIES_OUTPUT)
actualresult = @resign.installed_identity_descriptions
result = [IDENTITY_1_NAME, "\t#{IDENTITY_1_SHA1}", IDENTITY_2_NAME, "\t#{IDENTITY_2_SHA1}", "\t#{IDENTITY_3_SHA1}"]
expect(actualresult).to eq(result)
end
it "SHA1 for identity with name input" do
stub_request_valid_identities(@resign, VALID_IDENTITIES_OUTPUT)
actualresult = @resign.sha1_for_signing_identity(IDENTITY_3_NAME)
# due to order of of identities in the VALID_IDENTITIES_OUTPUT and since names of identities 2) and 3) are equal
# sha1_for_signing_identity(name) returns first matching SHA1 for identity name
expect(actualresult).to eq(IDENTITY_2_SHA1)
end
it "SHA1 for identity with SHA1 input" do
stub_request_valid_identities(@resign, VALID_IDENTITIES_OUTPUT)
actualresult = @resign.sha1_for_signing_identity(IDENTITY_1_SHA1)
expect(actualresult).to eq(IDENTITY_1_SHA1)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/spec/manager_spec.rb | sigh/spec/manager_spec.rb | describe Sigh do
describe Sigh::Manager do
before do
ENV["DELIVER_USER"] = "test@fastlane.tools"
ENV["DELIVER_PASSWORD"] = "123"
end
let(:mock_base_client) { "fake api base client" }
before(:each) do
allow(mock_base_client).to receive(:login)
allow(mock_base_client).to receive(:team_id).and_return('')
allow(Spaceship::ConnectAPI::Provisioning::Client).to receive(:instance).and_return(mock_base_client)
end
it "Successful run" do
sigh_stub_spaceship_connect(inhouse: false, create_profile_app_identifier: "com.krausefx.app", all_app_identifiers: ["com.krausefx.app"])
options = { app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
val = Sigh::Manager.start
expect(val).to eq(File.expand_path("./AppStore_com.krausefx.app.mobileprovision"))
File.delete(val)
end
it "Invalid profile not force run" do
sigh_stub_spaceship_connect(inhouse: false, create_profile_app_identifier: "com.krausefx.app", all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["No dupe here"] }, valid_profiles: false)
options = { app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
val = Sigh::Manager.start
expect(val).to eq(File.expand_path("./AppStore_com.krausefx.app.mobileprovision"))
File.delete(val)
end
it "Invalid profile force run" do
sigh_stub_spaceship_connect(inhouse: false, create_profile_app_identifier: "com.krausefx.app", all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["No dupe here"] }, valid_profiles: false, expect_delete: true)
options = { app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, force: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
val = Sigh::Manager.start
expect(val).to eq(File.expand_path("./AppStore_com.krausefx.app.mobileprovision"))
File.delete(val)
end
it "Existing profile fail on name taken" do
sigh_stub_spaceship_connect(inhouse: false, create_profile_app_identifier: nil, all_app_identifiers: ["com.krausefx.app", "com.krausefx.app.other"], app_identifier_and_profile_names: { "com.krausefx.app.other" => ["com.krausefx.app AppStore"] })
options = { app_identifier: "com.krausefx.app", skip_install: true, fail_on_name_taken: true, skip_certificate_verification: true, force: false }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect { Sigh::Manager.start }.to raise_error("The name 'com.krausefx.app AppStore' is already taken, and fail_on_name_taken is true")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/spec/runner_spec.rb | sigh/spec/runner_spec.rb | describe Sigh do
describe Sigh::Runner do
before do
ENV["DELIVER_USER"] = "test@fastlane.tools"
ENV["DELIVER_PASSWORD"] = "123"
end
let(:fake_runner) { Sigh::Runner.new }
let(:mock_base_client) { "fake api base client" }
before(:each) do
allow(mock_base_client).to receive(:login)
allow(mock_base_client).to receive(:team_id).and_return('')
allow(Spaceship::ConnectAPI::Provisioning::Client).to receive(:instance).and_return(mock_base_client)
end
describe "#run" do
end
describe "#profile_type" do
profile_types = {
"ios" => {
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_STORE => { in_house: false, options: { platform: "ios" } },
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE => { in_house: true, options: { platform: "ios" } },
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_ADHOC => { in_house: false, options: { platform: "ios", adhoc: true } },
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_DEVELOPMENT => { in_house: false, options: { platform: "ios", development: true } }
},
"tvos" => {
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_STORE => { in_house: false, options: { platform: "tvos" } },
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE => { in_house: true, options: { platform: "tvos" } },
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_ADHOC => { in_house: false, options: { platform: "tvos", adhoc: true } },
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_DEVELOPMENT => { in_house: false, options: { platform: "tvos", development: true } }
},
"macos" => {
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_STORE => { in_house: false, options: { platform: "macos" } },
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE => { in_house: true, options: { platform: "macos" } },
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DEVELOPMENT => { in_house: false, options: { platform: "macos", development: true } },
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DIRECT => { in_house: false, options: { platform: "macos", developer_id: true } }
},
"catalyst" => {
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_STORE => { in_house: false, options: { platform: "catalyst" } },
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE => { in_house: true, options: { platform: "catalyst" } },
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DEVELOPMENT => { in_house: false, options: { platform: "catalyst", development: true } },
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DIRECT => { in_house: false, options: { platform: "catalyst", developer_id: true } }
}
}
# Iterates over platforms
profile_types.each do |platform, test|
context platform do
# Creates test for each profile type in platform
test.each do |type, test_options|
it type do
sigh_stub_spaceship_connect(inhouse: test_options[:in_house])
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, test_options[:options])
expect(fake_runner.profile_type).to eq(type)
end
end
end
end
end
describe "#fetch_profiles" do
context "successfully" do
it "with skip verification" do
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["No dupe here"] })
options = { app_identifier: "com.krausefx.app", skip_certificate_verification: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profiles = fake_runner.fetch_profiles
expect(profiles.size).to eq(1)
end
it "on mac without skip verification" do
expect(FastlaneCore::Helper).to receive(:mac?).and_return(true)
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["No dupe here"] })
options = { app_identifier: "com.krausefx.app" }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect(FastlaneCore::CertChecker).to receive(:installed?).with(anything).and_return(true)
profiles = fake_runner.fetch_profiles
expect(profiles.size).to eq(1)
end
it "on non-mac without skip verification" do
expect(FastlaneCore::Helper).to receive(:mac?).and_return(false)
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["No dupe here"] })
options = { app_identifier: "com.krausefx.app" }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect(FastlaneCore::CertChecker).not_to receive(:installed?).with(anything)
profiles = fake_runner.fetch_profiles
expect(profiles.size).to eq(1)
end
it "with cert_id filter" do
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["No dupe here"] })
options = { app_identifier: "com.krausefx.app", skip_certificate_verification: true, cert_id: "123456789" }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profiles = fake_runner.fetch_profiles
expect(profiles.size).to eq(1)
end
end
context "unsuccessfully" do
it "on mac without skip verification" do
expect(FastlaneCore::Helper).to receive(:mac?).and_return(true)
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["No dupe here"] })
options = { app_identifier: "com.krausefx.app", skip_certificate_verification: false }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect(FastlaneCore::CertChecker).to receive(:installed?).with(anything).and_return(false)
profiles = fake_runner.fetch_profiles
expect(profiles.size).to eq(0)
end
it "with cert_id filter" do
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["No dupe here"] })
options = { app_identifier: "com.krausefx.app", skip_certificate_verification: true, cert_id: "987654321" }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profiles = fake_runner.fetch_profiles
expect(profiles.size).to eq(0)
end
end
end
describe "#devices_to_use" do
it "no devices for app store" do
options = {}
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect(Spaceship::ConnectAPI::Device).not_to(receive(:devices_for_platform))
devices = fake_runner.devices_to_use
expect(devices.size).to eq(0)
end
it "no devices for developer id" do
options = { developer_id: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect(Spaceship::ConnectAPI::Device).not_to(receive(:devices_for_platform))
devices = fake_runner.devices_to_use
expect(devices.size).to eq(0)
end
it "devices for development" do
options = { development: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect(Spaceship::ConnectAPI::Device).to receive(:devices_for_platform).and_return(["device"])
devices = fake_runner.devices_to_use
expect(devices.size).to eq(1)
end
it "devices for development with apple silicon" do
options = { development: true, include_mac_in_profiles: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect(Spaceship::ConnectAPI::Device).to receive(:devices_for_platform).and_return(["ios_device", "as_device"])
devices = fake_runner.devices_to_use
expect(devices.size).to eq(2)
end
it "devices for adhoc" do
options = { adhoc: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect(Spaceship::ConnectAPI::Device).to receive(:devices_for_platform).and_return(["device"])
devices = fake_runner.devices_to_use
expect(devices.size).to eq(1)
end
end
describe "#certificates_to_use" do
it "list certificates found when there're multiple certificates and not in development" do
options = { skip_certificate_verification: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
sigh_stub_spaceship_connect
certificates_to_use = fake_runner.certificates_to_use
expect(certificates_to_use.size).to eq(1)
end
it "list certificates found when there're multiple certificates and in development" do
options = { include_all_certificates: true, development: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
sigh_stub_spaceship_connect
certificates_to_use = fake_runner.certificates_to_use
expect(certificates_to_use.size).to eq(2)
end
end
describe "#profile_type_pretty_type" do
profile_types = {
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_STORE => "AppStore",
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE => "InHouse",
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_ADHOC => "AdHoc",
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_DEVELOPMENT => "Development",
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_STORE => "AppStore",
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE => "InHouse",
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_ADHOC => "AdHoc",
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_DEVELOPMENT => "Development",
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_STORE => "AppStore",
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DEVELOPMENT => "Development",
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DIRECT => "Direct",
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE => "InHouse",
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_STORE => "AppStore",
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DEVELOPMENT => "Development",
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DIRECT => "Direct",
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE => "InHouse"
}
# Creates test for each profile type
profile_types.each do |type, pretty_type|
it "#{type} - #{pretty_type}" do
allow(fake_runner).to receive(:profile_type).and_return(type)
expect(fake_runner.profile_type_pretty_type).to eq(pretty_type)
end
end
end
describe "#create_profile!" do
context "successfully creates profile" do
it "skips fetching of profiles" do
sigh_stub_spaceship_connect(inhouse: false, create_profile_app_identifier: "com.krausefx.app", all_app_identifiers: ["com.krausefx.app"])
options = { app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, skip_fetch_profiles: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profile = fake_runner.create_profile!
expect(profile.name).to eq("com.krausefx.app AppStore")
expect(profile.bundle_id.identifier).to eq("com.krausefx.app")
end
it "skips fetches profiles with no duplicate name" do
sigh_stub_spaceship_connect(inhouse: false, create_profile_app_identifier: "com.krausefx.app", all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["No dupe here"] })
options = { app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, skip_fetch_profiles: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profile = fake_runner.create_profile!
expect(profile.name).to eq("com.krausefx.app AppStore")
expect(profile.bundle_id.identifier).to eq("com.krausefx.app")
end
it "fetches profiles with duplicate name and appends timestamp" do
sigh_stub_spaceship_connect(inhouse: false, create_profile_app_identifier: "com.krausefx.app", all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["com.krausefx.app AppStore"] })
allow(Time).to receive(:now).and_return(Time.at(1_608_653_743))
options = { app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, skip_fetch_profiles: false }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profile = fake_runner.create_profile!
expect(profile.name).to eq("com.krausefx.app AppStore 1608653743")
expect(profile.bundle_id.identifier).to eq("com.krausefx.app")
end
end
context "raises error" do
it "when cannot find bundle id" do
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: [])
options = { app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, skip_fetch_profiles: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect do
fake_runner.create_profile!
end.to raise_error("Could not find App with App Identifier 'com.krausefx.app'")
end
it "when name already taken" do
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: ["com.krausefx.app"], app_identifier_and_profile_names: { "com.krausefx.app" => ["com.krausefx.app AppStore"] })
options = { app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, skip_fetch_profiles: false, fail_on_name_taken: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
expect do
fake_runner.create_profile!
end.to raise_error("The name 'com.krausefx.app AppStore' is already taken, and fail_on_name_taken is true")
end
end
end
describe "#download_profile" do
it "ios" do
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: [])
options = { platform: "ios", app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, skip_fetch_profiles: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profile = Spaceship::ConnectAPI::Profile.new("123", {
profileContent: Base64.encode64("12345")
})
path = fake_runner.download_profile(profile)
expect(path).to end_with("AppStore_com.krausefx.app.mobileprovision")
expect(File.binread(path)).to eq("12345")
end
it "tvos" do
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: [])
options = { platform: "tvos", app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, skip_fetch_profiles: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profile = Spaceship::ConnectAPI::Profile.new("123", {
profileContent: Base64.encode64("12345")
})
path = fake_runner.download_profile(profile)
expect(path).to end_with("AppStore_com.krausefx.app_tvos.mobileprovision")
expect(File.binread(path)).to eq("12345")
end
it "macos" do
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: [])
options = { platform: "macos", app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, skip_fetch_profiles: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profile = Spaceship::ConnectAPI::Profile.new("123", {
profileContent: Base64.encode64("12345")
})
path = fake_runner.download_profile(profile)
expect(path).to end_with("AppStore_com.krausefx.app.provisionprofile")
expect(File.binread(path)).to eq("12345")
end
it "catalyst" do
sigh_stub_spaceship_connect(inhouse: false, all_app_identifiers: [])
options = { platform: "catalyst", app_identifier: "com.krausefx.app", skip_install: true, skip_certificate_verification: true, skip_fetch_profiles: true }
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options)
profile = Spaceship::ConnectAPI::Profile.new("123", {
profileContent: Base64.encode64("12345")
})
path = fake_runner.download_profile(profile)
expect(path).to end_with("AppStore_com.krausefx.app_catalyst.provisionprofile")
expect(File.binread(path)).to eq("12345")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/spec/spec_helper.rb | sigh/spec/spec_helper.rb | def sigh_stub_spaceship_connect(inhouse: false, create_profile_app_identifier: nil, all_app_identifiers: [], app_identifier_and_profile_names: {}, valid_profiles: true, expect_delete: false)
allow(Spaceship::ConnectAPI).to receive(:login).and_return(nil)
allow(Spaceship::ConnectAPI).to receive(:client).and_return("client")
allow(Spaceship::ConnectAPI).to receive(:select_team).and_return(nil)
allow(Spaceship::ConnectAPI.client).to receive(:in_house?).and_return(inhouse)
# Mock cert
certificate = "certificate"
allow(certificate).to receive(:id).and_return("123456789")
allow(certificate).to receive(:display_name).and_return("Roger Oba")
allow(certificate).to receive(:expiration_date).and_return("2021-07-22T00:27:42.000+0000")
allow(certificate).to receive(:certificate_content).and_return(Base64.encode64("cert content"))
allow(Spaceship::ConnectAPI::Certificate).to receive(:all).and_return([certificate, certificate])
device = "device"
allow(device).to receive(:id).and_return(1)
allow(Spaceship::ConnectAPI::Device).to receive(:devices_for_platform).and_return([device])
bundle_ids = all_app_identifiers.map do |id|
Spaceship::ConnectAPI::BundleId.new("123", {
identifier: id,
name: id,
seedId: "seed",
platform: "IOS"
})
end
allow(Spaceship::ConnectAPI::BundleId).to receive(:find).with(anything).and_return(nil)
bundle_ids.each do |bundle_id|
allow(Spaceship::ConnectAPI::BundleId).to receive(:find).with(bundle_id.identifier).and_return(bundle_id)
end
if create_profile_app_identifier
bundle_id = bundle_ids.find { |b| b.identifier.to_s == create_profile_app_identifier }
expect(Spaceship::ConnectAPI::Profile).to receive(:create).with(anything) do |value|
profile = Spaceship::ConnectAPI::Profile.new("123", {
name: value[:name],
platform: "IOS",
profileState: Spaceship::ConnectAPI::Profile::ProfileState::ACTIVE,
profileContent: Base64.encode64("profile content")
})
allow(profile).to receive(:bundle_id).and_return(bundle_id)
allow(profile).to receive(:expiration_date).and_return(Date.today.next_year.to_time.utc.strftime("%Y-%m-%dT%H:%M:%S%:z"))
profile
end
end
profiles = []
app_identifier_and_profile_names.each do |app_identifier, profile_names|
profiles += profile_names.map do |name|
bundle_id = bundle_ids.find { |b| b.identifier.to_s == app_identifier.to_s }
raise "Could not find BundleId for #{app_identifier} in #{bundle_ids.map(&:identifier)}" unless bundle_id
profile = Spaceship::ConnectAPI::Profile.new("123", {
name: name,
platform: "IOS",
profileState: valid_profiles ? Spaceship::ConnectAPI::Profile::ProfileState::ACTIVE : Spaceship::ConnectAPI::Profile::ProfileState::INVALID,
profileContent: Base64.encode64("profile content")
})
allow(profile).to receive(:bundle_id).and_return(bundle_id)
allow(profile).to receive(:certificates).and_return([certificate])
expect(profile).to receive(:delete!) if expect_delete
if valid_profiles
allow(profile).to receive(:expiration_date).and_return(Date.today.next_year.to_time.utc.strftime("%Y-%m-%dT%H:%M:%S%:z"))
else
allow(profile).to receive(:expiration_date).and_return(Date.today.prev_year.to_time.utc.strftime("%Y-%m-%dT%H:%M:%S%:z"))
end
profile
end
end
allow(Spaceship::ConnectAPI::Profile).to receive(:all).and_return(profiles)
profiles.each do |profile|
allow(Spaceship::ConnectAPI::Profile).to receive(:all).with(filter: { name: profile.name }).and_return([profile])
end
# Stubs production to only receive certs
certs = [Spaceship.certificate.production]
certs.each do |current|
allow(current).to receive(:all).and_return([certificate])
end
# apple_distribution also gets called for Xcode 11 profiles
# so need to stub and empty array return
certs = [Spaceship.certificate.apple_distribution]
certs.each do |current|
allow(current).to receive(:all).and_return([])
end
end
def sigh_stub_spaceship(valid_profile = true, expect_create = false, expect_delete = false, fail_delete = false)
profile = "profile"
certificate = "certificate"
profiles_after_delete = expect_delete && !fail_delete ? [] : [profile]
expect(Spaceship).to receive(:login).and_return(nil)
allow(Spaceship).to receive(:client).and_return("client")
expect(Spaceship).to receive(:select_team).and_return(nil)
expect(Spaceship.client).to receive(:in_house?).and_return(false)
allow(Spaceship.app).to receive(:find).and_return(true)
allow(Spaceship.provisioning_profile).to receive(:all).and_return(profiles_after_delete)
allow(profile).to receive(:valid?).and_return(valid_profile)
allow(profile.class).to receive(:pretty_type).and_return("pretty")
allow(profile).to receive(:download).and_return("FileContent")
allow(profile).to receive(:name).and_return("com.krausefx.app AppStore")
if expect_delete
expect(profile).to receive(:delete!)
else
expect(profile).to_not(receive(:delete!))
end
profile_type = Spaceship.provisioning_profile.app_store
allow(profile_type).to receive(:find_by_bundle_id).and_return([profile])
if expect_create
expect(profile_type).to receive(:create!).and_return(profile)
else
expect(profile_type).to_not(receive(:create!))
end
# Stubs production to only receive certs
certs = [Spaceship.certificate.production]
certs.each do |current|
allow(current).to receive(:all).and_return([certificate])
end
# apple_distribution also gets called for Xcode 11 profiles
# so need to stub and empty array return
certs = [Spaceship.certificate.apple_distribution]
certs.each do |current|
allow(current).to receive(:all).and_return([])
end
end
def stub_request_valid_identities(resign, value)
expect(resign).to receive(:request_valid_identities).and_return(value)
end
# Commander::Command::Options does not define sane equals behavior,
# so we need this to make testing easier
RSpec::Matchers.define(:match_commander_options) do |expected|
match { |actual| actual.__hash__ == expected.__hash__ }
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh.rb | sigh/lib/sigh.rb | require_relative 'sigh/resign'
require_relative 'sigh/manager'
require_relative 'sigh/options'
require_relative 'sigh/local_manage'
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh/options.rb | sigh/lib/sigh/options.rb | require 'fastlane_core/configuration/configuration'
require 'credentials_manager/appfile_config'
require_relative 'module'
require 'spaceship/connect_api/models/device'
require 'spaceship/connect_api/models/certificate'
require 'spaceship/connect_api/models/bundle_id'
require 'spaceship/connect_api/models/profile'
module Sigh
class Options
def self.available_options
user = CredentialsManager::AppfileConfig.try_fetch_value(:apple_dev_portal_id)
user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)
[
FastlaneCore::ConfigItem.new(key: :adhoc,
env_name: "SIGH_AD_HOC",
description: "Setting this flag will generate AdHoc profiles instead of App Store Profiles",
is_string: false,
default_value: false,
conflicting_options: [:developer_id, :development],
conflict_block: proc do |option|
UI.user_error!("You can't enable both :#{option.key} and :adhoc")
end),
FastlaneCore::ConfigItem.new(key: :developer_id,
env_name: "SIGH_DEVELOPER_ID",
description: "Setting this flag will generate Developer ID profiles instead of App Store Profiles",
is_string: false,
default_value: false,
conflicting_options: [:adhoc, :development],
conflict_block: proc do |option|
UI.user_error!("You can't enable both :#{option.key} and :developer_id")
end),
FastlaneCore::ConfigItem.new(key: :development,
env_name: "SIGH_DEVELOPMENT",
description: "Renew the development certificate instead of the production one",
is_string: false,
default_value: false,
conflicting_options: [:adhoc, :developer_id],
conflict_block: proc do |option|
UI.user_error!("You can't enable both :#{option.key} and :development")
end),
FastlaneCore::ConfigItem.new(key: :skip_install,
env_name: "SIGH_SKIP_INSTALL",
description: "By default, the certificate will be added to your local machine. Setting this flag will skip this action",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :force,
env_name: "SIGH_FORCE",
description: "Renew provisioning profiles regardless of its state - to automatically add all devices for ad hoc profiles",
is_string: false,
short_option: "-f",
default_value: false),
FastlaneCore::ConfigItem.new(key: :include_mac_in_profiles,
env_name: "SIGH_INCLUDE_MAC_IN_PROFILES",
description: "Include Apple Silicon Mac devices in provisioning profiles for iOS/iPadOS apps",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :app_identifier,
short_option: "-a",
env_name: "SIGH_APP_IDENTIFIER",
description: "The bundle identifier of your app",
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier),
default_value_dynamic: true),
# App Store Connect API
FastlaneCore::ConfigItem.new(key: :api_key_path,
env_names: ["SIGH_API_KEY_PATH", "APP_STORE_CONNECT_API_KEY_PATH"],
description: "Path to your App Store Connect API Key JSON file (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-json-file)",
optional: true,
conflicting_options: [:api_key],
verify_block: proc do |value|
UI.user_error!("Couldn't find API key JSON file at path '#{value}'") unless File.exist?(value)
end),
FastlaneCore::ConfigItem.new(key: :api_key,
env_names: ["SIGH_API_KEY", "APP_STORE_CONNECT_API_KEY"],
description: "Your App Store Connect API Key information (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-hash-option)",
type: Hash,
optional: true,
sensitive: true,
conflicting_options: [:api_key_path]),
# Apple ID
FastlaneCore::ConfigItem.new(key: :username,
short_option: "-u",
env_name: "SIGH_USERNAME",
description: "Your Apple ID Username",
optional: true,
default_value: user,
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :team_id,
short_option: "-b",
env_name: "SIGH_TEAM_ID",
description: "The ID of your Developer Portal team if you're in multiple teams",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_id),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_TEAM_ID"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :team_name,
short_option: "-l",
env_name: "SIGH_TEAM_NAME",
description: "The name of your Developer Portal team if you're in multiple teams",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_name),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_TEAM_NAME"] = value.to_s
end),
# Other options
FastlaneCore::ConfigItem.new(key: :provisioning_name,
short_option: "-n",
env_name: "SIGH_PROVISIONING_PROFILE_NAME",
description: "The name of the profile that is used on the Apple Developer Portal",
optional: true),
FastlaneCore::ConfigItem.new(key: :ignore_profiles_with_different_name,
env_name: "SIGH_IGNORE_PROFILES_WITH_DIFFERENT_NAME",
description: "Use in combination with :provisioning_name - when true only profiles matching this exact name will be downloaded",
optional: true,
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :output_path,
short_option: "-o",
env_name: "SIGH_OUTPUT_PATH",
description: "Directory in which the profile should be stored",
default_value: "."),
FastlaneCore::ConfigItem.new(key: :cert_id,
short_option: "-i",
env_name: "SIGH_CERTIFICATE_ID",
description: "The ID of the code signing certificate to use (e.g. 78ADL6LVAA) ",
optional: true),
FastlaneCore::ConfigItem.new(key: :cert_owner_name,
short_option: "-c",
env_name: "SIGH_CERTIFICATE",
description: "The certificate name to use for new profiles, or to renew with. (e.g. \"Felix Krause\")",
optional: true),
FastlaneCore::ConfigItem.new(key: :filename,
short_option: "-q",
env_name: "SIGH_PROFILE_FILE_NAME",
optional: true,
description: "Filename to use for the generated provisioning profile (must include .mobileprovision)",
verify_block: proc do |value|
UI.user_error!("The output name must end with .mobileprovision") unless value.end_with?(".mobileprovision")
end),
FastlaneCore::ConfigItem.new(key: :skip_fetch_profiles,
env_name: "SIGH_SKIP_FETCH_PROFILES",
description: "Skips the verification of existing profiles which is useful if you have thousands of profiles",
is_string: false,
default_value: false,
short_option: "-w"),
FastlaneCore::ConfigItem.new(key: :include_all_certificates,
env_name: "SIGH_INCLUDE_ALL_CERTIFICATES",
description: "Include all matching certificates in the provisioning profile. Works only for the 'development' provisioning profile type",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :skip_certificate_verification,
short_option: '-z',
env_name: "SIGH_SKIP_CERTIFICATE_VERIFICATION",
description: "Skips the verification of the certificates for every existing profiles. This will make sure the provisioning profile can be used on the local machine",
is_string: false,
default_value: !FastlaneCore::Helper.mac?,
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :platform,
short_option: '-p',
env_name: "SIGH_PLATFORM",
description: "Set the provisioning profile's platform (i.e. ios, tvos, macos, catalyst)",
is_string: false,
default_value: "ios",
verify_block: proc do |value|
value = value.to_s
pt = %w(macos tvos ios catalyst)
UI.user_error!("Unsupported platform, must be: #{pt}") unless pt.include?(value)
end),
FastlaneCore::ConfigItem.new(key: :readonly,
env_name: "SIGH_READONLY",
description: "Only fetch existing profile, don't generate new ones",
optional: true,
is_string: false,
default_value: false,
conflicting_options: [:force],
conflict_block: proc do |value|
UI.user_error!("You can't enable both :force and :readonly")
end),
FastlaneCore::ConfigItem.new(key: :template_name,
env_name: "SIGH_PROVISIONING_PROFILE_TEMPLATE_NAME",
description: "The name of provisioning profile template. If the developer account has provisioning profile templates (aka: custom entitlements), the template name can be found by inspecting the Entitlements drop-down while creating/editing a provisioning profile (e.g. \"Apple Pay Pass Suppression Development\")",
optional: true,
deprecated: "Removed since May 2025 on App Store Connect API OpenAPI v3.8.0 - Learn more: https://docs.fastlane.tools/actions/match/#managed-capabilities",
default_value: nil),
FastlaneCore::ConfigItem.new(key: :fail_on_name_taken,
env_name: "SIGH_FAIL_ON_NAME_TAKEN",
description: "Should the command fail if it was about to create a duplicate of an existing provisioning profile. It can happen due to issues on Apple Developer Portal, when profile to be recreated was not properly deleted first",
optional: true,
is_string: false,
default_value: false),
# Cache
FastlaneCore::ConfigItem.new(key: :cached_certificates,
description: "A list of cached certificates",
optional: true,
is_string: false,
default_value: nil,
verify_block: proc do |value|
next if value.nil?
if !value.kind_of?(Array) ||
!value.all?(Spaceship::ConnectAPI::Certificate)
UI.user_error!("cached_certificates parameter must be an array of Spaceship::ConnectAPI::Certificate") unless value.kind_of?(Array)
end
end),
FastlaneCore::ConfigItem.new(key: :cached_devices,
description: "A list of cached devices",
optional: true,
is_string: false,
default_value: nil,
verify_block: proc do |value|
next if value.nil?
if !value.kind_of?(Array) ||
!value.all?(Spaceship::ConnectAPI::Device)
UI.user_error!("cached_devices parameter must be an array of Spaceship::ConnectAPI::Device")
end
end),
FastlaneCore::ConfigItem.new(key: :cached_bundle_ids,
description: "A list of cached bundle ids",
optional: true,
is_string: false,
default_value: nil,
verify_block: proc do |value|
next if value.nil?
if !value.kind_of?(Array) ||
!value.all?(Spaceship::ConnectAPI::BundleId)
UI.user_error!("cached_bundle_ids parameter must be an array of Spaceship::ConnectAPI::BundleId")
end
end),
FastlaneCore::ConfigItem.new(key: :cached_profiles,
description: "A list of cached bundle ids",
optional: true,
is_string: false,
default_value: nil,
verify_block: proc do |value|
next if value.nil?
if !value.kind_of?(Array) ||
!value.all?(Spaceship::ConnectAPI::Profile)
UI.user_error!("cached_profiles parameter must be an array of Spaceship::ConnectAPI::Profile")
end
end)
]
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh/commands_generator.rb | sigh/lib/sigh/commands_generator.rb | require 'commander'
require 'fastlane/version'
require 'fastlane_core/ui/help_formatter'
require_relative 'options'
require_relative 'resign'
require_relative 'local_manage'
require_relative 'manager'
HighLine.track_eof = false
module Sigh
class CommandsGenerator
include Commander::Methods
def self.start
self.new.run
end
def run
program :name, 'sigh'
program :version, Fastlane::VERSION
program :description, 'CLI for \'sigh\' - Because you would rather spend your time building stuff than fighting provisioning'
program :help, 'Author', 'Felix Krause <sigh@krausefx.com>'
program :help, 'Website', 'https://fastlane.tools'
program :help, 'Documentation', 'https://docs.fastlane.tools/actions/sigh/'
program :help_formatter, FastlaneCore::HelpFormatter
global_option('--verbose') { FastlaneCore::Globals.verbose = true }
global_option('--env STRING[,STRING2]', String, 'Add environment(s) to use with `dotenv`')
command :renew do |c|
c.syntax = 'fastlane sigh renew'
c.description = 'Renews the certificate (in case it expired) and outputs the path to the generated file'
FastlaneCore::CommanderGenerator.new.generate(Sigh::Options.available_options, command: c)
c.action do |args, options|
user_input = options.__hash__
# The user might run sigh using
#
# sigh development
#
# sigh adhoc -u user@krausefx.com
#
# When the user runs this, it will use :development
#
# sigh development --adhoc
#
case args.first
when "development"
user_input[:development] = true
user_input.delete(:adhoc)
when "adhoc"
user_input[:adhoc] = true
user_input.delete(:development)
end
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, user_input)
Sigh::Manager.start
end
end
command :download_all do |c|
c.syntax = 'fastlane sigh download_all'
c.description = 'Downloads all valid provisioning profiles'
c.option('--download_xcode_profiles', 'Only works with `fastlane sigh download_all` command: Also download Xcode managed provisioning profiles')
FastlaneCore::CommanderGenerator.new.generate(Sigh::Options.available_options, command: c)
c.action do |args, options|
# Below is some custom code to get an extra flag that's only available
# for the `fastlane sigh download_all` command and not for the `sigh` action
user_hash = options.__hash__
download_xcode_profiles = options.download_xcode_profiles
if download_xcode_profiles == true
user_hash.delete(:download_xcode_profiles)
end
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, user_hash)
Sigh::Manager.download_all(download_xcode_profiles: download_xcode_profiles)
end
end
command :repair do |c|
c.syntax = 'fastlane sigh repair'
c.description = 'Repairs all expired or invalid provisioning profiles'
FastlaneCore::CommanderGenerator.new.generate(Sigh::Options.available_options, command: c)
c.action do |args, options|
Sigh.config = FastlaneCore::Configuration.create(Sigh::Options.available_options, options.__hash__)
require 'sigh/repair'
Sigh::Repair.new.repair_all
end
end
command :resign do |c|
c.syntax = 'fastlane sigh resign'
c.description = 'Resigns an existing ipa file with the given provisioning profile'
c.option('-i', '--signing_identity STRING', String, 'The signing identity to use. Must match the one defined in the provisioning profile.')
c.option('-x', '--version_number STRING', String, 'Version number to force binary and all nested binaries to use. Changes both CFBundleShortVersionString and CFBundleVersion.')
c.option('-p', '--provisioning_profile PATH', String, '(or BUNDLE_ID=PATH) The path to the provisioning profile which should be used. '\
'Can be provided multiple times if the application contains nested applications and app extensions, which need their own provisioning profile. '\
'The path may be prefixed with a identifier in order to determine which provisioning profile should be used on which app.',
&multiple_values_option_proc(c, "provisioning_profile", &proc { |value| value.split('=', 2) }))
c.option('-d', '--display_name STRING', String, 'Display name to use')
c.option('-e', '--entitlements PATH', String, 'The path to the entitlements file to use.')
c.option('--short_version STRING', String, 'Short version string to force binary and all nested binaries to use (CFBundleShortVersionString).')
c.option('--bundle_version STRING', String, 'Bundle version to force binary and all nested binaries to use (CFBundleVersion).')
c.option('--use_app_entitlements', 'Extract app bundle codesigning entitlements and combine with entitlements from new provisioning profile.')
c.option('-g', '--new_bundle_id STRING', String, 'New application bundle ID (CFBundleIdentifier)')
c.option('--keychain_path STRING', String, 'Path to the keychain that /usr/bin/codesign should use')
c.action do |args, options|
Sigh::Resign.new.run(options, args)
end
end
command :manage do |c|
c.syntax = 'fastlane sigh manage'
c.description = 'Manage installed provisioning profiles on your system.'
c.option('-f', '--force', 'Force remove all expired provisioning profiles. Required on CI.')
c.option('-e', '--clean_expired', 'Remove all expired provisioning profiles.')
c.option('-p', '--clean_pattern STRING', String, 'Remove any provisioning profiles that matches the regular expression.')
c.example('Remove all "iOS Team Provisioning" provisioning profiles', 'fastlane sigh manage -p "iOS\ ?Team Provisioning Profile"')
c.action do |args, options|
Sigh::LocalManage.start(options, args)
end
end
default_command(:renew)
run!
end
def multiple_values_option_proc(command, name)
proc do |value|
value = yield(value) if block_given?
option = command.proxy_options.find { |opt| opt[0] == name } || []
values = option[1] || []
values << value
command.proxy_options.delete(option)
command.proxy_options << [name, values]
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh/runner.rb | sigh/lib/sigh/runner.rb | require 'spaceship'
require 'base64'
require 'fastlane_core/print_table'
require 'fastlane_core/cert_checker'
require_relative 'module'
module Sigh
class Runner
attr_accessor :spaceship
# Uses the spaceship to create or download a provisioning profile
# returns the path the newly created provisioning profile (in /tmp usually)
def run
FastlaneCore::PrintTable.print_values(config: Sigh.config,
hide_keys: [:output_path, :cached_certificates, :cached_devices, :cached_bundle_ids, :cached_profiles],
title: "Summary for sigh #{Fastlane::VERSION}")
if (api_token = Spaceship::ConnectAPI::Token.from(hash: Sigh.config[:api_key], filepath: Sigh.config[:api_key_path]))
UI.message("Creating authorization token for App Store Connect API")
Spaceship::ConnectAPI.token = api_token
elsif !Spaceship::ConnectAPI.token.nil?
UI.message("Using existing authorization token for App Store Connect API")
else
# Username is now optional since addition of App Store Connect API Key
# Force asking for username to prompt user if not already set
Sigh.config.fetch(:username, force_ask: true)
# Team selection passed though FASTLANE_ITC_TEAM_ID and FASTLANE_ITC_TEAM_NAME environment variables
# Prompts select team if multiple teams and none specified
UI.message("Starting login with user '#{Sigh.config[:username]}'")
Spaceship::ConnectAPI.login(Sigh.config[:username], nil, use_portal: true, use_tunes: false)
UI.message("Successfully logged in")
end
profiles = [] if Sigh.config[:skip_fetch_profiles]
profiles ||= fetch_profiles # download the profile if it's there
if profiles.count > 0
UI.success("Found #{profiles.count} matching profile(s)")
profile = profiles.first
if Sigh.config[:force]
# Recreating the profile ensures it has all of the requested properties (cert, name, etc.)
UI.important("Recreating the profile")
profile.delete!
profile = create_profile!
end
else
UI.user_error!("No matching provisioning profile found and cannot create a new one because you enabled `readonly`") if Sigh.config[:readonly]
UI.important("No existing profiles found, that match the certificates you have installed locally! Creating a new provisioning profile for you")
ensure_app_exists!
profile = create_profile!
end
UI.user_error!("Something went wrong fetching the latest profile") unless profile
if [Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE, Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE].include?(profile_type)
ENV["SIGH_PROFILE_ENTERPRISE"] = "1"
else
ENV.delete("SIGH_PROFILE_ENTERPRISE")
end
return download_profile(profile)
end
# The kind of provisioning profile we're interested in
def profile_type
return @profile_type if @profile_type
@profile_type = Sigh.profile_type_for_config(platform: Sigh.config[:platform], in_house: Spaceship::ConnectAPI.client.in_house?, config: Sigh.config)
@profile_type
end
# Fetches a profile matching the user's search requirements
def fetch_profiles
UI.message("Fetching profiles...")
filter = { profileType: profile_type }
# We can greatly speed up the search by filtering on the provisioning profile name
filter[:name] = Sigh.config[:provisioning_name] if Sigh.config[:provisioning_name].to_s.length > 0
includes = 'bundleId'
unless (Sigh.config[:skip_certificate_verification] || Sigh.config[:include_all_certificates]) && Sigh.config[:cert_id].to_s.length == 0
includes += ',certificates'
end
results = Sigh.config[:cached_profiles]
results ||= Spaceship::ConnectAPI::Profile.all(filter: filter, includes: includes)
results.select! do |profile|
profile.bundle_id&.identifier == Sigh.config[:app_identifier]
end
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
# Take the cert_id into account
results = filter_profiles_by_cert_id(results) if Sigh.config[:cert_id].to_s.length > 0
return results if Sigh.config[:skip_certificate_verification] || Sigh.config[:include_all_certificates]
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 = Base64.decode64(cert.certificate_content)
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].force_encoding('UTF-8'))
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
# Don't need to check if certificate is valid because it comes with the
# profile in the response
installed
end
end
def profile_type_pretty_type
return Sigh.profile_pretty_type(profile_type)
end
# Create a new profile and return it
def create_profile!
app_identifier = Sigh.config[:app_identifier]
name = Sigh.config[:provisioning_name] || [app_identifier, profile_type_pretty_type].join(' ')
unless Sigh.config[:skip_fetch_profiles]
# We can greatly speed up the search by filtering on the provisioning profile name
# It seems that there's no way to search for exact match using the API, so we'll need to run additional checks afterwards
profile = Spaceship::ConnectAPI::Profile.all(filter: { name: name }).find { |p| p.name == name }
if profile
UI.user_error!("The name '#{name}' is already taken, and fail_on_name_taken is true") if Sigh.config[:fail_on_name_taken]
UI.error("The name '#{name}' is already taken, using another one.")
name += " #{Time.now.to_i}"
end
end
bundle_ids = Sigh.config[:cached_bundle_ids]
bundle_id = bundle_ids.detect { |e| e.identifier == app_identifier } if bundle_ids
bundle_id ||= Spaceship::ConnectAPI::BundleId.find(app_identifier)
unless bundle_id
UI.user_error!("Could not find App with App Identifier '#{Sigh.config[:app_identifier]}'")
end
UI.important("Creating new provisioning profile for '#{Sigh.config[:app_identifier]}' with name '#{name}' for '#{Sigh.config[:platform]}' platform")
unless Sigh.config[:template_name].nil?
UI.important("Template name is set to '#{Sigh.config[:template_name]}', however, this is not supported by the App Store Connect API anymore, since May 2025. The template name will be ignored. For more information: https://docs.fastlane.tools/actions/match/#managed-capabilities")
end
profile = Spaceship::ConnectAPI::Profile.create(
name: name,
profile_type: profile_type,
bundle_id_id: bundle_id.id,
certificate_ids: certificates_to_use.map(&:id),
device_ids: devices_to_use.map(&:id)
)
profile
end
def filter_profiles_by_name(profiles)
filtered = profiles.select { |p| p.name.strip == Sigh.config[:provisioning_name].strip }
if Sigh.config[:ignore_profiles_with_different_name]
profiles = filtered
elsif (filtered || []).count > 0
profiles = filtered
end
profiles
end
def filter_profiles_by_cert_id(profiles)
filtered = profiles.find_all do |current_profile|
valid_cert_id = false
current_profile.certificates.each do |cert|
if cert.id == Sigh.config[:cert_id].to_s
valid_cert_id = true
else
UI.message("Provisioning Profile cert_id : '#{cert.id}' does not match given cert_id : '#{Sigh.config[:cert_id]}', skipping this one...")
end
end
valid_cert_id
end
filtered
end
def fetch_certificates(certificate_types)
filter = {
certificateType: certificate_types.join(',')
}
certificates = Sigh.config[:cached_certificates]
certificates ||= Spaceship::ConnectAPI::Certificate.all(filter: filter)
return certificates
end
def certificates_for_profile_and_platform
types = Sigh.certificate_types_for_profile_and_platform(platform: Sigh.config[:platform], profile_type: profile_type)
fetch_certificates(types)
end
def devices_to_use
# Only use devices if development or adhoc
return [] if !Sigh.config[:development] && !Sigh.config[:adhoc]
devices = Sigh.config[:cached_devices]
devices ||= Spaceship::ConnectAPI::Device.devices_for_platform(
platform: Sigh.config[:platform],
include_mac_in_profiles: Sigh.config[:include_mac_in_profiles]
)
return devices
end
# Certificate to use based on the current distribution mode
def certificates_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.display_name.strip == Sigh.config[:cert_owner_name].strip
end
true
end
# verify certificates
if Helper.mac?
unless Sigh.config[:skip_certificate_verification] || Sigh.config[:include_all_certificates]
certificates = certificates.find_all do |c|
file = Tempfile.new('cert')
raw_data = Base64.decode64(c.certificate_content)
file.write(raw_data.force_encoding("UTF-8"))
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.display_name, "- ID:", c.id + " - Expires", Time.parse(c.expiration_date).strftime("%Y-%m-%d")].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_pretty_type}'. "
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
# Downloads and stores the provisioning profile
def download_profile(profile)
UI.important("Downloading provisioning profile...")
profile_name ||= "#{profile_type_pretty_type}_#{Sigh.config[:app_identifier]}"
if Sigh.config[:platform].to_s == 'tvos'
profile_name += "_tvos"
elsif Sigh.config[:platform].to_s == 'catalyst'
profile_name += "_catalyst"
end
if ['macos', 'catalyst'].include?(Sigh.config[:platform].to_s)
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|
content = Base64.decode64(profile.profile_content)
f.write(content)
end
UI.success("Successfully downloaded provisioning profile...")
return output_path
end
# Makes sure the current App ID exists. If not, it will show an appropriate error message
def ensure_app_exists!
# Only ensuring by app identifier
# We used to ensure by platform (IOS and MAC_OS) but now apps are
# always UNIVERSAL as of 2020-07-30
return if Spaceship::ConnectAPI::BundleId.find(Sigh.config[:app_identifier])
print_produce_command(Sigh.config)
UI.user_error!("Could not find App with App Identifier '#{Sigh.config[:app_identifier]}'")
end
def print_produce_command(config)
UI.message("")
UI.message("==========================================".yellow)
UI.message("Could not find App ID with bundle identifier '#{config[:app_identifier]}'")
UI.message("You can easily generate a new App ID on the Developer Portal using 'produce':")
UI.message("")
UI.message("fastlane produce -u #{config[:username]} -a #{config[:app_identifier]} --skip_itc".yellow)
UI.message("")
UI.message("You will be asked for any missing information, like the full name of your app")
UI.message("If the app should also be created on App Store Connect, remove the " + "--skip_itc".yellow + " from the command above")
UI.message("==========================================".yellow)
UI.message("")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh/resign.rb | sigh/lib/sigh/resign.rb | require 'shellwords'
require 'fastlane_core/globals'
require_relative 'module'
module Sigh
# Resigns an existing ipa file
class Resign
def run(options, args)
# get the command line inputs and parse those into the vars we need...
ipa, signing_identity, provisioning_profiles, entitlements, version, display_name, short_version, bundle_version, new_bundle_id, use_app_entitlements, keychain_path = get_inputs(options, args)
# ... then invoke our programmatic interface with these vars
unless resign(ipa, signing_identity, provisioning_profiles, entitlements, version, display_name, short_version, bundle_version, new_bundle_id, use_app_entitlements, keychain_path)
UI.user_error!("Failed to re-sign .ipa")
end
end
def self.resign(ipa, signing_identity, provisioning_profiles, entitlements, version, display_name, short_version, bundle_version, new_bundle_id, use_app_entitlements, keychain_path)
self.new.resign(ipa, signing_identity, provisioning_profiles, entitlements, version, display_name, short_version, bundle_version, new_bundle_id, use_app_entitlements, keychain_path)
end
def resign(ipa, signing_identity, provisioning_profiles, entitlements, version, display_name, short_version, bundle_version, new_bundle_id, use_app_entitlements, keychain_path)
resign_path = find_resign_path
if keychain_path
keychain_path_absolute = File.expand_path(keychain_path)
current_keychains = `security list-keychains`
current_keychains.delete!("\n")
unless current_keychains.include?(keychain_path_absolute)
previous_keychains = current_keychains
`security list-keychains -s #{current_keychains} '#{keychain_path_absolute}'`
end
end
signing_identity = find_signing_identity(signing_identity)
unless provisioning_profiles.kind_of?(Enumerable)
provisioning_profiles = [provisioning_profiles]
end
# validate that we have valid values for all these params, we don't need to check signing_identity because `find_signing_identity` will only ever return a valid value
validate_params(resign_path, ipa, provisioning_profiles)
entitlements = "-e #{entitlements.shellescape}" if entitlements
provisioning_options = create_provisioning_options(provisioning_profiles)
version = "-n #{version}" if version
display_name = "-d #{display_name.shellescape}" if display_name
short_version = "--short-version #{short_version}" if short_version
bundle_version = "--bundle-version #{bundle_version}" if bundle_version
verbose = "-v" if FastlaneCore::Globals.verbose?
bundle_id = "-b '#{new_bundle_id}'" if new_bundle_id
use_app_entitlements_flag = "--use-app-entitlements" if use_app_entitlements
specific_keychain = "--keychain-path #{keychain_path.shellescape}" if keychain_path
command = [
resign_path.shellescape,
ipa.shellescape,
signing_identity.shellescape,
provisioning_options, # we are already shellescaping this above, when we create the provisioning_options from the provisioning_profiles
entitlements,
version,
display_name,
short_version,
bundle_version,
use_app_entitlements_flag,
verbose,
bundle_id,
specific_keychain,
ipa.shellescape # Output path must always be last argument
].join(' ')
puts(command.magenta)
puts(`#{command}`)
if $?.to_i == 0
UI.success("Successfully signed #{ipa}!")
true
else
UI.error("Something went wrong while code signing #{ipa}")
false
end
ensure
`security list-keychains -s #{previous_keychains}` if previous_keychains
end
def get_inputs(options, args)
ipa = args.first || find_ipa || UI.input('Path to ipa file: ')
signing_identity = options.signing_identity || ask_for_signing_identity
provisioning_profiles = options.provisioning_profile || find_provisioning_profile || UI.input('Path to provisioning file: ')
entitlements = options.entitlements || nil
version = options.version_number || nil
display_name = options.display_name || nil
short_version = options.short_version || nil
bundle_version = options.bundle_version || nil
new_bundle_id = options.new_bundle_id || nil
use_app_entitlements = options.use_app_entitlements || nil
keychain_path = options.keychain_path || nil
if options.provisioning_name
UI.important("The provisioning_name (-n) option is not applicable to resign. You should use provisioning_profile (-p) instead")
end
return ipa, signing_identity, provisioning_profiles, entitlements, version, display_name, short_version, bundle_version, new_bundle_id, use_app_entitlements, keychain_path
end
def find_resign_path
File.join(Sigh::ROOT, 'lib', 'assets', 'resign.sh')
end
def find_ipa
Dir[File.join(Dir.pwd, '*.ipa')].sort { |a, b| File.mtime(a) <=> File.mtime(b) }.first
end
def find_provisioning_profile
Dir[File.join(Dir.pwd, '*.mobileprovision')].sort { |a, b| File.mtime(a) <=> File.mtime(b) }.first
end
def find_signing_identity(signing_identity)
signing_identity_input = signing_identity
until (signing_identity = sha1_for_signing_identity(signing_identity_input))
UI.error("Couldn't find signing identity '#{signing_identity_input}'.")
signing_identity_input = ask_for_signing_identity
end
signing_identity
end
def sha1_for_signing_identity(signing_identity)
identities = installed_identities
return signing_identity if identities.keys.include?(signing_identity)
identities.key(signing_identity)
end
def create_provisioning_options(provisioning_profiles)
# provisioning_profiles is passed either a hash (to be able to resign extensions/nested apps):
# (in that case the underlying resign.sh expects values given as "-p at.fastlane=/folder/mobile.mobileprovision -p at.fastlane.today=/folder/mobile.mobileprovision")
# {
# "at.fastlane" => "/folder/mobile.mobileprovision",
# "at.fastlane.today" => "/folder/mobile.mobileprovision"
# }
# or an array
# (resign.sh also takes "-p /folder/mobile.mobileprovision" as a param)
# [
# "/folder/mobile.mobileprovision"
# ]
provisioning_profiles.map do |app_id, app_id_prov|
if app_id_prov
app_id_prov = File.expand_path(app_id_prov)
else
app_id = File.expand_path(app_id)
end
"-p #{[app_id, app_id_prov].compact.map(&:shellescape).join('=')}"
end.join(' ')
end
def validate_params(resign_path, ipa, provisioning_profiles)
validate_resign_path(resign_path)
validate_ipa_file(ipa)
provisioning_profiles.each { |fst, snd| validate_provisioning_file(snd || fst) }
end
def validate_resign_path(resign_path)
UI.user_error!('Could not find resign.sh file. Please try re-installing the gem') unless File.exist?(resign_path)
end
def validate_ipa_file(ipa)
UI.user_error!("ipa file could not be found or is not an ipa file (#{ipa})") unless File.exist?(ipa) && ipa.end_with?('.ipa')
end
def validate_provisioning_file(provisioning_profile)
unless File.exist?(provisioning_profile) && provisioning_profile.end_with?('.mobileprovision')
UI.user_error!("Provisioning profile file could not be found or is not a .mobileprovision file (#{provisioning_profile})")
end
end
def print_available_identities
UI.message("Available identities: \n\t#{installed_identity_descriptions.join("\n\t")}\n")
end
def ask_for_signing_identity
print_available_identities
UI.input('Signing Identity: ')
end
# Hash of available signing identities
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
def request_valid_identities
`security find-identity -v -p codesigning`
end
def installed_identity_descriptions
descriptions = []
installed_identities.group_by { |sha1, name| name }.each do |name, identities|
descriptions << name
# Show SHA-1 for homonymous identities
descriptions += identities.map do |sha1, _|
"\t#{sha1}"
end
end
descriptions
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh/repair.rb | sigh/lib/sigh/repair.rb | require 'spaceship'
require_relative 'module'
module Sigh
class Repair
def repair_all
UI.message("Starting login with user '#{Sigh.config[:username]}'")
Spaceship.login(Sigh.config[:username], nil)
Spaceship.select_team
UI.message("Successfully logged in")
# Select all 'Invalid' or 'Expired' provisioning profiles
broken_profiles = Spaceship.provisioning_profile.all.find_all do |profile|
(profile.status == "Invalid" or profile.status == "Expired")
end
if broken_profiles.count == 0
UI.success("All provisioning profiles are valid, nothing to do")
return
end
UI.success("Going to repair #{broken_profiles.count} provisioning profiles")
# Iterate over all broken profiles and repair them
broken_profiles.each do |profile|
UI.message("Repairing profile '#{profile.name}'...")
profile.repair! # yes, that's all you need to repair a profile
end
UI.success("Successfully repaired #{broken_profiles.count} provisioning profiles")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh/manager.rb | sigh/lib/sigh/manager.rb | require 'fastlane_core/provisioning_profile'
require_relative 'runner'
module Sigh
class Manager
def self.start
path = Sigh::Runner.new.run
return nil unless path
if Sigh.config[:filename]
file_name = Sigh.config[:filename]
else
file_name = File.basename(path)
end
FileUtils.mkdir_p(Sigh.config[:output_path])
output = File.join(File.expand_path(Sigh.config[:output_path]), file_name)
begin
FileUtils.mv(path, output)
rescue
# in case it already exists
end
install_profile(output) unless Sigh.config[:skip_install]
puts(output.green)
return File.expand_path(output)
end
def self.download_all(download_xcode_profiles: false)
require 'sigh/download_all'
DownloadAll.new.download_all(download_xcode_profiles: download_xcode_profiles)
end
def self.install_profile(profile)
uuid = FastlaneCore::ProvisioningProfile.uuid(profile)
name = FastlaneCore::ProvisioningProfile.name(profile)
ENV["SIGH_UDID"] = ENV["SIGH_UUID"] = uuid if uuid
ENV["SIGH_NAME"] = name if name
FastlaneCore::ProvisioningProfile.install(profile)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh/module.rb | sigh/lib/sigh/module.rb | require 'fastlane_core/ui/ui'
require 'fastlane_core/helper'
module Sigh
# Use this to just setup the configuration attribute and set it later somewhere else
class << self
attr_accessor :config
def profile_pretty_type(profile_type)
require 'spaceship'
case profile_type
when Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_DEVELOPMENT,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DEVELOPMENT,
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_DEVELOPMENT,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DEVELOPMENT
"Development"
when Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_STORE,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_STORE,
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_STORE,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_STORE
"AppStore"
when Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_ADHOC,
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_ADHOC
"AdHoc"
when Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE,
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE
"InHouse"
when Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DIRECT,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DIRECT
"Direct"
end
end
def profile_type_for_config(platform:, in_house:, config:)
profile_type = nil
case platform.to_s
when "ios"
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_STORE
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE if in_house
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_ADHOC if config[:adhoc]
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_DEVELOPMENT if config[:development]
when "tvos"
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_STORE
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE if in_house
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_ADHOC if config[:adhoc]
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_DEVELOPMENT if config[:development]
when "macos"
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_STORE
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE if in_house
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DEVELOPMENT if config[:development]
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DIRECT if config[:developer_id]
when "catalyst"
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_STORE
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE if in_house
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DEVELOPMENT if config[:development]
profile_type = Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DIRECT if config[:developer_id]
end
profile_type
end
def profile_type_for_distribution_type(platform:, distribution_type:)
config = { distribution_type.to_sym => true }
in_house = distribution_type == "enterprise"
self.profile_type_for_config(platform: platform, in_house: in_house, config: config)
end
def certificate_types_for_profile_and_platform(platform:, profile_type:)
types = []
case platform
when 'ios', 'tvos'
if profile_type == Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_DEVELOPMENT || profile_type == Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_DEVELOPMENT
types = [
Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPMENT,
Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DEVELOPMENT
]
elsif profile_type == Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE || profile_type == Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE
# Enterprise accounts don't have access to Apple Distribution certificates
types = [
Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DISTRIBUTION
]
# handles case where the desired certificate type is adhoc but the account is an enterprise account
# the apple dev portal api has a weird quirk in it where if you query for distribution certificates
# for enterprise accounts, you get nothing back even if they exist.
elsif (profile_type == Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_ADHOC || profile_type == Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_ADHOC) && Spaceship::ConnectAPI.client && Spaceship::ConnectAPI.client.in_house?
# Enterprise accounts don't have access to Apple Distribution certificates
types = [
Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DISTRIBUTION
]
else
types = [
Spaceship::ConnectAPI::Certificate::CertificateType::DISTRIBUTION,
Spaceship::ConnectAPI::Certificate::CertificateType::IOS_DISTRIBUTION
]
end
when 'macos', 'catalyst'
if profile_type == Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DEVELOPMENT || profile_type == Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DEVELOPMENT
types = [
Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPMENT,
Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DEVELOPMENT
]
elsif profile_type == Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_STORE || profile_type == Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_STORE
types = [
Spaceship::ConnectAPI::Certificate::CertificateType::DISTRIBUTION,
Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DISTRIBUTION
]
elsif profile_type == Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DIRECT || profile_type == Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DIRECT
types = [
Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_APPLICATION,
Spaceship::ConnectAPI::Certificate::CertificateType::DEVELOPER_ID_APPLICATION_G2
]
elsif profile_type == Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE || profile_type == Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE
# Enterprise accounts don't have access to Apple Distribution certificates
types = [
Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DISTRIBUTION
]
else
types = [
Spaceship::ConnectAPI::Certificate::CertificateType::DISTRIBUTION,
Spaceship::ConnectAPI::Certificate::CertificateType::MAC_APP_DISTRIBUTION
]
end
end
types
end
end
Helper = FastlaneCore::Helper # you gotta love Ruby: Helper.* should use the Helper class contained in FastlaneCore
UI = FastlaneCore::UI
ROOT = Pathname.new(File.expand_path('../../..', __FILE__))
ENV['FASTLANE_TEAM_ID'] ||= ENV["SIGH_TEAM_ID"]
ENV['DELIVER_USER'] ||= ENV["SIGH_USERNAME"]
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh/local_manage.rb | sigh/lib/sigh/local_manage.rb | require 'plist'
require 'fastlane_core/globals'
require 'fastlane_core/provisioning_profile'
require_relative 'module'
module Sigh
class LocalManage
LIST = "list"
CLEANUP = "cleanup"
def self.start(options, args)
command, clean_expired, clean_pattern, force = get_inputs(options, args)
if command == LIST
list_profiles
elsif command == CLEANUP
cleanup_profiles(clean_expired, clean_pattern, force)
end
end
def self.install_profile(profile)
UI.message("Installing provisioning profile...")
profile_path = FastlaneCore::ProvisioningProfile.profiles_path
uuid = ENV["SIGH_UUID"] || ENV["SIGH_UDID"]
profile_filename = uuid + ".mobileprovision"
destination = File.join(profile_path, profile_filename)
# If the directory doesn't exist, make it first
unless File.directory?(profile_path)
FileUtils.mkdir_p(profile_path)
end
# copy to Xcode provisioning profile directory
FileUtils.copy(profile, destination)
if File.exist?(destination)
UI.success("Profile installed at \"#{destination}\"")
else
UI.user_error!("Failed installation of provisioning profile at location: #{destination}")
end
end
def self.get_inputs(options, _args)
clean_expired = options.clean_expired
clean_pattern = /#{options.clean_pattern}/ if options.clean_pattern
force = options.force
command = (!clean_expired.nil? || !clean_pattern.nil?) ? CLEANUP : LIST
return command, clean_expired, clean_pattern, force
end
def self.list_profiles
profiles = load_profiles
now = DateTime.now
soon = (Date.today + 30).to_datetime
profiles_valid = profiles.select { |profile| profile["ExpirationDate"] > now && profile["ExpirationDate"] > soon }
if profiles_valid.count > 0
UI.message("Provisioning profiles installed")
UI.message("Valid:")
profiles_valid.each do |profile|
UI.message(profile_info(profile).green)
end
end
profiles_soon = profiles.select { |profile| profile["ExpirationDate"] > now && profile["ExpirationDate"] < soon }
if profiles_soon.count > 0
UI.message("")
UI.message("Expiring within 30 days:")
profiles_soon.each do |profile|
UI.message(profile_info(profile).yellow)
end
end
profiles_expired = profiles.select { |profile| profile["ExpirationDate"] < now }
if profiles_expired.count > 0
UI.message("")
UI.message("Expired:")
profiles_expired.each do |profile|
UI.message(profile_info(profile).red)
end
end
UI.message("")
UI.message("Summary")
UI.message("#{profiles.count} installed profiles")
UI.message("#{profiles_expired.count} are expired".red) if profiles_expired.count > 0
UI.message("#{profiles_soon.count} are valid but will expire within 30 days".yellow)
UI.message("#{profiles_valid.count} are valid".green)
UI.message("You can remove all expired profiles using `fastlane sigh manage -e`") if profiles_expired.count > 0
end
def self.profile_info(profile)
if FastlaneCore::Globals.verbose?
"#{profile['Name']} - #{File.basename(profile['Path'])}"
else
profile['Name']
end
end
def self.cleanup_profiles(expired = false, pattern = nil, force = nil)
now = DateTime.now
profiles = load_profiles.select { |profile| (expired && profile["ExpirationDate"] < now) || (!pattern.nil? && profile["Name"] =~ pattern) }
UI.message("The following provisioning profiles are either expired or matches your pattern:")
profiles.each do |profile|
UI.message(profile["Name"].red)
end
delete = force
unless delete
if Helper.ci?
UI.user_error!("On a CI server, cleanup cannot be used without the --force option")
else
delete = UI.confirm("Delete these provisioning profiles #{profiles.length}?")
end
end
if delete
profiles.each do |profile|
File.delete(profile["Path"])
end
UI.success("\n\nDeleted #{profiles.length} profiles")
end
end
def self.load_profiles
profiles_path = FastlaneCore::ProvisioningProfile.profiles_path
UI.message("Loading Provisioning profiles from #{profiles_path}")
profiles_path = File.join(profiles_path, "*.mobileprovision")
profile_paths = Dir[profiles_path]
profiles = []
profile_paths.each do |profile_path|
profile = Plist.parse_xml(`security cms -D -i '#{profile_path}' 2> /dev/null`) # /dev/null: https://github.com/fastlane/fastlane/issues/6387
profile['Path'] = profile_path
profiles << profile
end
profiles = profiles.sort_by { |profile| profile["Name"].downcase }
return profiles
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/sigh/lib/sigh/download_all.rb | sigh/lib/sigh/download_all.rb | require 'spaceship'
require 'base64'
require_relative 'manager'
require_relative 'module'
module Sigh
class DownloadAll
# Download all valid provisioning profiles
def download_all(download_xcode_profiles: false)
if (api_token = Spaceship::ConnectAPI::Token.from(hash: Sigh.config[:api_key], filepath: Sigh.config[:api_key_path]))
UI.message("Creating authorization token for App Store Connect API")
Spaceship::ConnectAPI.token = api_token
elsif !Spaceship::ConnectAPI.token.nil?
UI.message("Using existing authorization token for App Store Connect API")
else
# Team selection passed though FASTLANE_ITC_TEAM_ID and FASTLANE_ITC_TEAM_NAME environment variables
# Prompts select team if multiple teams and none specified
UI.message("Starting login with user '#{Sigh.config[:username]}'")
Spaceship::ConnectAPI.login(Sigh.config[:username], nil, use_portal: true, use_tunes: false)
UI.message("Successfully logged in")
end
if download_xcode_profiles
UI.deprecated("The App Store Connect API does not support querying for Xcode managed profiles: --download_code_profiles is deprecated")
end
case Sigh.config[:platform].to_s
when 'ios'
profile_types = [
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_STORE,
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_INHOUSE,
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_ADHOC,
Spaceship::ConnectAPI::Profile::ProfileType::IOS_APP_DEVELOPMENT
]
when 'macos'
profile_types = [
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_STORE,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DEVELOPMENT,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_DIRECT
]
# As of 2022-06-25, only available with Apple ID auth
if Spaceship::ConnectAPI.token
UI.important("Skipping #{Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE}... only available with Apple ID auth")
else
profile_types << Spaceship::ConnectAPI::Profile::ProfileType::MAC_APP_INHOUSE
end
when 'catalyst'
profile_types = [
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_STORE,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DEVELOPMENT,
Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_DIRECT
]
# As of 2022-06-25, only available with Apple ID auth
if Spaceship::ConnectAPI.token
UI.important("Skipping #{Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE}... only available with Apple ID auth")
else
profile_types << Spaceship::ConnectAPI::Profile::ProfileType::MAC_CATALYST_APP_INHOUSE
end
when 'tvos'
profile_types = [
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_STORE,
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_INHOUSE,
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_ADHOC,
Spaceship::ConnectAPI::Profile::ProfileType::TVOS_APP_DEVELOPMENT
]
end
profiles = Spaceship::ConnectAPI::Profile.all(filter: { profileType: profile_types.join(",") }, includes: "bundleId")
download_profiles(profiles)
end
# @param profiles [Array] Array of all the provisioning profiles we want to download
def download_profiles(profiles)
UI.important("No profiles available for download") if profiles.empty?
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
end
def pretty_type(profile_type)
return Sigh.profile_pretty_type(profile_type)
end
# @param profile [ProvisioningProfile] A profile we plan to download and store
def download_profile(profile)
FileUtils.mkdir_p(Sigh.config[:output_path])
type_name = pretty_type(profile.profile_type)
profile_name = "#{type_name}_#{profile.uuid}_#{profile.bundle_id.identifier}"
if Sigh.config[:platform].to_s == 'tvos'
profile_name += "_tvos"
end
if ['macos', 'catalyst'].include?(Sigh.config[:platform].to_s)
profile_name += '.provisionprofile'
else
profile_name += '.mobileprovision'
end
output_path = File.join(Sigh.config[:output_path], profile_name)
File.open(output_path, "wb") do |f|
content = Base64.decode64(profile.profile_content)
f.write(content)
end
Manager.install_profile(output_path) unless Sigh.config[:skip_install]
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/spec/junit_generator_spec.rb | trainer/spec/junit_generator_spec.rb | describe Trainer do
describe Trainer::JunitGenerator do
it "works for a valid .plist file" do
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Valid1.plist")
junit = File.read("./trainer/spec/fixtures/Valid1.junit")
expect(tp.to_junit).to eq(junit)
end
it "works for a valid .plist file and xcpretty naming" do
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Valid1.plist", { xcpretty_naming: true })
junit = File.read("./trainer/spec/fixtures/Valid1-x.junit")
expect(tp.to_junit).to eq(junit)
end
it "works for a with all tests passing" do
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Valid2.plist")
junit = File.read("./trainer/spec/fixtures/Valid2.junit")
expect(tp.to_junit).to eq(junit)
end
it "works for a with all tests passing and xcpretty naming" do
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Valid2.plist", { xcpretty_naming: true })
junit = File.read("./trainer/spec/fixtures/Valid2-x.junit")
expect(tp.to_junit).to eq(junit)
end
it "works with an xcresult", requires_xcode: true do
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Test.test_result.xcresult", { force_legacy_xcresulttool: true })
junit = File.read("./trainer/spec/fixtures/XCResult.junit")
expect(tp.to_junit).to eq(junit)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/spec/test_parser_spec.rb | trainer/spec/test_parser_spec.rb | describe Trainer do
describe Trainer::TestParser do
describe "Loading a file" do
it "raises an error if the file doesn't exist" do
expect do
Trainer::TestParser.new("notExistent")
end.to raise_error(/File not found at path/)
end
it "raises an error if FormatVersion is not supported" do
expect do
Trainer::TestParser.new("./trainer/spec/fixtures/InvalidVersionMismatch.plist")
end.to raise_error("Format version '0.9' is not supported, must be 1.1, 1.2")
end
it "loads a file without throwing an error" do
Trainer::TestParser.new("./trainer/spec/fixtures/Valid1.plist")
end
end
describe "#auto_convert" do
it "raises an error if no files were found" do
expect do
Trainer::TestParser.auto_convert({ path: "bin" })
end.to raise_error("No test result files found in directory 'bin', make sure the file name ends with 'TestSummaries.plist' or '.xcresult'")
end
end
describe "#generate_cmd_parse_xcresult" do
let(:xcresult_sample_path) { "./trainer/spec/fixtures/Test.test_result.xcresult" }
let(:command) { Trainer::LegacyXCResult::Parser.send(:generate_cmd_parse_xcresult, xcresult_sample_path) }
before do
allow(File).to receive(:expand_path).with(xcresult_sample_path).and_return(xcresult_sample_path)
allow(Trainer::XCResult::Helper).to receive(:`).with('xcrun xcresulttool version').and_return(version)
end
context 'with >= Xcode 16 beta 3' do
let(:version) { 'xcresulttool version 23021, format version 3.53 (current)' }
let(:expected) { ['xcrun', 'xcresulttool', 'get', '--format', 'json', '--path', xcresult_sample_path, '--legacy'] }
it 'should pass `--legacy`', requires_xcode: true do
expect(command).to eq(expected)
end
end
context 'with < Xcode 16 beta 3' do
let(:version) { 'xcresulttool version 22608, format version 3.49 (current)' }
let(:expected) { ['xcrun', 'xcresulttool', 'get', '--format', 'json', '--path', xcresult_sample_path] }
it 'should not pass `--legacy`', requires_xcode: true do
expect(command).to eq(expected)
end
end
end
describe "Stores the data in a useful format" do
let(:config) { { force_legacy_xcresulttool: true } }
describe "#tests_successful?" do
it "returns false if tests failed" do
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Valid1.plist", config)
expect(tp.tests_successful?).to eq(false)
end
end
it "works as expected with plist" do
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Valid1.plist")
expect(tp.data).to eq([
{
project_path: "Trainer.xcodeproj",
target_name: "Unit",
test_name: "Unit",
duration: 0.4,
tests: [
{
identifier: "Unit/testExample()",
test_group: "Unit",
name: "testExample()",
object_class: "IDESchemeActionTestSummary",
status: "Success",
guid: "6840EEB8-3D7A-4B2D-9A45-6955DC11D32B",
duration: 0.1
},
{
identifier: "Unit/testExample2()",
test_group: "Unit",
name: "testExample2()",
object_class: "IDESchemeActionTestSummary",
status: "Failure",
guid: "B2EB311E-ED8D-4DAD-8AF0-A455A20855DF",
duration: 0.1,
failures: [
{
file_name: "/Users/liamnichols/Code/Local/Trainer/Unit/Unit.swift",
line_number: 19,
message: "XCTAssertTrue failed - ",
performance_failure: false,
failure_message: "XCTAssertTrue failed - (/Users/liamnichols/Code/Local/Trainer/Unit/Unit.swift:19)"
}
]
},
{
identifier: "Unit/testPerformanceExample()",
test_group: "Unit",
name: "testPerformanceExample()",
object_class: "IDESchemeActionTestSummary",
status: "Success",
guid: "72D0B210-939D-4751-966F-986B6CB2660C",
duration: 0.2
}
],
number_of_tests: 3,
number_of_failures: 1,
number_of_tests_excluding_retries: 3,
number_of_failures_excluding_retries: 1,
number_of_retries: 0
}
])
end
it "works as expected with xcresult", requires_xcode: true do
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Test.test_result.xcresult", config)
expect(tp.data).to eq([
{
project_path: "Test.xcodeproj",
target_name: "TestUITests",
test_name: "TestUITests",
configuration_name: "Test Scheme Action",
duration: 16.05245804786682,
tests: [
{
identifier: "TestUITests.testExample()",
name: "testExample()",
duration: 16.05245804786682,
status: "Success",
test_group: "TestUITests",
guid: ""
}
],
number_of_tests: 1,
number_of_failures: 0,
number_of_skipped: 0,
number_of_tests_excluding_retries: 1,
number_of_failures_excluding_retries: 0,
number_of_retries: 0
},
{
project_path: "Test.xcodeproj",
target_name: "TestThisDude",
test_name: "TestThisDude",
configuration_name: "Test Scheme Action",
duration: 0.5279300212860107,
tests: [
{
identifier: "TestTests.testExample()",
name: "testExample()",
duration: 0.0005381107330322266,
status: "Success",
test_group: "TestTests",
guid: ""
},
{
identifier: "TestTests.testFailureJosh1()",
name: "testFailureJosh1()",
duration: 0.006072044372558594,
status: "Failure",
test_group: "TestTests",
guid: "",
failures: [
{
file_name: "",
line_number: 0,
message: "",
performance_failure: {},
failure_message: "XCTAssertTrue failed (/Users/josh/Projects/fastlane/test-ios/TestTests/TestTests.swift#CharacterRangeLen=0&EndingLineNumber=36&StartingLineNumber=36)"
}
]
},
{
identifier: "TestTests.testPerformanceExample()",
name: "testPerformanceExample()",
duration: 0.2661939859390259,
status: "Success",
test_group: "TestTests",
guid: ""
},
{
identifier: "TestThisDude.testExample()",
name: "testExample()",
duration: 0.0004099607467651367,
status: "Success",
test_group: "TestThisDude",
guid: ""
},
{
identifier: "TestThisDude.testFailureJosh2()",
name: "testFailureJosh2()",
duration: 0.001544952392578125,
status: "Failure",
test_group: "TestThisDude",
guid: "",
failures: [
{
file_name: "",
line_number: 0,
message: "",
performance_failure: {},
failure_message: "XCTAssertTrue failed (/Users/josh/Projects/fastlane/test-ios/TestThisDude/TestThisDude.swift#CharacterRangeLen=0&EndingLineNumber=35&StartingLineNumber=35)"
}
]
},
{
identifier: "TestThisDude.testPerformanceExample()",
name: "testPerformanceExample()",
duration: 0.2531709671020508,
status: "Success",
test_group: "TestThisDude",
guid: ""
}
],
number_of_tests: 6,
number_of_failures: 2,
number_of_skipped: 0,
number_of_tests_excluding_retries: 6,
number_of_failures_excluding_retries: 2,
number_of_retries: 0
}
])
end
it "still produces a test failure message when file url is missing", requires_xcode: true do
allow_any_instance_of(Trainer::LegacyXCResult::TestFailureIssueSummary).to receive(:document_location_in_creating_workspace).and_return(nil)
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Test.test_result.xcresult", config)
test_failures = tp.data.last[:tests].select { |t| t[:failures] }
failure_messages = test_failures.map { |tf| tf[:failures].first[:failure_message] }
expect(failure_messages).to eq(["XCTAssertTrue failed", "XCTAssertTrue failed"])
RSpec::Mocks.space.proxy_for(Trainer::LegacyXCResult::TestFailureIssueSummary).reset
end
it "works as expected with xcresult with spaces", requires_xcode: true do
tp = Trainer::TestParser.new("./trainer/spec/fixtures/Test.with_spaces.xcresult", config)
expect(tp.data).to eq([
{
project_path: "SpaceTests.xcodeproj",
target_name: "SpaceTestsTests",
test_name: "SpaceTestsTests",
configuration_name: "Test Scheme Action",
duration: 0.21180307865142822,
tests: [
{
identifier: "SpaceTestsSpec.a test with spaces, should always fail()",
name: "a test with spaces, should always fail()",
duration: 0.21180307865142822,
status: "Failure",
test_group: "SpaceTestsSpec",
guid: "",
failures: [
{
failure_message: "expected to equal <1>, got <2>\n (/Users/mahmood.tahir/Developer/SpaceTests/SpaceTestsTests/TestSpec.swift#CharacterRangeLen=0&EndingLineNumber=15&StartingLineNumber=15)",
file_name: "",
line_number: 0,
message: "",
performance_failure: {}
}
]
}
],
number_of_tests: 1,
number_of_failures: 1,
number_of_skipped: 0,
number_of_tests_excluding_retries: 1,
number_of_failures_excluding_retries: 1,
number_of_retries: 0
}
])
end
end
end
describe Trainer::XCResult::Parser do
it 'generates same data for legacy and new commands', requires_xcodebuild: true do
skip "Requires Xcode 16 or higher" unless Trainer::XCResult::Helper.supports_xcode16_xcresulttool?
xcresult_path = File.expand_path('../fixtures/Test.test_result.xcresult', __FILE__)
keys_to_compare = [
:number_of_tests,
:number_of_failures,
:number_of_tests_excluding_retries,
:number_of_failures_excluding_retries,
:number_of_retries,
:number_of_skipped
]
new_parser_data = Trainer::XCResult::Parser.parse_xcresult(path: xcresult_path).map do |hash|
hash.slice(*keys_to_compare)
end
legacy_parser_data = Trainer::LegacyXCResult::Parser.parse_xcresult(path: xcresult_path).map do |hash|
hash.slice(*keys_to_compare)
end
expect(legacy_parser_data).to eq(new_parser_data)
end
describe 'Xcode 16 xcresult bundle' do
let(:xcresult_path) { File.expand_path('../fixtures/Xcode16-Mixed-XCTest-SwiftTesting.xcresult', __FILE__) }
let(:json_fixture_path) { File.expand_path("../fixtures/Xcode16-Mixed-XCTest-SwiftTesting.json", __FILE__) }
let(:json_fixture) { JSON.parse(File.read(json_fixture_path)) }
it 'generates correct JUnit XML including retries', requires_xcodebuild: true do
skip "Requires Xcode 16 or higher" unless Trainer::XCResult::Helper.supports_xcode16_xcresulttool?
# Uncomment this if you want to bypass the xcresult_to_json call during testing
# allow(Trainer::XCResult::Parser).to receive(:xcresult_to_json).with(xcresult_path).and_return(json_fixture)
test_plan = Trainer::XCResult::Parser.parse_xcresult(path: xcresult_path)
junit_xml = test_plan.to_xml
expected_xml_path = File.expand_path('../fixtures/Xcode16-Mixed-XCTest-SwiftTesting-WithRetries.junit', __FILE__)
expected_xml = File.read(expected_xml_path)
expect(junit_xml.chomp).to eq(expected_xml.chomp)
end
it 'generates correct JUnit XML excluding retries', requires_xcodebuild: true do
skip "Requires Xcode 16 or higher" unless Trainer::XCResult::Helper.supports_xcode16_xcresulttool?
# Uncomment this if you want to bypass the xcresult_to_json call during testing
# allow(Trainer::XCResult::Parser).to receive(:xcresult_to_json).with(xcresult_path).and_return(json_fixture)
test_plan = Trainer::XCResult::Parser.parse_xcresult(path: xcresult_path, output_remove_retry_attempts: true)
junit_xml = test_plan.to_xml
expected_xml_path = File.expand_path('../fixtures/Xcode16-Mixed-XCTest-SwiftTesting-WithoutRetries.junit', __FILE__)
expected_xml = File.read(expected_xml_path)
expect(junit_xml.chomp).to eq(expected_xml.chomp)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/spec/spec_helper.rb | trainer/spec/spec_helper.rb | require 'trainer'
# This module is only used to check the environment is currently a testing env
module SpecHelper
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer.rb | trainer/lib/trainer.rb | require 'fastlane'
require 'trainer/options'
require 'trainer/test_parser'
require 'trainer/xcresult'
require 'trainer/junit_generator'
require 'trainer/legacy_xcresult'
require 'trainer/plist_test_summary_parser'
require 'trainer/module'
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/plist_test_summary_parser.rb | trainer/lib/trainer/plist_test_summary_parser.rb | require 'plist'
module Trainer
module PlistTestSummaryParser
class << self
def parse_content(raw_json, xcpretty_naming)
data = raw_json["TestableSummaries"].collect do |testable_summary|
summary_row = {
project_path: testable_summary["ProjectPath"],
target_name: testable_summary["TargetName"],
test_name: testable_summary["TestName"],
duration: testable_summary["Tests"].map { |current_test| current_test["Duration"] }.inject(:+),
tests: unfold_tests(testable_summary["Tests"]).collect do |current_test|
test_group, test_name = test_group_and_name(testable_summary, current_test, xcpretty_naming)
current_row = {
identifier: current_test["TestIdentifier"],
test_group: test_group,
name: test_name,
object_class: current_test["TestObjectClass"],
status: current_test["TestStatus"],
guid: current_test["TestSummaryGUID"],
duration: current_test["Duration"]
}
if current_test["FailureSummaries"]
current_row[:failures] = current_test["FailureSummaries"].collect do |current_failure|
{
file_name: current_failure['FileName'],
line_number: current_failure['LineNumber'],
message: current_failure['Message'],
performance_failure: current_failure['PerformanceFailure'],
failure_message: "#{current_failure['Message']} (#{current_failure['FileName']}:#{current_failure['LineNumber']})"
}
end
end
current_row
end
}
summary_row[:number_of_tests] = summary_row[:tests].count
summary_row[:number_of_failures] = summary_row[:tests].find_all { |a| (a[:failures] || []).count > 0 }.count
# Makes sure that plist support matches data output of xcresult
summary_row[:number_of_tests_excluding_retries] = summary_row[:number_of_tests]
summary_row[:number_of_failures_excluding_retries] = summary_row[:number_of_failures]
summary_row[:number_of_retries] = 0
summary_row
end
data
end
def ensure_file_valid!(raw_json)
format_version = raw_json["FormatVersion"]
supported_versions = ["1.1", "1.2"]
raise "Format version '#{format_version}' is not supported, must be #{supported_versions.join(', ')}" unless supported_versions.include?(format_version)
end
private
def unfold_tests(data)
tests = []
data.each do |current_hash|
if current_hash["Subtests"]
tests += unfold_tests(current_hash["Subtests"])
end
if current_hash["TestStatus"]
tests << current_hash
end
end
return tests
end
def test_group_and_name(testable_summary, test, xcpretty_naming)
if xcpretty_naming
group = testable_summary["TargetName"] + "." + test["TestIdentifier"].split("/")[0..-2].join(".")
name = test["TestName"][0..-3]
else
group = test["TestIdentifier"].split("/")[0..-2].join(".")
name = test["TestName"]
end
return group, name
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/xcresult.rb | trainer/lib/trainer/xcresult.rb | require 'json'
require 'open3'
require_relative 'xcresult/helper'
require_relative 'xcresult/test_case_attributes'
require_relative 'xcresult/repetition'
require_relative 'xcresult/test_case'
require_relative 'xcresult/test_suite'
require_relative 'xcresult/test_plan'
module Trainer
# Model xcresulttool JSON output for Xcode16+ version of xcresulttool
# See JSON schema from `xcrun xcresulttool get test-results tests --help`
module XCResult
module Parser
class << self
# Parses an xcresult file and returns a TestPlan object
#
# @param path [String] The path to the xcresult file
# @param output_remove_retry_attempts [Boolean] Whether to remove retry attempts from the output
# @return [TestPlan] A TestPlan object containing the test results
def parse_xcresult(path:, output_remove_retry_attempts: false)
json = xcresult_to_json(path)
TestPlan.from_json(
json: json
).tap do |test_plan|
test_plan.output_remove_retry_attempts = output_remove_retry_attempts
end
end
private
def xcresult_to_json(path)
stdout, stderr, status = Open3.capture3('xcrun', 'xcresulttool', 'get', 'test-results', 'tests', '--path', path)
raise "Failed to execute xcresulttool command - #{stderr}" unless status.success?
JSON.parse(stdout)
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/options.rb | trainer/lib/trainer/options.rb | require 'fastlane_core/configuration/config_item'
require_relative 'module'
module Trainer
class Options
def self.available_options
@options ||= [
FastlaneCore::ConfigItem.new(key: :path,
short_option: "-p",
env_name: "TRAINER_PATH",
default_value: ".",
description: "Path to the directory that should be converted",
verify_block: proc do |value|
v = File.expand_path(value.to_s)
if v.end_with?(".plist")
UI.user_error!("Can't find file at path #{v}") unless File.exist?(v)
else
UI.user_error!("Path '#{v}' is not a directory or can't be found") unless File.directory?(v)
end
end),
FastlaneCore::ConfigItem.new(key: :extension,
short_option: "-e",
env_name: "TRAINER_EXTENSION",
default_value: ".xml",
description: "The extension for the newly created file. Usually .xml or .junit",
verify_block: proc do |value|
UI.user_error!("extension must contain a `.`") unless value.include?(".")
end),
FastlaneCore::ConfigItem.new(key: :output_directory,
short_option: "-o",
env_name: "TRAINER_OUTPUT_DIRECTORY",
default_value: nil,
optional: true,
description: "Directory in which the xml files should be written to. Same directory as source by default"),
FastlaneCore::ConfigItem.new(key: :output_filename,
short_option: "-f",
env_name: "TRAINER_OUTPUT_FILENAME",
default_value: nil,
optional: true,
description: "Filename the xml file should be written to. Defaults to name of input file. (Only works if one input file is used)"),
FastlaneCore::ConfigItem.new(key: :fail_build,
env_name: "TRAINER_FAIL_BUILD",
description: "Should this step stop the build if the tests fail? Set this to false if you're handling this with a test reporter",
is_string: false,
default_value: true),
FastlaneCore::ConfigItem.new(key: :xcpretty_naming,
short_option: "-x",
env_name: "TRAINER_XCPRETTY_NAMING",
description: "Produces class name and test name identical to xcpretty naming in junit file",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :force_legacy_xcresulttool,
env_name: "TRAINER_FORCE_LEGACY_XCRESULTTOOL",
description: "Force the use of the '--legacy' flag for xcresulttool instead of using the new commands",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :silent,
env_name: "TRAINER_SILENT",
description: "Silences all output",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :output_remove_retry_attempts,
env_name: "TRAINER_OUTPUT_REMOVE_RETRY_ATTEMPTS",
description: "Doesn't include retry attempts in the output",
is_string: false,
default_value: false)
]
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/junit_generator.rb | trainer/lib/trainer/junit_generator.rb | require_relative 'module'
module Trainer
class JunitGenerator
attr_accessor :results
def initialize(results)
self.results = results
end
def generate
# JUnit file documentation: http://llg.cubic.org/docs/junit/
# And http://nelsonwells.net/2012/09/how-jenkins-ci-parses-and-displays-junit-output/
# And http://windyroad.com.au/dl/Open%20Source/JUnit.xsd
lib_path = Trainer::ROOT
xml_path = File.join(lib_path, "lib/assets/junit.xml.erb")
xml = ERB.new(File.read(xml_path), trim_mode: '<>').result(binding) # http://www.rrn.dk/rubys-erb-templating-system
xml = xml.gsub('system_', 'system-').delete("\e") # Jenkins cannot parse 'ESC' symbol
# We have to manually clear empty lines
# They may contain white spaces
clean_xml = []
xml.each_line do |row|
clean_xml << row.delete("\n") if row.strip.to_s.length > 0
end
return clean_xml.join("\n")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/legacy_xcresult.rb | trainer/lib/trainer/legacy_xcresult.rb | require 'open3'
require_relative 'xcresult/helper'
module Trainer
module LegacyXCResult
# Model attributes and relationships taken from running the following command:
# xcrun xcresulttool formatDescription --legacy
class AbstractObject
attr_accessor :type
def initialize(data)
self.type = data["_type"]["_name"]
end
def fetch_value(data, key)
return (data[key] || {})["_value"]
end
def fetch_values(data, key)
return (data[key] || {})["_values"] || []
end
end
# - ActionTestPlanRunSummaries
# * Kind: object
# * Properties:
# + summaries: [ActionTestPlanRunSummary]
class ActionTestPlanRunSummaries < AbstractObject
attr_accessor :summaries
def initialize(data)
self.summaries = fetch_values(data, "summaries").map do |summary_data|
ActionTestPlanRunSummary.new(summary_data)
end
super
end
end
# - ActionAbstractTestSummary
# * Kind: object
# * Properties:
# + name: String?
class ActionAbstractTestSummary < AbstractObject
attr_accessor :name
def initialize(data)
self.name = fetch_value(data, "name")
super
end
end
# - ActionTestPlanRunSummary
# * Supertype: ActionAbstractTestSummary
# * Kind: object
# * Properties:
# + testableSummaries: [ActionTestableSummary]
class ActionTestPlanRunSummary < ActionAbstractTestSummary
attr_accessor :testable_summaries
def initialize(data)
self.testable_summaries = fetch_values(data, "testableSummaries").map do |summary_data|
ActionTestableSummary.new(summary_data)
end
super
end
end
# - ActionTestableSummary
# * Supertype: ActionAbstractTestSummary
# * Kind: object
# * Properties:
# + projectRelativePath: String?
# + targetName: String?
# + testKind: String?
# + tests: [ActionTestSummaryIdentifiableObject]
# + diagnosticsDirectoryName: String?
# + failureSummaries: [ActionTestFailureSummary]
# + testLanguage: String?
# + testRegion: String?
class ActionTestableSummary < ActionAbstractTestSummary
attr_accessor :project_relative_path
attr_accessor :target_name
attr_accessor :test_kind
attr_accessor :tests
def initialize(data)
self.project_relative_path = fetch_value(data, "projectRelativePath")
self.target_name = fetch_value(data, "targetName")
self.test_kind = fetch_value(data, "testKind")
self.tests = fetch_values(data, "tests").map do |tests_data|
ActionTestSummaryIdentifiableObject.create(tests_data, self)
end
super
end
def all_tests
return tests.map(&:all_subtests).flatten
end
end
# - ActionTestSummaryIdentifiableObject
# * Supertype: ActionAbstractTestSummary
# * Kind: object
# * Properties:
# + identifier: String?
class ActionTestSummaryIdentifiableObject < ActionAbstractTestSummary
attr_accessor :identifier
attr_accessor :parent
def initialize(data, parent)
self.identifier = fetch_value(data, "identifier")
self.parent = parent
super(data)
end
def all_subtests
raise "Not overridden"
end
def self.create(data, parent)
type = data["_type"]["_name"]
if type == "ActionTestSummaryGroup"
return ActionTestSummaryGroup.new(data, parent)
elsif type == "ActionTestMetadata"
return ActionTestMetadata.new(data, parent)
else
raise "Unsupported type: #{type}"
end
end
end
# - ActionTestSummaryGroup
# * Supertype: ActionTestSummaryIdentifiableObject
# * Kind: object
# * Properties:
# + duration: Double
# + subtests: [ActionTestSummaryIdentifiableObject]
class ActionTestSummaryGroup < ActionTestSummaryIdentifiableObject
attr_accessor :duration
attr_accessor :subtests
def initialize(data, parent)
self.duration = fetch_value(data, "duration").to_f
self.subtests = fetch_values(data, "subtests").map do |subtests_data|
ActionTestSummaryIdentifiableObject.create(subtests_data, self)
end
super(data, parent)
end
def all_subtests
return subtests.map(&:all_subtests).flatten
end
end
# - ActionTestMetadata
# * Supertype: ActionTestSummaryIdentifiableObject
# * Kind: object
# * Properties:
# + testStatus: String
# + duration: Double?
# + summaryRef: Reference?
# + performanceMetricsCount: Int
# + failureSummariesCount: Int
# + activitySummariesCount: Int
class ActionTestMetadata < ActionTestSummaryIdentifiableObject
attr_accessor :test_status
attr_accessor :duration
attr_accessor :performance_metrics_count
attr_accessor :failure_summaries_count
attr_accessor :activity_summaries_count
def initialize(data, parent)
self.test_status = fetch_value(data, "testStatus")
self.duration = fetch_value(data, "duration").to_f
self.performance_metrics_count = fetch_value(data, "performanceMetricsCount")
self.failure_summaries_count = fetch_value(data, "failureSummariesCount")
self.activity_summaries_count = fetch_value(data, "activitySummariesCount")
super(data, parent)
end
def all_subtests
return [self]
end
def find_failure(failures)
sanitizer = proc { |name| name.gsub(/\W/, "_") }
sanitized_identifier = sanitizer.call(self.identifier)
if self.test_status == "Failure"
# Tries to match failure on test case name
# Example TestFailureIssueSummary:
# producingTarget: "TestThisDude"
# test_case_name: "TestThisDude.testFailureJosh2()" (when Swift)
# or "-[TestThisDudeTests testFailureJosh2]" (when Objective-C)
# Example ActionTestMetadata
# identifier: "TestThisDude/testFailureJosh2()" (when Swift)
# or identifier: "TestThisDude/testFailureJosh2" (when Objective-C)
found_failure = failures.find do |failure|
# Sanitize both test case name and identifier in a consistent fashion, then replace all non-word
# chars with underscore, and compare them
sanitized_test_case_name = sanitizer.call(failure.test_case_name)
sanitized_identifier == sanitized_test_case_name
end
return found_failure
else
return nil
end
end
end
# - ActionsInvocationRecord
# * Kind: object
# * Properties:
# + metadataRef: Reference?
# + metrics: ResultMetrics
# + issues: ResultIssueSummaries
# + actions: [ActionRecord]
# + archive: ArchiveInfo?
class ActionsInvocationRecord < AbstractObject
attr_accessor :actions
attr_accessor :issues
def initialize(data)
self.actions = fetch_values(data, "actions").map do |action_data|
ActionRecord.new(action_data)
end
self.issues = ResultIssueSummaries.new(data["issues"])
super
end
end
# - ActionRecord
# * Kind: object
# * Properties:
# + schemeCommandName: String
# + schemeTaskName: String
# + title: String?
# + startedTime: Date
# + endedTime: Date
# + runDestination: ActionRunDestinationRecord
# + buildResult: ActionResult
# + actionResult: ActionResult
class ActionRecord < AbstractObject
attr_accessor :scheme_command_name
attr_accessor :scheme_task_name
attr_accessor :title
attr_accessor :build_result
attr_accessor :action_result
def initialize(data)
self.scheme_command_name = fetch_value(data, "schemeCommandName")
self.scheme_task_name = fetch_value(data, "schemeTaskName")
self.title = fetch_value(data, "title")
self.build_result = ActionResult.new(data["buildResult"])
self.action_result = ActionResult.new(data["actionResult"])
super
end
end
# - ActionResult
# * Kind: object
# * Properties:
# + resultName: String
# + status: String
# + metrics: ResultMetrics
# + issues: ResultIssueSummaries
# + coverage: CodeCoverageInfo
# + timelineRef: Reference?
# + logRef: Reference?
# + testsRef: Reference?
# + diagnosticsRef: Reference?
class ActionResult < AbstractObject
attr_accessor :result_name
attr_accessor :status
attr_accessor :issues
attr_accessor :timeline_ref
attr_accessor :log_ref
attr_accessor :tests_ref
attr_accessor :diagnostics_ref
def initialize(data)
self.result_name = fetch_value(data, "resultName")
self.status = fetch_value(data, "status")
self.issues = ResultIssueSummaries.new(data["issues"])
self.timeline_ref = Reference.new(data["timelineRef"]) if data["timelineRef"]
self.log_ref = Reference.new(data["logRef"]) if data["logRef"]
self.tests_ref = Reference.new(data["testsRef"]) if data["testsRef"]
self.diagnostics_ref = Reference.new(data["diagnosticsRef"]) if data["diagnosticsRef"]
super
end
end
# - Reference
# * Kind: object
# * Properties:
# + id: String
# + targetType: TypeDefinition?
class Reference < AbstractObject
attr_accessor :id
attr_accessor :target_type
def initialize(data)
self.id = fetch_value(data, "id")
self.target_type = TypeDefinition.new(data["targetType"]) if data["targetType"]
super
end
end
# - TypeDefinition
# * Kind: object
# * Properties:
# + name: String
# + supertype: TypeDefinition?
class TypeDefinition < AbstractObject
attr_accessor :name
attr_accessor :supertype
def initialize(data)
self.name = fetch_value(data, "name")
self.supertype = TypeDefinition.new(data["supertype"]) if data["supertype"]
super
end
end
# - DocumentLocation
# * Kind: object
# * Properties:
# + url: String
# + concreteTypeName: String
class DocumentLocation < AbstractObject
attr_accessor :url
attr_accessor :concrete_type_name
def initialize(data)
self.url = fetch_value(data, "url")
self.concrete_type_name = data["concreteTypeName"]["_value"]
super
end
end
# - IssueSummary
# * Kind: object
# * Properties:
# + issueType: String
# + message: String
# + producingTarget: String?
# + documentLocationInCreatingWorkspace: DocumentLocation?
class IssueSummary < AbstractObject
attr_accessor :issue_type
attr_accessor :message
attr_accessor :producing_target
attr_accessor :document_location_in_creating_workspace
def initialize(data)
self.issue_type = fetch_value(data, "issueType")
self.message = fetch_value(data, "message")
self.producing_target = fetch_value(data, "producingTarget")
self.document_location_in_creating_workspace = DocumentLocation.new(data["documentLocationInCreatingWorkspace"]) if data["documentLocationInCreatingWorkspace"]
super
end
end
# - ResultIssueSummaries
# * Kind: object
# * Properties:
# + analyzerWarningSummaries: [IssueSummary]
# + errorSummaries: [IssueSummary]
# + testFailureSummaries: [TestFailureIssueSummary]
# + warningSummaries: [IssueSummary]
class ResultIssueSummaries < AbstractObject
attr_accessor :analyzer_warning_summaries
attr_accessor :error_summaries
attr_accessor :test_failure_summaries
attr_accessor :warning_summaries
def initialize(data)
self.analyzer_warning_summaries = fetch_values(data, "analyzerWarningSummaries").map do |summary_data|
IssueSummary.new(summary_data)
end
self.error_summaries = fetch_values(data, "errorSummaries").map do |summary_data|
IssueSummary.new(summary_data)
end
self.test_failure_summaries = fetch_values(data, "testFailureSummaries").map do |summary_data|
TestFailureIssueSummary.new(summary_data)
end
self.warning_summaries = fetch_values(data, "warningSummaries").map do |summary_data|
IssueSummary.new(summary_data)
end
super
end
end
# - TestFailureIssueSummary
# * Supertype: IssueSummary
# * Kind: object
# * Properties:
# + testCaseName: String
class TestFailureIssueSummary < IssueSummary
attr_accessor :test_case_name
def initialize(data)
self.test_case_name = fetch_value(data, "testCaseName")
super
end
def failure_message
new_message = self.message
if self.document_location_in_creating_workspace&.url
file_path = self.document_location_in_creating_workspace.url.gsub("file://", "")
new_message += " (#{file_path})"
end
return new_message
end
end
module Parser
class << self
def parse_xcresult(path:, output_remove_retry_attempts: false)
require 'json'
# Executes xcresulttool to get JSON format of the result bundle object
# Hotfix: From Xcode 16 beta 3 'xcresulttool get --format json' has been deprecated; '--legacy' flag required to keep on using the command
xcresulttool_cmd = generate_cmd_parse_xcresult(path)
result_bundle_object_raw = execute_cmd(xcresulttool_cmd)
result_bundle_object = JSON.parse(result_bundle_object_raw)
# Parses JSON into ActionsInvocationRecord to find a list of all ids for ActionTestPlanRunSummaries
actions_invocation_record = Trainer::LegacyXCResult::ActionsInvocationRecord.new(result_bundle_object)
test_refs = actions_invocation_record.actions.map do |action|
action.action_result.tests_ref
end.compact
ids = test_refs.map(&:id)
# Maps ids into ActionTestPlanRunSummaries by executing xcresulttool to get JSON
# containing specific information for each test summary,
summaries = ids.map do |id|
raw = execute_cmd([*xcresulttool_cmd, '--id', id])
json = JSON.parse(raw)
Trainer::LegacyXCResult::ActionTestPlanRunSummaries.new(json)
end
# Converts the ActionTestPlanRunSummaries to data for junit generator
failures = actions_invocation_record.issues.test_failure_summaries || []
summaries_to_data(summaries, failures, output_remove_retry_attempts: output_remove_retry_attempts)
end
private
def summaries_to_data(summaries, failures, output_remove_retry_attempts: false)
# Gets flat list of all ActionTestableSummary
all_summaries = summaries.map(&:summaries).flatten
testable_summaries = all_summaries.map(&:testable_summaries).flatten
summaries_to_names = test_summaries_to_configuration_names(all_summaries)
# Maps ActionTestableSummary to rows for junit generator
rows = testable_summaries.map do |testable_summary|
all_tests = testable_summary.all_tests.flatten
# Used by store number of passes and failures by identifier
# This is used when Xcode 13 (and up) retries tests
# The identifier is duplicated until test succeeds or max count is reached
tests_by_identifier = {}
test_rows = all_tests.map do |test|
identifier = "#{test.parent.name}.#{test.name}"
test_row = {
identifier: identifier,
name: test.name,
duration: test.duration,
status: test.test_status,
test_group: test.parent.name,
# These don't map to anything but keeping empty strings
guid: ""
}
info = tests_by_identifier[identifier] || {}
info[:failure_count] ||= 0
info[:skip_count] ||= 0
info[:success_count] ||= 0
retry_count = info[:retry_count]
if retry_count.nil?
retry_count = 0
else
retry_count += 1
end
info[:retry_count] = retry_count
# Set failure message if failure found
failure = test.find_failure(failures)
if failure
test_row[:failures] = [{
file_name: "",
line_number: 0,
message: "",
performance_failure: {},
failure_message: failure.failure_message
}]
info[:failure_count] += 1
elsif test.test_status == "Skipped"
test_row[:skipped] = true
info[:skip_count] += 1
else
info[:success_count] = 1
end
tests_by_identifier[identifier] = info
test_row
end
# Remove retry attempts from the count and test rows
if output_remove_retry_attempts
test_rows = test_rows.reject do |test_row|
remove = false
identifier = test_row[:identifier]
info = tests_by_identifier[identifier]
# Remove if this row is a retry and is a failure
if info[:retry_count] > 0
remove = !(test_row[:failures] || []).empty?
end
# Remove all failure and retry count if test did eventually pass
if remove
info[:failure_count] -= 1
info[:retry_count] -= 1
tests_by_identifier[identifier] = info
end
remove
end
end
row = {
project_path: testable_summary.project_relative_path,
target_name: testable_summary.target_name,
test_name: testable_summary.name,
configuration_name: summaries_to_names[testable_summary],
duration: all_tests.map(&:duration).inject(:+),
tests: test_rows
}
row[:number_of_tests] = row[:tests].count
row[:number_of_failures] = row[:tests].find_all { |a| (a[:failures] || []).count > 0 }.count
# Used for seeing if any tests continued to fail after all of the Xcode 13 (and up) retries have finished
unique_tests = tests_by_identifier.values || []
row[:number_of_tests_excluding_retries] = unique_tests.count
row[:number_of_skipped] = unique_tests.map { |a| a[:skip_count] }.inject(:+)
row[:number_of_failures_excluding_retries] = unique_tests.find_all { |a| (a[:success_count] + a[:skip_count]) == 0 }.count
row[:number_of_retries] = unique_tests.map { |a| a[:retry_count] }.inject(:+)
row
end
rows
end
def test_summaries_to_configuration_names(test_summaries)
summary_to_name = {}
test_summaries.each do |summary|
summary.testable_summaries.each do |testable_summary|
summary_to_name[testable_summary] = summary.name
end
end
summary_to_name
end
def generate_cmd_parse_xcresult(path)
xcresulttool_cmd = [
'xcrun',
'xcresulttool',
'get',
'--format',
'json',
'--path',
path
]
xcresulttool_cmd << '--legacy' if Trainer::XCResult::Helper.supports_xcode16_xcresulttool?
xcresulttool_cmd
end
def execute_cmd(cmd)
output, status = Open3.capture2e(*cmd)
raise "Failed to execute '#{cmd}': #{output}" unless status.success?
return output
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/commands_generator.rb | trainer/lib/trainer/commands_generator.rb | require 'commander'
require 'fastlane_core/configuration/configuration'
require 'fastlane_core/ui/help_formatter'
require_relative 'options'
require_relative 'test_parser'
require_relative 'module'
HighLine.track_eof = false
module Trainer
class CommandsGenerator
include Commander::Methods
def self.start
self.new.run
end
def run
program :version, Fastlane::VERSION
program :description, Trainer::DESCRIPTION
program :help, 'Author', 'Felix Krause <trainer@krausefx.com>'
program :help, 'Website', 'https://fastlane.tools'
program :help, 'GitHub', 'https://github.com/KrauseFx/trainer'
program :help_formatter, :compact
global_option('--verbose', 'Shows a more verbose output') { $verbose = true }
always_trace!
FastlaneCore::CommanderGenerator.new.generate(Trainer::Options.available_options)
command :run do |c|
c.syntax = 'trainer'
c.description = Trainer::DESCRIPTION
c.action do |args, options|
options = FastlaneCore::Configuration.create(Trainer::Options.available_options, options.__hash__)
FastlaneCore::PrintTable.print_values(config: options, title: "Summary for trainer #{Fastlane::VERSION}") if $verbose
Trainer::TestParser.auto_convert(options)
end
end
default_command(:run)
run!
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/test_parser.rb | trainer/lib/trainer/test_parser.rb | require 'plist'
require 'fastlane_core/print_table'
require_relative 'xcresult'
require_relative 'xcresult/helper'
require_relative 'junit_generator'
require_relative 'legacy_xcresult'
require_relative 'plist_test_summary_parser'
require_relative 'module'
module Trainer
class TestParser
attr_accessor :data
attr_accessor :number_of_tests
attr_accessor :number_of_failures
attr_accessor :number_of_tests_excluding_retries
attr_accessor :number_of_failures_excluding_retries
attr_accessor :number_of_retries
attr_accessor :number_of_skipped
# Returns a hash with the path being the key, and the value
# defining if the tests were successful
def self.auto_convert(config)
unless config[:silent]
FastlaneCore::PrintTable.print_values(config: config,
title: "Summary for trainer #{Fastlane::VERSION}")
end
containing_dir = config[:path]
# Xcode < 10
files = Dir["#{containing_dir}/**/Logs/Test/*TestSummaries.plist"]
files += Dir["#{containing_dir}/Test/*TestSummaries.plist"]
files += Dir["#{containing_dir}/*TestSummaries.plist"]
# Xcode 10
files += Dir["#{containing_dir}/**/Logs/Test/*.xcresult/TestSummaries.plist"]
files += Dir["#{containing_dir}/Test/*.xcresult/TestSummaries.plist"]
files += Dir["#{containing_dir}/*.xcresult/TestSummaries.plist"]
files += Dir[containing_dir] if containing_dir.end_with?(".plist") # if it's the exact path to a plist file
# Xcode 11
files += Dir["#{containing_dir}/**/Logs/Test/*.xcresult"]
files += Dir["#{containing_dir}/Test/*.xcresult"]
files += Dir["#{containing_dir}/*.xcresult"]
files << containing_dir if File.extname(containing_dir) == ".xcresult"
if files.empty?
UI.user_error!("No test result files found in directory '#{containing_dir}', make sure the file name ends with 'TestSummaries.plist' or '.xcresult'")
end
return_hash = {}
files.each do |path|
extension = config[:extension]
output_filename = config[:output_filename]
should_write_file = !extension.nil? || !output_filename.nil?
if should_write_file
if config[:output_directory]
FileUtils.mkdir_p(config[:output_directory])
# Remove .xcresult or .plist extension
# Use custom file name ONLY if one file otherwise issues
if files.size == 1 && output_filename
filename = output_filename
elsif path.end_with?(".xcresult")
filename ||= File.basename(path).gsub(".xcresult", extension)
else
filename ||= File.basename(path).gsub(".plist", extension)
end
to_path = File.join(config[:output_directory], filename)
else
# Remove .xcresult or .plist extension
if path.end_with?(".xcresult")
to_path = path.gsub(".xcresult", extension)
else
to_path = path.gsub(".plist", extension)
end
end
end
tp = Trainer::TestParser.new(path, config)
File.write(to_path, tp.to_junit) if should_write_file
UI.success("Successfully generated '#{to_path}'") if should_write_file && !config[:silent]
return_hash[path] = {
to_path: to_path,
successful: tp.tests_successful?,
number_of_tests: tp.number_of_tests,
number_of_failures: tp.number_of_failures,
number_of_tests_excluding_retries: tp.number_of_tests_excluding_retries,
number_of_failures_excluding_retries: tp.number_of_failures_excluding_retries,
number_of_retries: tp.number_of_retries,
number_of_skipped: tp.number_of_skipped
}
end
return_hash
end
def initialize(path, config = {})
path = File.expand_path(path)
UI.user_error!("File not found at path '#{path}'") unless File.exist?(path)
if File.directory?(path) && path.end_with?(".xcresult")
parser = XCResult::Helper.supports_xcode16_xcresulttool? && !config[:force_legacy_xcresulttool] ? XCResult::Parser : LegacyXCResult::Parser
self.data = parser.parse_xcresult(path: path, output_remove_retry_attempts: config[:output_remove_retry_attempts])
else
file_content = File.read(path)
raw_json = Plist.parse_xml(file_content)
return if raw_json["FormatVersion"].to_s.length.zero? # maybe that's a useless plist file
PlistTestSummaryParser.ensure_file_valid!(raw_json)
self.data = PlistTestSummaryParser.parse_content(raw_json, config[:xcpretty_naming])
end
self.number_of_tests = 0
self.number_of_failures = 0
self.number_of_tests_excluding_retries = 0
self.number_of_failures_excluding_retries = 0
self.number_of_retries = 0
self.number_of_skipped = 0
self.data.each do |thing|
self.number_of_tests += thing[:number_of_tests].to_i
self.number_of_failures += thing[:number_of_failures].to_i
self.number_of_tests_excluding_retries += thing[:number_of_tests_excluding_retries].to_i
self.number_of_failures_excluding_retries += thing[:number_of_failures_excluding_retries].to_i
self.number_of_retries += thing[:number_of_retries].to_i
self.number_of_skipped += thing[:number_of_skipped].to_i
end
end
# Returns the JUnit report as String
def to_junit
self.data.kind_of?(Trainer::XCResult::TestPlan) ? self.data.to_xml : JunitGenerator.new(self.data).generate
end
# @return [Bool] were all tests successful? Is false if at least one test failed
def tests_successful?
self.data.collect { |a| a[:number_of_failures_excluding_retries] }.all?(&:zero?)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/module.rb | trainer/lib/trainer/module.rb | require 'fastlane_core/helper'
require 'fastlane/boolean'
module Trainer
Helper = FastlaneCore::Helper # you gotta love Ruby: Helper.* should use the Helper class contained in FastlaneCore
UI = FastlaneCore::UI
Boolean = Fastlane::Boolean
ROOT = Pathname.new(File.expand_path('../../..', __FILE__))
DESCRIPTION = "Convert xcodebuild plist and xcresult files to JUnit reports"
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/xcresult/test_plan.rb | trainer/lib/trainer/xcresult/test_plan.rb | require_relative 'test_suite'
module Trainer
module XCResult
# Represents a collection of test suites + the configuration, and device used to run them
class TestPlan
attr_reader :test_suites, :name, :configurations, :devices
attr_accessor :output_remove_retry_attempts
def initialize(test_suites:, configurations: [], devices: [], output_remove_retry_attempts: false)
@test_suites = test_suites
@configurations = configurations
@devices = devices
@output_remove_retry_attempts = output_remove_retry_attempts
end
def self.from_json(json:)
# Extract configurations and devices
configurations = json['testPlanConfigurations'] || []
devices = json['devices'] || []
# Find the test plan node (root of test results)
test_plan_node = json['testNodes']&.find { |node| node['nodeType'] == 'Test Plan' }
return new(test_suites: []) if test_plan_node.nil?
# Convert test plan node's children (test bundles) to TestSuite objects
test_suites = test_plan_node['children']&.map do |test_bundle|
TestSuite.from_json(
node: test_bundle
)
end || []
new(
test_suites: test_suites,
configurations: configurations,
devices: devices
)
end
# Allows iteration over test suites. Used by TestParser to collect test results
include Enumerable
def each(&block)
test_suites.map(&:to_hash).each(&block)
end
# Generates a JUnit-compatible XML representation of the test plan
# See https://github.com/testmoapp/junitxml/
def to_xml
# Create the root testsuites element with calculated summary attributes
testsuites = Helper.create_xml_element('testsuites',
tests: test_suites.sum(&:test_cases_count).to_s,
failures: test_suites.sum(&:failures_count).to_s,
skipped: test_suites.sum(&:skipped_count).to_s,
time: test_suites.sum(&:duration).to_s)
# Create <properties> node for configuration and device, to be applied to each suite node
properties = Helper.create_xml_element('properties').tap do |node|
@configurations.each do |config|
config_prop = Helper.create_xml_element('property', name: 'Configuration', value: config['configurationName'])
node.add_element(config_prop)
end
@devices.each do |device|
device_prop = Helper.create_xml_element('property', name: 'device', value: "#{device.fetch('modelName', 'Unknown Device')} (#{device.fetch('osVersion', 'Unknown OS Version')})")
node.add_element(device_prop)
end
end
# Add each test suite to the root
test_suites.each do |suite|
suite_node = suite.to_xml(output_remove_retry_attempts: output_remove_retry_attempts)
# In JUnit conventions, the <testsuites> root element can't have properties
# So we add the <properties> node to each child <testsuite> node instead
suite_node.add_element(properties.dup) if properties.elements.any?
testsuites.add_element(suite_node)
end
# Convert to XML string with prologue
doc = REXML::Document.new
doc << REXML::XMLDecl.new('1.0', 'UTF-8')
doc.add(testsuites)
formatter = REXML::Formatters::Pretty.new
output = String.new
formatter.write(doc, output)
output
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/xcresult/test_case.rb | trainer/lib/trainer/xcresult/test_case.rb | require_relative 'helper'
require_relative 'test_case_attributes'
require_relative 'repetition'
module Trainer
module XCResult
# Represents a test case, including its retries (aka repetitions)
class TestCase
include TestCaseAttributes
attr_reader :name
attr_reader :identifier
attr_reader :duration
attr_reader :result
attr_reader :classname
attr_reader :argument
# @return [Array<Repetition>] Array of retry attempts for this test case, **including the initial attempt**
# This will be `nil` if the test case was not run multiple times, but will contain all repetitions if it was run more than once.
attr_reader :retries
attr_reader :failure_messages
attr_reader :source_references
attr_reader :attachments
attr_reader :tags
def initialize(
name:, identifier:, duration:, result:, classname:, argument: nil, tags: [], retries: nil,
failure_messages: [], source_references: [], attachments: []
)
@name = name
@identifier = identifier
@duration = duration
@result = result
@classname = classname
@argument = argument
@tags = tags
@retries = retries
@failure_messages = failure_messages
@source_references = source_references
@attachments = attachments
end
def self.from_json(node:)
# Handle test case arguments
argument_nodes = Helper.find_json_children(node, 'Arguments')
argument_nodes = [nil] if argument_nodes.empty?
# Generate test cases for each argument
argument_nodes.map do |arg_node|
# For repetition nodes, failure messages, source refs, attachments and result attributes,
# Search them as children of the argument child node if present, of the test case node otherwise.
node_for_attributes = arg_node || node
retries = Helper.find_json_children(node_for_attributes, 'Repetition', 'Test Case Run')
&.map { |rep_node| Repetition.from_json(node: rep_node) } || []
failure_messages = if retries.empty?
extract_failure_messages(node_for_attributes)
else
retries.flat_map(&:failure_messages)
end
source_references = if retries.empty?
extract_source_references(node_for_attributes)
else
retries.flat_map(&:source_references)
end
attachments = if retries.empty?
extract_attachments(node_for_attributes)
else
retries.flat_map(&:attachments)
end
new(
name: node['name'],
identifier: node['nodeIdentifier'],
duration: parse_duration(node['duration']),
result: node_for_attributes['result'],
classname: extract_classname(node),
argument: arg_node&.[]('name'), # Only set if there is an argument
tags: node['tags'] || [],
retries: retries,
failure_messages: failure_messages,
source_references: source_references,
attachments: attachments
)
end
end
# Generates XML nodes for the test case
#
# @return [Array<REXML::Element>] An array of XML <testcase> elements
#
# - If no retries, the array contains a single <testcase> element
# - If retries, the array contains one <testcase> element per retry
def to_xml_nodes
runs = @retries.nil? || @retries.empty? ? [nil] : @retries
runs.map do |run|
Helper.create_xml_element('testcase',
name: if @argument.nil?
@name
else
@name.match?(/(\(.*\))/) ? @name.gsub(/(\(.*\))/, "(#{@argument})") : "#{@name} (#{@argument})"
end,
classname: @classname,
time: (run || self).duration.to_s).tap do |testcase|
add_xml_result_elements(testcase, run || self)
add_properties_to_xml(testcase, repetition_name: run&.name)
end
end
end
def retries_count
@retries&.count || 0
end
def total_tests_count
retries_count > 0 ? retries_count : 1
end
def total_failures_count
if retries_count > 0
@retries.count(&:failed?)
elsif failed?
1
else
0
end
end
def self.extract_classname(node)
return nil if node['nodeIdentifier'].nil?
parts = node['nodeIdentifier'].split('/')
parts[0...-1].join('.')
end
private_class_method :extract_classname
private
# Adds <properties> element to the XML <testcase> element
#
# @param testcase [REXML::Element] The XML testcase element to add properties to
# @param repetition_name [String, nil] Name of the retry attempt, if this is a retry
#
# Properties added:
# - if argument is present:
# - `testname`: Raw test name (as in such case, <testcase name="…"> would contain a mix of the test name and the argument)
# - `argument`: Test argument value
# - `repetitionN`: Name of the retry attempt if present
# - `source_referenceN`: Source code references (file/line) for failures
# - `attachmentN`: Test attachments like screenshots
# - `tagN`: Test tags/categories
#
# <properties> element is only added to the XML if at least one property exists
def add_properties_to_xml(testcase, repetition_name: nil)
properties = Helper.create_xml_element('properties')
# Add argument as property
if @argument
name_prop = Helper.create_xml_element('property', name: "testname", value: @name)
properties.add_element(name_prop)
prop = Helper.create_xml_element('property', name: "argument", value: @argument)
properties.add_element(prop)
end
# Add repetition as property
if repetition_name
prop = Helper.create_xml_element('property', name: "repetition", value: repetition_name)
properties.add_element(prop)
end
# Add source references as properties
(@source_references || []).each_with_index do |ref, index|
prop = Helper.create_xml_element('property', name: "source_reference#{index + 1}", value: ref)
properties.add_element(prop)
end
# Add attachments as properties
(@attachments || []).each_with_index do |attachment, index|
prop = Helper.create_xml_element('property', name: "attachment#{index + 1}", value: attachment)
properties.add_element(prop)
end
# Add tags as properties
(@tags || []).sort.each_with_index do |tag, index|
prop = Helper.create_xml_element('property', name: "tag#{index + 1}", value: tag)
properties.add_element(prop)
end
# Only add properties to testcase if it has child elements
testcase.add_element(properties) if properties.elements.any?
end
# Adds <failure> and <skipped> elements to the XML <testcase> element based on test status
#
# @param testcase [REXML::Element] The XML testcase element to add result elements to
# @param test_obj [Repetition, TestCase] Object representing the test result
# This can be either a Repetition object or the TestCase itself.
# Must respond to the following methods:
# - failed? [Boolean]: Indicates if the test failed
# - skipped? [Boolean]: Indicates if the test was skipped
# - failure_messages [Array<String>, nil]: List of failure messages (optional)
#
# Adds:
# - <failure> elements with messages for failed tests
# - <skipped> element for skipped tests
# - No elements added for passed tests
def add_xml_result_elements(testcase, test_obj)
if test_obj.failed?
(test_obj.failure_messages&.any? ? test_obj.failure_messages : [nil]).each do |msg|
testcase.add_element(Helper.create_xml_element('failure', message: msg))
end
elsif test_obj.skipped?
testcase.add_element(Helper.create_xml_element('skipped', message: test_obj.failure_messages&.first))
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/xcresult/repetition.rb | trainer/lib/trainer/xcresult/repetition.rb | require_relative 'test_case_attributes'
module Trainer
module XCResult
# Represents retries of a test case, including the original run
# e.g. a test case that ran 3 times in total will be represented by 3 Repetition instances in the `xcresulttool` JSON output,
# one for the original run and one for the 2 retries.
class Repetition
include TestCaseAttributes
attr_reader :name
attr_reader :duration
attr_reader :result
attr_reader :failure_messages
attr_reader :source_references
attr_reader :attachments
def initialize(name:, duration:, result:, failure_messages: [], source_references: [], attachments: [])
@name = name
@duration = duration
@result = result
@failure_messages = failure_messages
@source_references = source_references
@attachments = attachments
end
def self.from_json(node:)
new(
name: node['name'],
duration: parse_duration(node['duration']),
result: node['result'],
failure_messages: extract_failure_messages(node),
source_references: extract_source_references(node),
attachments: extract_attachments(node)
)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/xcresult/test_case_attributes.rb | trainer/lib/trainer/xcresult/test_case_attributes.rb | module Trainer
module XCResult
# Mixin for shared attributes between TestCase and Repetition
module TestCaseAttributes
def self.included(base)
base.extend(ClassMethods)
end
def passed?
@result == 'Passed'
end
def failed?
@result == 'Failed'
end
def skipped?
@result == 'Skipped'
end
module ClassMethods
def parse_duration(duration_str)
return 0.0 if duration_str.nil?
# Handle comma-separated duration, and remove 's' suffix
duration_str.gsub(',', '.').chomp('s').to_f
end
def extract_failure_messages(node)
node['children']
&.select { |child| child['nodeType'] == 'Failure Message' }
&.map { |msg| msg['name'] } || []
end
def extract_source_references(node)
node['children']
&.select { |child| child['nodeType'] == 'Source Code Reference' }
&.map { |ref| ref['name'] } || []
end
def extract_attachments(node)
node['children']
&.select { |child| child['nodeType'] == 'Attachment' }
&.map { |attachment| attachment['name'] } || []
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/xcresult/helper.rb | trainer/lib/trainer/xcresult/helper.rb | require 'rexml/document'
require 'rubygems'
module Trainer
module XCResult
# Helper class for XML and node operations
class Helper
# Creates an XML element with the given name and attributes
#
# @param name [String] The name of the XML element
# @param attributes [Hash] A hash of attributes to add to the element
# @return [REXML::Element] The created XML element
def self.create_xml_element(name, **attributes)
# Sanitize invalid XML characters (control chars except tab/CR/LF) to avoid errors when generating XML
sanitizer = proc { |text| text.to_s.gsub(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/) { |c| format("\\u%04x", c.ord) } }
element = REXML::Element.new(sanitizer.call(name))
attributes.compact.each do |key, value|
safe_value = sanitizer.call(value.to_s)
element.attributes[key.to_s] = safe_value
end
element
end
# Find children of a node by specified node types
#
# @param node [Hash, nil] The JSON node to search within
# @param node_types [Array<String>] The node types to filter by
# @return [Array<Hash>] Array of child nodes matching the specified types
def self.find_json_children(node, *node_types)
return [] if node.nil? || node['children'].nil?
node['children'].select { |child| node_types.include?(child['nodeType']) }
end
# Check if the current xcresulttool supports new commands introduced in Xcode 16+
#
# Since Xcode 16b3, xcresulttool has marked `get <object> --format json` as deprecated/legacy,
# and replaced it with `xcrun xcresulttool get test-results tests` instead.
#
# @return [Boolean] Whether the xcresulttool supports Xcode 16+ commands
def self.supports_xcode16_xcresulttool?
# e.g. DEVELOPER_DIR=/Applications/Xcode_16_beta_3.app
# xcresulttool version 23021, format version 3.53 (current)
match = `xcrun xcresulttool version`.match(/xcresulttool version (?<version>[\d.]+)/)
version = match[:version]
Gem::Version.new(version) >= Gem::Version.new(23_021)
rescue
false
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/trainer/lib/trainer/xcresult/test_suite.rb | trainer/lib/trainer/xcresult/test_suite.rb | require_relative 'test_case'
module Trainer
module XCResult
# Represents a test suite, including its test cases and sub-suites
class TestSuite
attr_reader :name
attr_reader :identifier
attr_reader :type
attr_reader :result
attr_reader :test_cases
attr_reader :sub_suites
attr_reader :tags
def initialize(name:, identifier:, type:, result:, tags: [], test_cases: [], sub_suites: [])
@name = name
@identifier = identifier
@type = type
@result = result
@tags = tags
@test_cases = test_cases
@sub_suites = sub_suites
end
def self.from_json(node:)
# Create initial TestSuite with basic attributes
test_suite = new(
name: node['name'],
identifier: node['nodeIdentifier'],
type: node['nodeType'],
result: node['result'],
tags: node['tags'] || []
)
# Process children to populate test_cases and sub_suites
test_suite.process_children(node['children'] || [])
test_suite
end
def passed?
@result == 'Passed'
end
def failed?
@result == 'Failed'
end
def skipped?
@result == 'Skipped'
end
def duration
@duration ||= @test_cases.sum(&:duration) + @sub_suites.sum(&:duration)
end
def test_cases_count
@test_cases_count ||= @test_cases.count + @sub_suites.sum(&:test_cases_count)
end
def failures_count
@failures_count ||= @test_cases.count(&:failed?) + @sub_suites.sum(&:failures_count)
end
def skipped_count
@skipped_count ||= @test_cases.count(&:skipped?) + @sub_suites.sum(&:skipped_count)
end
def total_tests_count
@test_cases.sum(&:total_tests_count) +
@sub_suites.sum(&:total_tests_count)
end
def total_failures_count
@test_cases.sum(&:total_failures_count) +
@sub_suites.sum(&:total_failures_count)
end
def total_retries_count
@test_cases.sum(&:retries_count) +
@sub_suites.sum(&:total_retries_count)
end
# Hash representation used by TestParser to collect test results
def to_hash
{
number_of_tests: total_tests_count,
number_of_failures: total_failures_count,
number_of_tests_excluding_retries: test_cases_count,
number_of_failures_excluding_retries: failures_count,
number_of_retries: total_retries_count,
number_of_skipped: skipped_count
}
end
# Generates a JUnit-compatible XML representation of the test suite
# See https://github.com/testmoapp/junitxml/
def to_xml(output_remove_retry_attempts: false)
testsuite = Helper.create_xml_element('testsuite',
name: @name,
time: duration.to_s,
tests: test_cases_count.to_s,
failures: failures_count.to_s,
skipped: skipped_count.to_s)
# Add test cases
@test_cases.each do |test_case|
runs = test_case.to_xml_nodes
runs = runs.last(1) if output_remove_retry_attempts
runs.each { |node| testsuite.add_element(node) }
end
# Add sub-suites
@sub_suites.each do |sub_suite|
testsuite.add_element(sub_suite.to_xml(output_remove_retry_attempts: output_remove_retry_attempts))
end
testsuite
end
def process_children(children)
children.each do |child|
case child['nodeType']
when 'Test Case'
# Use from_json to generate multiple test cases if needed
@test_cases.concat(TestCase.from_json(node: child))
when 'Test Suite', 'Unit test bundle', 'UI test bundle'
@sub_suites << TestSuite.from_json(node: child)
end
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/sync_screenshots_spec.rb | deliver/spec/sync_screenshots_spec.rb | require 'deliver/sync_screenshots'
require 'fakefs/spec_helpers'
describe Deliver::SyncScreenshots do
describe '#do_replace_screenshots' do
subject { described_class.new(app: nil, platform: nil) }
before do
# To emulate checksum calculation, return the given path as a checksum
allow(Deliver::ScreenshotComparable).to receive(:calculate_checksum) { |path| path }
end
let(:en_US) { mock_app_store_version_localization }
let(:app_screenshot_set_55) { mock_app_screenshot_set(display_type: DisplayType::APP_IPHONE_55) }
let(:app_screenshot_set_65) { mock_app_screenshot_set(display_type: DisplayType::APP_IPHONE_65) }
context 'ASC has nothing and going to add screenshots' do
let(:screenshots) do
[
mock_screenshot(path: '5.5_1.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_55),
mock_screenshot(path: '5.5_2.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_55),
mock_screenshot(path: '6.5_1.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_65),
mock_screenshot(path: '6.5_2.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_65)
]
end
let(:iterator) do
mock_app_screenshot_iterator(
each_app_screenshot: [
],
each_local_screenshot: [
[en_US, app_screenshot_set_55, screenshots[0], 0],
[en_US, app_screenshot_set_55, screenshots[1], 1],
[en_US, app_screenshot_set_65, screenshots[2], 0],
[en_US, app_screenshot_set_65, screenshots[3], 1]
]
)
end
it 'should enqueue upload jobs for the screenshots that do not exist on App Store Connect' do
delete_worker = mock_queue_worker([])
upload_worker = mock_queue_worker([Deliver::SyncScreenshots::UploadScreenshotJob.new(app_screenshot_set_55, screenshots[0].path),
Deliver::SyncScreenshots::UploadScreenshotJob.new(app_screenshot_set_55, screenshots[1].path),
Deliver::SyncScreenshots::UploadScreenshotJob.new(app_screenshot_set_65, screenshots[2].path),
Deliver::SyncScreenshots::UploadScreenshotJob.new(app_screenshot_set_65, screenshots[3].path)])
subject.do_replace_screenshots(iterator, screenshots, delete_worker, upload_worker)
end
end
context 'ASC has a screenshot on each screenshot set and going to add another screenshot' do
let(:screenshots) do
[
mock_screenshot(path: '5.5_1.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_55),
mock_screenshot(path: '5.5_2.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_55),
mock_screenshot(path: '6.5_1.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_65),
mock_screenshot(path: '6.5_2.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_65)
]
end
let(:iterator) do
mock_app_screenshot_iterator(
each_app_screenshot: [
[en_US, app_screenshot_set_55, mock_app_screenshot(path: '5.5_1.jpg')],
[en_US, app_screenshot_set_65, mock_app_screenshot(path: '6.5_1.jpg')]
],
each_local_screenshot: [
[en_US, app_screenshot_set_55, screenshots[0], 0],
[en_US, app_screenshot_set_55, screenshots[1], 1],
[en_US, app_screenshot_set_65, screenshots[2], 0],
[en_US, app_screenshot_set_65, screenshots[3], 1]
]
)
end
it 'should enqueue upload jobs for the screenshots that do not exist on App Store Connect' do
delete_worker = mock_queue_worker([])
upload_worker = mock_queue_worker([Deliver::SyncScreenshots::UploadScreenshotJob.new(app_screenshot_set_55, screenshots[1].path),
Deliver::SyncScreenshots::UploadScreenshotJob.new(app_screenshot_set_65, screenshots[3].path)])
subject.do_replace_screenshots(iterator, screenshots, delete_worker, upload_worker)
end
end
context 'ASC has screenshots but the user has nothing locally' do
let(:screenshots) do
[]
end
let(:app_screenshots) do
[
mock_app_screenshot(path: '5.5_1.jpg'),
mock_app_screenshot(path: '6.5_1.jpg')
]
end
let(:iterator) do
mock_app_screenshot_iterator(
each_app_screenshot: [
[en_US, app_screenshot_set_55, app_screenshots[0]],
[en_US, app_screenshot_set_65, app_screenshots[1]]
],
each_local_screenshot: [
]
)
end
it 'should enqueue delete jobs for the screenshots that do not exist on local' do
delete_worker = mock_queue_worker([Deliver::SyncScreenshots::DeleteScreenshotJob.new(app_screenshots[0], en_US.locale),
Deliver::SyncScreenshots::DeleteScreenshotJob.new(app_screenshots[1], en_US.locale)])
upload_worker = mock_queue_worker([])
subject.do_replace_screenshots(iterator, screenshots, delete_worker, upload_worker)
end
end
context 'ASC has some screenshots and the user replaces some of them' do
let(:app_screenshots) do
[
mock_app_screenshot(path: '5.5_1.jpg'),
mock_app_screenshot(path: '5.5_2.jpg'),
mock_app_screenshot(path: '6.5_1.jpg'),
mock_app_screenshot(path: '6.5_2.jpg')
]
end
let(:screenshots) do
[
mock_screenshot(path: '5.5_1.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_55),
mock_screenshot(path: '5.5_2_improved.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_55),
mock_screenshot(path: '6.5_1.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_65),
mock_screenshot(path: '6.5_2_improved.jpg', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_65)
]
end
let(:iterator) do
mock_app_screenshot_iterator(
each_app_screenshot: [
[en_US, app_screenshot_set_55, app_screenshots[0]],
[en_US, app_screenshot_set_55, app_screenshots[1]],
[en_US, app_screenshot_set_65, app_screenshots[2]],
[en_US, app_screenshot_set_65, app_screenshots[3]]
],
each_local_screenshot: [
[en_US, app_screenshot_set_55, screenshots[0], 0],
[en_US, app_screenshot_set_55, screenshots[1], 1],
[en_US, app_screenshot_set_65, screenshots[2], 0],
[en_US, app_screenshot_set_65, screenshots[3], 1]
]
)
end
it 'should enqueue both delete and upload jobs to keep them up-to-date' do
delete_worker = mock_queue_worker([Deliver::SyncScreenshots::DeleteScreenshotJob.new(app_screenshots[1], en_US.locale),
Deliver::SyncScreenshots::DeleteScreenshotJob.new(app_screenshots[3], en_US.locale)])
upload_worker = mock_queue_worker([Deliver::SyncScreenshots::UploadScreenshotJob.new(app_screenshot_set_55, screenshots[1].path),
Deliver::SyncScreenshots::UploadScreenshotJob.new(app_screenshot_set_65, screenshots[3].path)])
subject.do_replace_screenshots(iterator, screenshots, delete_worker, upload_worker)
end
end
def mock_app_screenshot_iterator(each_app_screenshot: [], each_local_screenshot: [])
iterator = double('Deliver::AppScreenshotIterator')
enumerator1 = each_app_screenshot.to_enum
allow(iterator).to receive(:each_app_screenshot) do |&arg|
next(enumerator1.to_a) unless arg
arg.call(*enumerator1.next)
end
enumerator2 = each_local_screenshot.to_enum
allow(iterator).to receive(:each_local_screenshot) do |&arg|
next(enumerator2.to_a) unless arg
arg.call(*enumerator2.next)
end
iterator
end
def mock_queue_worker(enqueued_jobs)
queue_worker = double('FastlaneCore::QueueWorker')
expect(queue_worker).to receive(:batch_enqueue).with(enqueued_jobs)
expect(queue_worker).to receive(:start)
queue_worker
end
def mock_app_screenshot(path: '/path/to/screenshot')
screenshot = double(
'Spaceship::ConnectAPI::AppScreenshot',
file_name: path,
source_file_checksum: path # To match the behavior of stubbing checksum calculation, use given path as a checksum
)
allow(screenshot).to receive(:kind_of?).with(Spaceship::ConnectAPI::AppScreenshot).and_return(true)
screenshot
end
def mock_screenshot(path: '/path/to/screenshot', language: 'en-US', display_type: Deliver::AppScreenshot::DisplayType::APP_IPHONE_55)
screenshot = double(
'Deliver::AppScreenshot',
path: path,
language: language,
display_type: display_type
)
allow(screenshot).to receive(:kind_of?).with(Deliver::AppScreenshot).and_return(true)
screenshot
end
def mock_app_store_version_localization(locale: 'en-US', app_screenshot_sets: [])
double(
'Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: locale,
get_app_screenshot_sets: app_screenshot_sets
)
end
def mock_app_screenshot_set(display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55, app_screenshots: [])
app_screenshot_set = double(
'Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: display_type,
app_screenshots: app_screenshots
)
allow(app_screenshot_set).to receive(:kind_of?).with(Spaceship::ConnectAPI::AppScreenshotSet).and_return(true)
app_screenshot_set
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/setup_spec.rb | deliver/spec/setup_spec.rb | require 'deliver/setup'
describe Deliver do
describe Deliver::Setup do
describe '#generate_metadata_files' do
context 'with review_information' do
let(:setup) { Deliver::Setup.new }
let(:tempdir) { Dir.mktmpdir }
let(:app) { double('app') }
let(:app_info) do
double('app_info',
primary_category: double('primary_category', id: 'cat1'),
primary_subcategory_one: double('primary_subcategory_one', id: 'cat1sub1'),
primary_subcategory_two: double('primary_subcategory_two', id: 'cat1sub2'),
secondary_category: double('secondary_category', id: 'cat2'),
secondary_subcategory_one: double('secondary_subcategory_one', id: 'cat2sub1'),
secondary_subcategory_two: double('secondary_subcategory_two', id: 'cat2sub2'))
end
let(:app_info_localization_en) do
double('app_info_localization_en',
locale: "en-US",
name: "fastlane",
subtitle: "the fastest lane",
privacy_policy_url: "https://fastlane.tools/privacy/en",
privacy_policy_text: "fastlane privacy en")
end
let(:version) do
double('version',
copyright: "2020 fastlane")
end
let(:version_localization_en) do
double('version',
description: "description en",
locale: "en-US",
keywords: "app version en",
marketing_url: "https://fastlane.tools/en",
promotional_text: "promotional text en",
support_url: "https://fastlane.tools/support/en",
whats_new: "whats new en")
end
let(:app_review_detail) do
double('app_review_detail',
contact_first_name: 'John',
contact_last_name: 'Smith',
contact_phone: '+819012345678',
contact_email: 'deliver@example.com',
demo_account_name: 'user',
demo_account_password: 'password',
notes: 'This is a note')
end
before do
allow(app).to receive(:fetch_live_app_info).and_return(app_info)
allow(app_info).to receive(:get_app_info_localizations).and_return([app_info_localization_en])
allow(version).to receive(:get_app_store_version_localizations).and_return([version_localization_en])
allow(version).to receive(:fetch_app_store_review_detail).and_return(app_review_detail)
end
it 'generates metadata' do
map = {
"copyright" => "2020 fastlane",
"primary_category" => "cat1",
"secondary_category" => "cat2",
"primary_first_sub_category" => "cat1sub1",
"primary_second_sub_category" => "cat1sub2",
"secondary_first_sub_category" => "cat2sub1",
"secondary_second_sub_category" => "cat2sub2",
"en-US/description" => "description en",
"en-US/keywords" => "app version en",
"en-US/release_notes" => "whats new en",
"en-US/support_url" => "https://fastlane.tools/support/en",
"en-US/marketing_url" => "https://fastlane.tools/en",
"en-US/promotional_text" => "promotional text en",
"review_information/first_name" => "John",
"review_information/last_name" => "Smith",
"review_information/phone_number" => "+819012345678",
"review_information/email_address" => "deliver@example.com",
"review_information/demo_user" => "user",
"review_information/demo_password" => "password",
"review_information/notes" => "This is a note"
}
setup.generate_metadata_files(app, version, tempdir, { use_live_version: true })
base_dir = File.join(tempdir)
map.each do |filename, value|
path = File.join(base_dir, "#{filename}.txt")
expect(File.exist?(path)).to be_truthy, " for #{path}"
expect(File.read(path).strip).to eq(value)
end
end
after do
FileUtils.remove_entry_secure(tempdir)
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/commands_generator_spec.rb | deliver/spec/commands_generator_spec.rb | require 'deliver/commands_generator'
require 'deliver/setup'
describe Deliver::CommandsGenerator do
def expect_runner_run_with(expected_options)
fake_runner = "runner"
expect_runner_new_with(expected_options).and_return(fake_runner)
expect(fake_runner).to receive(:run)
end
def expect_runner_new_with(expected_options)
expect(Deliver::Runner).to receive(:new) do |actual_options|
expect(expected_options._values).to eq(actual_options._values)
end
end
describe ":run option handling" do
it "can use the username short flag from tool options" do
# leaving out the command name defaults to 'run'
stub_commander_runner_args(['--description', '{"en-US": "My description"}', '-u', 'me@it.com'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
description: { "en-US" => "My description" },
username: 'me@it.com'
})
expect_runner_run_with(expected_options)
Deliver::CommandsGenerator.start
end
it "can use the app_identifier flag from tool options" do
# leaving out the command name defaults to 'run'
stub_commander_runner_args(['--description', '{"en-US": "My description"}', '--app_identifier', 'abcd'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
description: { "en-US" => "My description" },
app_identifier: 'abcd'
})
expect_runner_run_with(expected_options)
Deliver::CommandsGenerator.start
end
end
describe ":submit_build option handling" do
it "can use the username short flag from tool options" do
stub_commander_runner_args(['submit_build', '--description', '{"en-US": "My description"}', '-u', 'me@it.com'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
description: { "en-US" => "My description" },
username: 'me@it.com',
submit_for_review: true,
build_number: 'latest'
})
expect_runner_run_with(expected_options)
Deliver::CommandsGenerator.start
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['submit_build', '--description', '{"en-US": "My description"}', '--app_identifier', 'abcd'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
description: { "en-US" => "My description" },
app_identifier: 'abcd',
submit_for_review: true,
build_number: 'latest'
})
expect_runner_run_with(expected_options)
Deliver::CommandsGenerator.start
end
end
describe ":init option handling" do
def expect_setup_run_with(expected_options)
fake_setup = "setup"
expect(Deliver::Setup).to receive(:new).and_return(fake_setup)
expect(fake_setup).to receive(:run) do |actual_options|
expect(expected_options._values).to eq(actual_options._values)
end
end
it "can use the username short flag from tool options" do
stub_commander_runner_args(['init', '--description', '{"en-US": "My description"}', '-u', 'me@it.com'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
description: { "en-US" => "My description" },
username: 'me@it.com',
run_precheck_before_submit: false
})
expect_runner_new_with(expected_options)
expect_setup_run_with(expected_options)
Deliver::CommandsGenerator.start
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['init', '--description', '{"en-US": "My description"}', '--app_identifier', 'abcd'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
description: { "en-US" => "My description" },
app_identifier: 'abcd',
run_precheck_before_submit: false
})
expect_runner_new_with(expected_options)
expect_setup_run_with(expected_options)
Deliver::CommandsGenerator.start
end
end
describe ":generate_summary option handling" do
def expect_generate_summary_run_with(expected_options)
fake_generate_summary = "generate_summary"
expect(Deliver::GenerateSummary).to receive(:new).and_return(fake_generate_summary)
expect(fake_generate_summary).to receive(:run) do |actual_options|
expect(expected_options._values).to eq(actual_options._values)
end
end
it "can use the username short flag from tool options" do
stub_commander_runner_args(['generate_summary', '-u', 'me@it.com', '-f', 'true'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
username: 'me@it.com',
force: true
})
expect_runner_new_with(expected_options)
expect_generate_summary_run_with(expected_options)
Deliver::CommandsGenerator.start
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['generate_summary', '--app_identifier', 'abcd', '-f', 'true'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
app_identifier: 'abcd',
force: true
})
expect_runner_new_with(expected_options)
expect_generate_summary_run_with(expected_options)
Deliver::CommandsGenerator.start
end
end
describe ":download_screenshots option handling" do
def expect_download_screenshots_run_with(expected_options)
expect(Deliver::DownloadScreenshots).to receive(:run) do |actual_options, screenshots_path|
expect(expected_options._values).to eq(actual_options._values)
expect(screenshots_path).to eq('screenshots/path')
end
end
it "can use the username short flag from tool options" do
stub_commander_runner_args(['download_screenshots', '-u', 'me@it.com', '-w', 'screenshots/path'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
username: 'me@it.com',
screenshots_path: 'screenshots/path'
})
expect_runner_new_with(expected_options)
expect_download_screenshots_run_with(expected_options)
Deliver::CommandsGenerator.start
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['download_screenshots', '--app_identifier', 'abcd', '-w', 'screenshots/path'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
app_identifier: 'abcd',
screenshots_path: 'screenshots/path'
})
expect_runner_new_with(expected_options)
expect_download_screenshots_run_with(expected_options)
Deliver::CommandsGenerator.start
end
end
describe ":download_metadata option handling" do
let(:latest_version) do
double('version',
version_string: "1.0.0")
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['download_metadata', '--app_identifier', 'abcd', '-m', 'metadata/path', '--force'])
expected_options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
app_identifier: 'abcd',
metadata_path: 'metadata/path',
force: true
})
fake_app = "fake_app"
expect(fake_app).to receive(:get_latest_app_store_version).and_return(latest_version)
expect(Deliver::Runner).to receive(:new) do |actual_options|
expect(expected_options._values).to eq(actual_options._values)
# ugly workaround to do the work that DetectValues would normally do
Deliver.cache[:app] = fake_app
end
fake_setup = "fake_setup"
expect(Deliver::Setup).to receive(:new).and_return(fake_setup)
expect(fake_setup).to receive(:generate_metadata_files) do |app, version, metadata_path|
expect(app).to eq(fake_app)
expect(version).to eq(latest_version)
expect(metadata_path).to eq('metadata/path')
end
Deliver::CommandsGenerator.start
end
describe "force overwriting metadata" do
it "forces overwriting metadata if force is set" do
options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
force: true
})
expect(Deliver::CommandsGenerator.force_overwrite_metadata?(options, "an/ignored/path")).to be_truthy
end
it "forces overwriting metadata if DELIVER_FORCE_OVERWRITE is set" do
FastlaneSpec::Env.with_env_values('DELIVER_FORCE_OVERWRITE' => '1') do
expect(Deliver::CommandsGenerator.force_overwrite_metadata?({}, "an/ignored/path")).to be_truthy
end
end
it "fails forcing overwriting metadata if DELIVER_FORCE_OVERWRITE isn't set, force isn't set and user answers no in interactive mode" do
options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
force: false
})
expect(UI).to receive(:interactive?).and_return(true)
expect(UI).to receive(:confirm).and_return(false)
expect(Deliver::CommandsGenerator.force_overwrite_metadata?(options, "an/ignored/path")).to be_falsy
end
it "forces overwriting metadata if DELIVER_FORCE_OVERWRITE isn't set, force isn't set and user answers yes in interactive mode" do
options = FastlaneCore::Configuration.create(Deliver::Options.available_options, {
force: false
})
expect(UI).to receive(:interactive?).and_return(true)
expect(UI).to receive(:confirm).and_return(true)
expect(Deliver::CommandsGenerator.force_overwrite_metadata?(options, "an/ignored/path")).to be_truthy
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/submit_for_review_spec.rb | deliver/spec/submit_for_review_spec.rb | require 'deliver/submit_for_review'
require 'ostruct'
describe Deliver::SubmitForReview do
let(:review_submitter) { Deliver::SubmitForReview.new }
describe 'submit app' do
let(:app) { double('app') }
let(:edit_version) do
double('edit_version',
id: '1',
version_string: "1.0.0")
end
let(:ready_for_review_version) do
double('ready_for_review_version',
id: '1',
app_version_state: "READY_FOR_REVIEW",
version_string: "1.0.0")
end
let(:prepare_for_submission_version) do
double('prepare_for_submission_version',
id: '1',
app_version_state: "PREPARE_FOR_SUBMISSION",
version_string: "1.0.0")
end
let(:selected_build) { double('selected_build') }
let(:submission) do
double('submission',
id: '1')
end
before do
allow(Deliver).to receive(:cache).and_return({ app: app })
end
context 'submit fails' do
it 'no version' do
options = {
platform: Spaceship::ConnectAPI::Platform::IOS
}
expect(app).to receive(:get_edit_app_store_version).and_return(nil)
expect(UI).to receive(:user_error!).with(/Cannot submit for review - could not find an editable version for/).and_raise("boom")
expect do
review_submitter.submit!(options)
end.to raise_error("boom")
end
it 'needs to set export_compliance_uses_encryption' do
options = {
platform: Spaceship::ConnectAPI::Platform::IOS
}
expect(app).to receive(:get_edit_app_store_version).and_return(edit_version)
expect(review_submitter).to receive(:select_build).and_return(selected_build)
expect(selected_build).to receive(:uses_non_exempt_encryption).and_return(nil)
expect(UI).to receive(:user_error!).with(/Export compliance is required to submit/).and_raise("boom")
expect do
review_submitter.submit!(options)
end.to raise_error("boom")
end
end
context 'submits successfully' do
describe 'no options' do
it 'with in progress review submission' do
options = {
platform: Spaceship::ConnectAPI::Platform::IOS
}
expect(app).to receive(:get_edit_app_store_version).and_return(edit_version)
expect(review_submitter).to receive(:select_build).and_return(selected_build)
expect(selected_build).to receive(:uses_non_exempt_encryption).and_return(false)
expect(app).to receive(:get_in_progress_review_submission).and_return(submission)
expect do
review_submitter.submit!(options)
end.to raise_error("Cannot submit for review - A review submission is already in progress")
end
it 'with empty submission' do
options = {
platform: Spaceship::ConnectAPI::Platform::IOS
}
expect(app).to receive(:get_edit_app_store_version).and_return(edit_version)
expect(review_submitter).to receive(:select_build).and_return(selected_build)
expect(selected_build).to receive(:uses_non_exempt_encryption).and_return(false)
expect(app).to receive(:get_in_progress_review_submission).and_return(nil)
expect(app).to receive(:get_ready_review_submission).and_return(submission)
expect(submission).to receive(:items).and_return([])
expect(app).not_to receive(:create_review_submission)
expect(submission).to receive(:add_app_store_version_to_review_items).with(app_store_version_id: edit_version.id)
expect(Spaceship::ConnectAPI::AppStoreVersion).to receive(:get).and_return(ready_for_review_version)
expect(submission).to receive(:submit_for_review)
review_submitter.submit!(options)
end
it 'with submission containing items' do
options = {
platform: Spaceship::ConnectAPI::Platform::IOS
}
expect(app).to receive(:get_edit_app_store_version).and_return(edit_version)
expect(review_submitter).to receive(:select_build).and_return(selected_build)
expect(selected_build).to receive(:uses_non_exempt_encryption).and_return(false)
expect(app).to receive(:get_in_progress_review_submission).and_return(nil)
expect(app).to receive(:get_ready_review_submission).and_return(submission)
expect(submission).to receive(:items).and_return([double('some item')])
expect do
review_submitter.submit!(options)
end.to raise_error("Cannot submit for review - A review submission already exists with items not managed by fastlane. Please cancel or remove items from submission for the App Store Connect website")
end
end
context 'it still tries to submit for review if the version state is not expected' do
it 'retires to get the version state at most 10 times' do
options = {
platform: Spaceship::ConnectAPI::Platform::IOS
}
expect(app).to receive(:get_edit_app_store_version).and_return(edit_version)
expect(review_submitter).to receive(:select_build).and_return(selected_build)
expect(selected_build).to receive(:uses_non_exempt_encryption).and_return(false)
expect(app).to receive(:get_in_progress_review_submission).and_return(nil)
expect(app).to receive(:get_ready_review_submission).and_return(submission)
expect(submission).to receive(:items).and_return([])
expect(app).not_to receive(:create_review_submission)
expect(submission).to receive(:add_app_store_version_to_review_items).with(app_store_version_id: edit_version.id)
allow_any_instance_of(Deliver::SubmitForReview).to receive(:sleep)
expect(Spaceship::ConnectAPI::AppStoreVersion).to receive(:get).exactly(10).times.and_return(prepare_for_submission_version)
expect(submission).to receive(:submit_for_review)
review_submitter.submit!(options)
end
end
context 'export_compliance_uses_encryption' do
it 'sets to false' do
options = {
platform: Spaceship::ConnectAPI::Platform::IOS,
submission_information: {
export_compliance_uses_encryption: false
}
}
expect(app).to receive(:get_edit_app_store_version).and_return(edit_version)
expect(review_submitter).to receive(:select_build).and_return(selected_build)
expect(selected_build).to receive(:uses_non_exempt_encryption).and_return(nil)
expect(selected_build).to receive(:update).with(attributes: { usesNonExemptEncryption: false }).and_return(selected_build)
expect(selected_build).to receive(:uses_non_exempt_encryption).and_return(false)
expect(app).to receive(:get_in_progress_review_submission).and_return(nil)
expect(app).to receive(:get_ready_review_submission).and_return(nil)
expect(app).to receive(:create_review_submission).and_return(submission)
expect(submission).to receive(:add_app_store_version_to_review_items).with(app_store_version_id: edit_version.id)
expect(Spaceship::ConnectAPI::AppStoreVersion).to receive(:get).and_return(ready_for_review_version)
expect(submission).to receive(:submit_for_review)
review_submitter.submit!(options)
end
end
context 'content_rights_contains_third_party_content' do
it 'sets to true' do
options = {
platform: Spaceship::ConnectAPI::Platform::IOS,
submission_information: {
content_rights_contains_third_party_content: true
}
}
expect(app).to receive(:get_edit_app_store_version).and_return(edit_version)
expect(review_submitter).to receive(:select_build).and_return(selected_build)
expect(selected_build).to receive(:uses_non_exempt_encryption).and_return(false)
expect(app).to receive(:update).with(attributes: {
contentRightsDeclaration: "USES_THIRD_PARTY_CONTENT"
})
expect(app).to receive(:get_in_progress_review_submission).and_return(nil)
expect(app).to receive(:get_ready_review_submission).and_return(nil)
expect(app).to receive(:create_review_submission).and_return(submission)
expect(submission).to receive(:add_app_store_version_to_review_items).with(app_store_version_id: edit_version.id)
expect(Spaceship::ConnectAPI::AppStoreVersion).to receive(:get).and_return(ready_for_review_version)
expect(submission).to receive(:submit_for_review)
review_submitter.submit!(options)
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/app_screenshot_spec.rb | deliver/spec/app_screenshot_spec.rb | require 'deliver/app_screenshot'
require 'deliver/setup'
describe Deliver::AppScreenshot do
DisplayType = Deliver::AppScreenshot::DisplayType
def screen_size_from(path)
path.match(/{([0-9]+)x([0-9]+)}/).captures.map(&:to_i)
end
before do
allow(FastImage).to receive(:size) do |path|
screen_size_from(path)
end
end
describe "#initialize" do
{
"APP_IPAD_PRO_129" => ["Screen-Name-APP_IPAD_PRO_129{2732x2048}.png", DisplayType::APP_IPAD_PRO_129],
"iPad Pro (12.9-inch) (2nd generation)" => ["Screen-Name-iPad Pro (12.9-inch) (2nd generation){2732x2048}.png", DisplayType::APP_IPAD_PRO_129],
"IPAD_PRO_3GEN_129" => ["IPAD_PRO_3GEN_129-AAABBBCCCDDD{2732x2048}.png", DisplayType::APP_IPAD_PRO_3GEN_129],
"iPad Pro (3rd generation)" => ["Screen-Name-iPad Pro (12.9-inch) (3rd generation){2732x2048}.png", DisplayType::APP_IPAD_PRO_3GEN_129],
"iPad Pro (4th generation)" => ["Screen-Name-iPad Pro (12.9-inch) (4th generation){2732x2048}.png", DisplayType::APP_IPAD_PRO_3GEN_129],
"iPad Pro (5th generation)" => ["Screen-Name-iPad Pro (12.9-inch) (5th generation){2732x2048}.png", DisplayType::APP_IPAD_PRO_3GEN_129],
"no generation info" => ["Screen-Name-iPad Pro{2732x2048}.png", DisplayType::APP_IPAD_PRO_3GEN_129]
}.each do |description, (filename, expected_type)|
context "when filename contains '#{description}'" do
it "returns #{expected_type}" do
screenshot = Deliver::AppScreenshot.new("path/to/screenshot/#{filename}", "de-DE")
expect(screenshot.display_type).to eq(expected_type)
end
end
end
end
# Ensure that screenshots correctly map based on the following:
# https://help.apple.com/app-store-connect/#/devd274dd925
describe "#calculate_display_type" do
def expect_display_type_from_file(file)
expect(Deliver::AppScreenshot.calculate_display_type(file))
end
describe "valid screen sizes" do
device_tests = {
"6.7 inch iPhone" => [
["iPhone14ProMax-Portrait{1260x2736}.jpg", DisplayType::APP_IPHONE_67],
["iPhone14ProMax-Landscape{2736x1260}.jpg", DisplayType::APP_IPHONE_67],
["iPhone14ProMax-Portrait{1290x2796}.jpg", DisplayType::APP_IPHONE_67],
["iPhone14ProMax-Landscape{2796x1290}.jpg", DisplayType::APP_IPHONE_67],
["iPhone16ProMax-Portrait{1320x2868}.jpg", DisplayType::APP_IPHONE_67],
["iPhone16ProMax-Landscape{2868x1320}.jpg", DisplayType::APP_IPHONE_67]
],
"6.5 inch iPhone" => [
["iPhoneXSMax-Portrait{1242x2688}.jpg", DisplayType::APP_IPHONE_65],
["iPhoneXSMax-Landscape{2688x1242}.jpg", DisplayType::APP_IPHONE_65],
["iPhone12ProMax-Portrait{1284x2778}.jpg", DisplayType::APP_IPHONE_65],
["iPhone12ProMax-Landscape{2778x1284}.jpg", DisplayType::APP_IPHONE_65]
],
"6.1 inch iPhone" => [
["iPhone14Pro-Portrait{1179x2556}.jpg", DisplayType::APP_IPHONE_61],
["iPhone14Pro-Landscape{2556x1179}.jpg", DisplayType::APP_IPHONE_61],
["iPhone15Pro-Portrait{1206x2622}.jpg", DisplayType::APP_IPHONE_61],
["iPhone15Pro-Landscape{2622x1206}.jpg", DisplayType::APP_IPHONE_61]
],
"5.8 inch iPhone" => [
["iPhone12-Portrait{1170x2532}.jpg", DisplayType::APP_IPHONE_58],
["iPhone12-Landscape{2532x1170}.jpg", DisplayType::APP_IPHONE_58],
["iPhoneXS-Portrait{1125x2436}.jpg", DisplayType::APP_IPHONE_58],
["iPhoneXS-Landscape{2436x1125}.jpg", DisplayType::APP_IPHONE_58],
["iPhoneX-Portrait{1080x2340}.jpg", DisplayType::APP_IPHONE_58],
["iPhoneX-Landscape{2340x1080}.jpg", DisplayType::APP_IPHONE_58]
],
"5.5 inch iPhone" => [
["iPhone8Plus-Portrait{1242x2208}.jpg", DisplayType::APP_IPHONE_55],
["iPhone8Plus-Landscape{2208x1242}.jpg", DisplayType::APP_IPHONE_55]
],
"4.7 inch iPhone" => [
["iPhone8-Portrait{750x1334}.jpg", DisplayType::APP_IPHONE_47],
["iPhone8-Landscape{1334x750}.jpg", DisplayType::APP_IPHONE_47]
],
"4 inch iPhone" => [
["iPhoneSE-Portrait{640x1136}.jpg", DisplayType::APP_IPHONE_40],
["iPhoneSE-Landscape{1136x640}.jpg", DisplayType::APP_IPHONE_40],
["iPhoneSE-Portrait-NoStatusBar{640x1096}.jpg", DisplayType::APP_IPHONE_40],
["iPhoneSE-Landscape-NoStatusBar{1136x600}.jpg", DisplayType::APP_IPHONE_40]
],
"3.5 inch iPhone" => [
["iPhone4S-Portrait{640x960}.jpg", DisplayType::APP_IPHONE_35],
["iPhone4S-Landscape{960x640}.jpg", DisplayType::APP_IPHONE_35],
["iPhone4S-Portrait-NoStatusBar{640x920}.jpg", DisplayType::APP_IPHONE_35],
["iPhone4S-Landscape-NoStatusBar{960x600}.jpg", DisplayType::APP_IPHONE_35]
],
"12.9 inch iPad (2nd gen)" => [
["iPad-Portrait-12.9-inch-(2nd generation){2048x2732}.jpg", DisplayType::APP_IPAD_PRO_129],
["iPad-Landscape-12.9-inch-(2nd generation){2732x2048}.jpg", DisplayType::APP_IPAD_PRO_129],
["APP_IPAD_PRO_129-portrait{2048x2732}.jpg", DisplayType::APP_IPAD_PRO_129],
["APP_IPAD_PRO_129-landscape{2732x2048}.jpg", DisplayType::APP_IPAD_PRO_129]
],
"13 inch iPad (3rd+ gen)" => [
["iPad-Portrait-13Inch{2048x2732}.jpg", DisplayType::APP_IPAD_PRO_3GEN_129],
["iPad-Landscape-13Inch{2732x2048}.jpg", DisplayType::APP_IPAD_PRO_3GEN_129],
["iPad-Portrait-13Inch{2064x2752}.jpg", DisplayType::APP_IPAD_PRO_3GEN_129],
["iPad-Landscape-13Inch{2752x2064}.jpg", DisplayType::APP_IPAD_PRO_3GEN_129]
],
"11 inch iPad" => [
["iPad-Portrait-11Inch{1488x2266}.jpg", DisplayType::APP_IPAD_PRO_3GEN_11],
["iPad-Landscape-11Inch{2266x1488}.jpg", DisplayType::APP_IPAD_PRO_3GEN_11],
["iPad-Portrait-11Inch{1668x2420}.jpg", DisplayType::APP_IPAD_PRO_3GEN_11],
["iPad-Landscape-11Inch{2420x1668}.jpg", DisplayType::APP_IPAD_PRO_3GEN_11],
["iPad-Portrait-11Inch{1668x2388}.jpg", DisplayType::APP_IPAD_PRO_3GEN_11],
["iPad-Landscape-11Inch{2388x1668}.jpg", DisplayType::APP_IPAD_PRO_3GEN_11],
["iPad-Portrait-11Inch{1640x2360}.jpg", DisplayType::APP_IPAD_PRO_3GEN_11],
["iPad-Landscape-11Inch{2360x1640}.jpg", DisplayType::APP_IPAD_PRO_3GEN_11]
],
"10.5 inch iPad" => [
["iPad-Portrait-10_5Inch{1668x2224}.jpg", DisplayType::APP_IPAD_105],
["iPad-Landscape-10_5Inch{2224x1668}.jpg", DisplayType::APP_IPAD_105]
],
"9.7 inch iPad" => [
["iPad-Portrait-9_7Inch-Retina{1536x2048}.jpg", DisplayType::APP_IPAD_97],
["iPad-Landscape-9_7Inch-Retina{2048x1536}.jpg", DisplayType::APP_IPAD_97],
["iPad-Portrait-9_7Inch-Retina-NoStatusBar{1536x2008}.jpg", DisplayType::APP_IPAD_97],
["iPad-Landscape-9_7Inch-Retina-NoStatusBar{2048x1496}.jpg", DisplayType::APP_IPAD_97],
["iPad-Portrait-9_7Inch-{768x1024}.jpg", DisplayType::APP_IPAD_97],
["iPad-Landscape-9_7Inch-{1024x768}.jpg", DisplayType::APP_IPAD_97],
["iPad-Portrait-9_7Inch-NoStatusBar{768x1004}.jpg", DisplayType::APP_IPAD_97],
["iPad-Landscape-9_7Inch-NoStatusBar{1024x748}.jpg", DisplayType::APP_IPAD_97]
],
"Mac" => [
["Mac{1280x800}.jpg", DisplayType::APP_DESKTOP],
["Mac{1440x900}.jpg", DisplayType::APP_DESKTOP],
["Mac{2560x1600}.jpg", DisplayType::APP_DESKTOP],
["Mac{2880x1800}.jpg", DisplayType::APP_DESKTOP]
],
"Apple TV" => [
["AppleTV{1920x1080}.jpg", DisplayType::APP_APPLE_TV],
["AppleTV-4K{3840x2160}.jpg", DisplayType::APP_APPLE_TV]
],
"Apple Vision Pro" => [
["VisionPro{3840x2160}.jpg", DisplayType::APP_APPLE_VISION_PRO],
["AppleVisionPro{3840x2160}.jpg", DisplayType::APP_APPLE_VISION_PRO],
["Apple-Vision-Pro{3840x2160}.jpg", DisplayType::APP_APPLE_VISION_PRO]
],
"Apple Watch" => [
["AppleWatch-Series3{312x390}.jpg", DisplayType::APP_WATCH_SERIES_3],
["AppleWatch-Series4{368x448}.jpg", DisplayType::APP_WATCH_SERIES_4],
["AppleWatch-Series7{396x484}.jpg", DisplayType::APP_WATCH_SERIES_7],
["AppleWatch-Ultra{410x502}.jpg", DisplayType::APP_WATCH_ULTRA]
]
}
device_tests.each do |device_name, test_cases|
it "should calculate all #{device_name} resolutions" do
test_cases.each do |filename, expected_type|
expect_display_type_from_file(filename).to eq(expected_type)
end
end
end
end
describe "valid iMessage app display types" do
imessage_tests = {
"6.7 inch iPhone" => [
["iMessage/en-GB/iPhone14ProMax-Portrait{1290x2796}.jpg", DisplayType::IMESSAGE_APP_IPHONE_67],
["iMessage/en-GB/iPhone14ProMax-Landscape{2796x1290}.jpg", DisplayType::IMESSAGE_APP_IPHONE_67]
],
"6.5 inch iPhone" => [
["iMessage/en-GB/iPhoneXSMax-Portrait{1242x2688}.jpg", DisplayType::IMESSAGE_APP_IPHONE_65],
["iMessage/en-GB/iPhoneXSMax-Landscape{2688x1242}.jpg", DisplayType::IMESSAGE_APP_IPHONE_65],
["iMessage/en-GB/iPhone12ProMax-Portrait{1284x2778}.jpg", DisplayType::IMESSAGE_APP_IPHONE_65],
["iMessage/en-GB/iPhone12ProMax-Landscape{2778x1284}.jpg", DisplayType::IMESSAGE_APP_IPHONE_65]
],
"6.1 inch iPhone" => [
["iMessage/en-GB/iPhone14Pro-Portrait{1179x2556}.jpg", DisplayType::IMESSAGE_APP_IPHONE_61],
["iMessage/en-GB/iPhone14Pro-Landscape{2556x1179}.jpg", DisplayType::IMESSAGE_APP_IPHONE_61]
],
"5.8 inch iPhone" => [
["iMessage/en-GB/iPhoneXS-Portrait{1125x2436}.jpg", DisplayType::IMESSAGE_APP_IPHONE_58],
["iMessage/en-GB/iPhoneXS-Landscape{2436x1125}.jpg", DisplayType::IMESSAGE_APP_IPHONE_58]
],
"5.5 inch iPhone" => [
["iMessage/en-GB/iPhone8Plus-Portrait{1242x2208}.jpg", DisplayType::IMESSAGE_APP_IPHONE_55],
["iMessage/en-GB/iPhone8Plus-Landscape{2208x1242}.jpg", DisplayType::IMESSAGE_APP_IPHONE_55]
],
"4.7 inch iPhone" => [
["iMessage/en-GB/iPhone8-Portrait{750x1334}.jpg", DisplayType::IMESSAGE_APP_IPHONE_47],
["iMessage/en-GB/iPhone8-Landscape{1334x750}.jpg", DisplayType::IMESSAGE_APP_IPHONE_47]
],
"4 inch iPhone" => [
["iMessage/en-GB/iPhoneSE-Portrait{640x1136}.jpg", DisplayType::IMESSAGE_APP_IPHONE_40],
["iMessage/en-GB/iPhoneSE-Landscape{1136x640}.jpg", DisplayType::IMESSAGE_APP_IPHONE_40],
["iMessage/en-GB/iPhoneSE-Portrait-NoStatusBar{640x1096}.jpg", DisplayType::IMESSAGE_APP_IPHONE_40],
["iMessage/en-GB/iPhoneSE-Landscape-NoStatusBar{1136x600}.jpg", DisplayType::IMESSAGE_APP_IPHONE_40]
],
"12.9 inch iPad (2nd gen)" => [
["iMessage/en-GB/iPad-Portrait-12.9-inch-(2nd generation){2048x2732}.jpg", DisplayType::IMESSAGE_APP_IPAD_PRO_129],
["iMessage/en-GB/iPad-Landscape-12.9-inch-(2nd generation){2732x2048}.jpg", DisplayType::IMESSAGE_APP_IPAD_PRO_129]
],
"13 inch iPad (3rd+ gen)" => [
["iMessage/en-GB/iPad-Portrait-13Inch{2048x2732}.jpg", DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_129],
["iMessage/en-GB/iPad-Landscape-13Inch{2732x2048}.jpg", DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_129]
],
"11 inch iPad" => [
["iMessage/en-GB/iPad-Portrait-11Inch{1668x2388}.jpg", DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_11],
["iMessage/en-GB/iPad-Landscape-11Inch{2388x1668}.jpg", DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_11]
],
"10.5 inch iPad" => [
["iMessage/en-GB/iPad-Portrait-10_5Inch{1668x2224}.jpg", DisplayType::IMESSAGE_APP_IPAD_105],
["iMessage/en-GB/iPad-Landscape-10_5Inch{2224x1668}.jpg", DisplayType::IMESSAGE_APP_IPAD_105]
],
"9.7 inch iPad" => [
["iMessage/en-GB/iPad-Portrait-9_7Inch-Retina{1536x2048}.jpg", DisplayType::IMESSAGE_APP_IPAD_97],
["iMessage/en-GB/iPad-Landscape-9_7Inch-Retina{2048x1536}.jpg", DisplayType::IMESSAGE_APP_IPAD_97],
["iMessage/en-GB/iPad-Portrait-9_7Inch-Retina-NoStatusBar{1536x2008}.jpg", DisplayType::IMESSAGE_APP_IPAD_97],
["iMessage/en-GB/iPad-Landscape-9_7Inch-Retina-NoStatusBar{2048x1496}.jpg", DisplayType::IMESSAGE_APP_IPAD_97],
["iMessage/en-GB/iPad-Portrait-9_7Inch-{768x1024}.jpg", DisplayType::IMESSAGE_APP_IPAD_97],
["iMessage/en-GB/iPad-Landscape-9_7Inch-{1024x768}.jpg", DisplayType::IMESSAGE_APP_IPAD_97],
["iMessage/en-GB/iPad-Portrait-9_7Inch-NoStatusBar{768x1004}.jpg", DisplayType::IMESSAGE_APP_IPAD_97],
["iMessage/en-GB/iPad-Landscape-9_7Inch-NoStatusBar{1024x748}.jpg", DisplayType::IMESSAGE_APP_IPAD_97]
]
}
imessage_tests.each do |device_name, test_cases|
it "should calculate all #{device_name} resolutions" do
test_cases.each do |filename, expected_type|
expect_display_type_from_file(filename).to eq(expected_type)
end
end
end
end
describe "conflict resolution" do
it "should resolve iPad Pro 2nd gen vs 3rd+ gen correctly" do
expect_display_type_from_file("iPad-Portrait-APP_IPAD_PRO_129{2048x2732}.jpg").to eq(DisplayType::APP_IPAD_PRO_129)
expect_display_type_from_file("iPad-Portrait-app_ipad_pro_129{2048x2732}.jpg").to eq(DisplayType::APP_IPAD_PRO_129)
expect_display_type_from_file("iPad-Portrait-12.9-inch-(2ND GENERATION){2048x2732}.jpg").to eq(DisplayType::APP_IPAD_PRO_129)
expect_display_type_from_file("iPad-Portrait-12.9-inch{2048x2732}.jpg").to eq(DisplayType::APP_IPAD_PRO_3GEN_129)
expect_display_type_from_file("iPad-Portrait-generic{2048x2732}.jpg").to eq(DisplayType::APP_IPAD_PRO_3GEN_129)
end
it "should resolve Apple TV vs Vision Pro correctly" do
expect_display_type_from_file("VisionPro{3840x2160}.jpg").to eq(DisplayType::APP_APPLE_VISION_PRO)
expect_display_type_from_file("vision-pro{3840x2160}.jpg").to eq(DisplayType::APP_APPLE_VISION_PRO)
expect_display_type_from_file("VISION-PRO{3840x2160}.jpg").to eq(DisplayType::APP_APPLE_VISION_PRO)
expect_display_type_from_file("AppleTV{3840x2160}.jpg").to eq(DisplayType::APP_APPLE_TV)
expect_display_type_from_file("tv-4k{3840x2160}.jpg").to eq(DisplayType::APP_APPLE_TV)
expect_display_type_from_file("generic-4k{3840x2160}.jpg").to eq(DisplayType::APP_APPLE_TV)
end
end
describe "invalid display types" do
def expect_invalid_display_type_from_file(file)
expect(Deliver::AppScreenshot.calculate_display_type(file)).to be_nil
end
it "shouldn't allow native resolution 5.5 inch iPhone screenshots" do
expect_invalid_display_type_from_file("iPhone8Plus-NativeResolution{1080x1920}.jpg")
expect_invalid_display_type_from_file("iMessage/en-GB/iPhone8Plus-NativeResolution{1080x1920}.jpg")
end
it "shouldn't calculate portrait Apple TV resolutions" do
expect_invalid_display_type_from_file("appleTV/en-GB/AppleTV-Portrait{1080x1920}.jpg")
expect_invalid_display_type_from_file("appleTV/en-GB/AppleTV-Portrait{2160x3840}.jpg")
end
it "shouldn't calculate modern devices excluding status bars" do
expect_invalid_display_type_from_file("iPhoneXSMax-Portrait-NoStatusBar{1242x2556}.jpg")
expect_invalid_display_type_from_file("iPhoneXS-Portrait-NoStatusBar{1125x2304}.jpg")
expect_invalid_display_type_from_file("iPhone8Plus-Portrait-NoStatusBar{1242x2148}.jpg")
expect_invalid_display_type_from_file("iPhone8-Portrait-NoStatusBar{750x1294}.jpg")
expect_invalid_display_type_from_file("iPad-Portrait-12_9Inch-NoStatusBar{2048x2692}.jpg")
expect_invalid_display_type_from_file("iPad-Portrait-11Inch{1668x2348}.jpg")
expect_invalid_display_type_from_file("iPad-Portrait-10_5Inch{1668x2184}.jpg")
end
it "shouldn't allow non 16:10 resolutions for Mac" do
expect_invalid_display_type_from_file("Mac-Portrait{800x1280}.jpg")
expect_invalid_display_type_from_file("Mac-Portrait{900x1440}.jpg")
expect_invalid_display_type_from_file("Mac-Portrait{1600x2560}.jpg")
expect_invalid_display_type_from_file("Mac-Portrait{1800x2880}.jpg")
end
end
end
describe "#is_messages?" do
it "should return true when contained in the iMessage directory" do
files = [
"screenshots/iMessage/en-GB/iPhoneXSMax-Portrait{1242x2688}.png",
"screenshots/iMessage/en-GB/iPhoneXS-Portrait{1125x2436}.png",
"screenshots/iMessage/en-GB/iPhone8Plus-Landscape{2208x1242}.png",
"screenshots/iMessage/en-GB/iPhone8-Landscape{1334x750}.png",
"screenshots/iMessage/en-GB/iPhoneSE-Portrait-NoStatusBar{640x1096}.png",
"screenshots/iMessage/en-GB/iPad-Portrait-12_9Inch{2048x2732}.png",
"screenshots/iMessage/en-GB/iPad-Portrait-11Inch{1668x2388}.png",
"screenshots/iMessage/en-GB/iPad-Landscape-10_5Inch{2224x1668}.png",
"screenshots/iMessage/en-GB/iPad-Portrait-9_7Inch-NoStatusBar{768x1004}.png"
]
files.each do |file|
screenshot = Deliver::AppScreenshot.new(file, 'en-GB')
expect({ file: file, result: screenshot.is_messages? }).to eq({ file: file, result: true })
end
end
it "should return false when not contained in the iMessage directory" do
files = [
"screenshots/en-GB/iPhoneXSMax-Portrait{1242x2688}.png",
"screenshots/en-GB/iPhoneXS-Portrait{1125x2436}.png",
"screenshots/en-GB/iPhone8Plus-Landscape{2208x1242}.png",
"screenshots/en-GB/iPhone8-Landscape{1334x750}.png",
"screenshots/en-GB/iPhoneSE-Portrait-NoStatusBar{640x1096}.png",
"screenshots/en-GB/iPad-Portrait-12_9Inch{2048x2732}.png",
"screenshots/en-GB/iPad-Portrait-11Inch{1668x2388}.png",
"screenshots/en-GB/iPad-Landscape-10_5Inch{2224x1668}.png",
"screenshots/en-GB/iPad-Portrait-9_7Inch-NoStatusBar{768x1004}.png",
"screenshots/en-GB/Mac{1440x900}.png",
"screenshots/en-GB/AppleWatch-Series4{368x448}.png",
"screenshots/appleTV/en-GB/AppleTV-4K{3840x2160}.png"
]
files.each do |file|
screenshot = Deliver::AppScreenshot.new(file, 'en-GB')
expect({ file: file, result: screenshot.is_messages? }).to eq({ file: file, result: false })
end
end
end
describe "#display_type" do
def app_screenshot_with(display_type, path = '', language = 'en-US')
allow(Deliver::AppScreenshot).to receive(:calculate_display_type).and_return(display_type)
Deliver::AppScreenshot.new(path, language)
end
it "should return APP_IPHONE_35 for 3.5 inch displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPHONE_35).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPHONE_35)
end
it "should return appropriate display types for 4 inch displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPHONE_40).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPHONE_40)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_40).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_40)
end
it "should return appropriate display types for 4.7 inch displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPHONE_47).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPHONE_47)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_47).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_47)
end
it "should return appropriate display types for 5.5 inch displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPHONE_55).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPHONE_55)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_55).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_55)
end
it "should return appropriate display types for 6.1 inch displays (iPhone 14)" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPHONE_61).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPHONE_61)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_61).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_61)
end
it "should return appropriate display types for 6.7 inch displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPHONE_67).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPHONE_67)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_67).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_67)
end
it "should return appropriate display types for 6.5 inch displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPHONE_65).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPHONE_65)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_65).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPHONE_65)
end
it "should return appropriate display types for 9.7 inch iPad displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPAD_97).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPAD_97)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPAD_97).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPAD_97)
end
it "should return appropriate display types for 10.5 inch iPad displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPAD_105).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPAD_105)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPAD_105).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPAD_105)
end
it "should return appropriate display types for 11 inch iPad displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPAD_PRO_3GEN_11).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPAD_PRO_3GEN_11)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_11).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_11)
end
it "should return appropriate display types for 12.9 inch iPad displays" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_IPAD_PRO_129).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPAD_PRO_129)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPAD_PRO_129).display_type).to eq(Deliver::AppScreenshot::DisplayType::IMESSAGE_APP_IPAD_PRO_129)
end
it "should return watch display types" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_WATCH_SERIES_3).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_WATCH_SERIES_3)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_WATCH_SERIES_4).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_WATCH_SERIES_4)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_WATCH_SERIES_7).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_WATCH_SERIES_7)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_WATCH_ULTRA).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_WATCH_ULTRA)
end
it "should return other device display types" do
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_APPLE_TV).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_APPLE_TV)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_APPLE_VISION_PRO).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_APPLE_VISION_PRO)
expect(app_screenshot_with(Deliver::AppScreenshot::DisplayType::APP_DESKTOP).display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_DESKTOP)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/loader_spec.rb | deliver/spec/loader_spec.rb | require 'deliver/loader'
require 'fakefs/spec_helpers'
describe Deliver::Loader do
include(FakeFS::SpecHelpers)
describe Deliver::Loader::LanguageFolder do
let(:root) { '/some/root' }
before { FileUtils.mkdir_p(root) }
def directory_path(name)
path = File.join(root, name)
FileUtils.mkdir_p(path)
path
end
describe '#new' do
it 'should fail to initialize an instance unless given a directory path' do
random_path = File.join(root, 'random_file')
expect { described_class.new(random_path) }.to raise_error(ArgumentError)
path = directory_path('directory')
expect { described_class.new(path) }.not_to raise_error
end
end
describe '#language' do
let(:language) { FastlaneCore::Languages::ALL_LANGUAGES.sample }
it 'should be same as directory name being language name' do
expect(described_class.new(directory_path(language)).language).to eq(language)
end
it 'should be same as language name normalized even when case is different' do
expect(described_class.new(directory_path(language.upcase)).language).to eq(language)
end
end
describe '#valid?' do
it 'should be valid for allowed directory names' do
(FastlaneCore::Languages::ALL_LANGUAGES + Deliver::Loader::SPECIAL_DIR_NAMES).each do |name|
expect(described_class.new(directory_path(name)).valid?).to be(true)
end
expect(described_class.new(directory_path('random')).valid?).to be(false)
end
end
describe '#expandable?' do
it 'should be true for specific directories' do
Deliver::Loader::EXPANDABLE_DIR_NAMES.each do |name|
expect(described_class.new(directory_path(name)).expandable?).to be(true)
end
expect(described_class.new(directory_path(FastlaneCore::Languages::ALL_LANGUAGES.sample)).expandable?).to be(false)
end
end
describe '#skip?' do
it 'should be true when exceptional directories' do
Deliver::Loader::EXCEPTION_DIRECTORIES.each do |name|
expect(described_class.new(directory_path(name)).skip?).to be(true)
end
expect(described_class.new(directory_path(FastlaneCore::Languages::ALL_LANGUAGES.sample)).skip?).to be(false)
expect(described_class.new(directory_path(Deliver::Loader::SPECIAL_DIR_NAMES.sample)).skip?).to be(false)
end
end
end
describe '#language_folders' do
before do
@languages = FastlaneCore::Languages::ALL_LANGUAGES
@root = '/some/root'
FileUtils.mkdir_p(@root)
# Add a file with a lang code
File.open(File.join(@root, @languages.first), 'w') { |f| f << 'touch' }
# Create dirs for all the other codes
@languages[1..-1].each.with_index do |lang, index|
FileUtils.mkdir(File.join(@root, (index.even? ? lang : lang.downcase)))
end
end
it 'only returns directories in the specified directory' do
@folders = Deliver::Loader.language_folders(@root, false)
expect(@folders.size).not_to(eq(0))
end
it 'only returns directories regardless of case' do
FileUtils.mkdir(File.join(@root, 'unrelated-dir'))
@folders = Deliver::Loader.language_folders(@root, true)
expect(@folders.size).not_to(eq(0))
expected_languages = @languages[1..-1].map(&:downcase).sort
actual_languages = @folders.map(&:basename).map(&:downcase).sort
expect(actual_languages).to eq(expected_languages)
end
it 'raises error when a directory name contains an unsupported directory name' do
allowed_directory_names = (@languages + Deliver::Loader::SPECIAL_DIR_NAMES)
FileUtils.mkdir(File.join(@root, 'unrelated-dir'))
expect do
@folders = Deliver::Loader.language_folders(@root, false)
end.to raise_error(FastlaneCore::Interface::FastlaneError, "Unsupported directory name(s) for screenshots/metadata in '#{@root}': unrelated-dir" \
"\nValid directory names are: #{allowed_directory_names}" \
"\n\nEnable 'ignore_language_directory_validation' to prevent this validation from happening")
end
it 'allows but ignores the special "fonts" directory used by frameit"' do
FileUtils.mkdir(File.join(@root, 'fonts'))
@folders = Deliver::Loader.language_folders(@root, false)
basenames = @folders.map(&:basename)
expect(basenames.include?('fonts')).to eq(false)
end
it 'should expand specific directories when they have sub language directories' do
Deliver::Loader::SPECIAL_DIR_NAMES.each do |dirname|
FileUtils.mkdir(File.join(@root, dirname))
FileUtils.mkdir(File.join(@root, dirname, @languages.first))
end
folders_not_expanded = Deliver::Loader.language_folders(@root, true, false)
folders_expanded = Deliver::Loader.language_folders(@root, true, true)
expect(folders_not_expanded.any?(&:expandable?)).to be(true)
expect(folders_expanded.any?(&:expandable?)).to be(false)
expanded_special_folders = folders_expanded.select do |folder|
folder.path.include?(Deliver::Loader::APPLE_TV_DIR_NAME) || folder.path.include?(Deliver::Loader::IMESSAGE_DIR_NAME)
end
# all expanded folder should have its language
expect(expanded_special_folders.map(&:language).any?(&:nil?)).to be(false)
end
end
describe "#load_app_screenshots" do
include(FakeFS::SpecHelpers)
def add_screenshot(file)
FileUtils.mkdir_p(File.dirname(file))
File.open(file, 'w') { |f| f << 'touch' }
end
def collect_screenshots_from_dir(dir)
Deliver::Loader.load_app_screenshots(dir, false)
end
before do
FakeFS::FileSystem.clone(File.join(Spaceship::ROOT, "lib", "assets", "displayFamilies.json"))
allow(FastImage).to receive(:size) do |path|
path.match(/{([0-9]+)x([0-9]+)}/).captures.map(&:to_i)
end
allow(FastImage).to receive(:type) do |path|
# work out valid format symbol
found = Deliver::AppScreenshotValidator::ALLOWED_SCREENSHOT_FILE_EXTENSION.find do |_, extensions|
extensions.include?(File.extname(path).delete('.'))
end
found.first if found
end
end
it "should not find any screenshots when the directory is empty" do
screenshots = collect_screenshots_from_dir("/Screenshots")
expect(screenshots.count).to eq(0)
end
it "should find screenshot when present in the directory" do
add_screenshot("/Screenshots/en-GB/iPhone8-01First{750x1334}.jpg")
screenshots = collect_screenshots_from_dir("/Screenshots/")
expect(screenshots.count).to eq(1)
expect(screenshots.first.display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_IPHONE_47)
end
it "should find different languages" do
add_screenshot("/Screenshots/en-GB/iPhone8-01First{750x1334}.jpg")
add_screenshot("/Screenshots/fr-FR/iPhone8-01First{750x1334}.jpg")
screenshots = collect_screenshots_from_dir("/Screenshots")
expect(screenshots.count).to eq(2)
expect(screenshots.group_by(&:language).keys).to include("en-GB", "fr-FR")
end
it "should not collect regular screenshots if framed varieties exist" do
add_screenshot("/Screenshots/en-GB/iPhone8-01First{750x1334}.jpg")
add_screenshot("/Screenshots/en-GB/iPhone8-01First{750x1334}_framed.jpg")
screenshots = collect_screenshots_from_dir("/Screenshots/")
expect(screenshots.count).to eq(1)
expect(screenshots.first.path).to eq("/Screenshots/en-GB/iPhone8-01First{750x1334}_framed.jpg")
end
it "should collect Apple Watch screenshots" do
add_screenshot("/Screenshots/en-GB/AppleWatch-01First{368x448}.jpg")
screenshots = collect_screenshots_from_dir("/Screenshots/")
expect(screenshots.count).to eq(1)
end
it "should continue to collect Apple Watch screenshots even when framed iPhone screenshots exist" do
add_screenshot("/Screenshots/en-GB/AppleWatch-01First{368x448}.jpg")
add_screenshot("/Screenshots/en-GB/iPhone8-01First{750x1334}.jpg")
add_screenshot("/Screenshots/en-GB/iPhone8-01First{750x1334}_framed.jpg")
screenshots = collect_screenshots_from_dir("/Screenshots/")
expect(screenshots.count).to eq(2)
expect(screenshots.group_by(&:display_type).keys).to include(Deliver::AppScreenshot::DisplayType::APP_WATCH_SERIES_4, Deliver::AppScreenshot::DisplayType::APP_IPHONE_47)
end
it "should support special appleTV directory" do
add_screenshot("/Screenshots/appleTV/en-GB/01First{3840x2160}.jpg")
screenshots = collect_screenshots_from_dir("/Screenshots/")
expect(screenshots.count).to eq(1)
expect(screenshots.first.display_type).to eq(Deliver::AppScreenshot::DisplayType::APP_APPLE_TV)
end
it "should detect iMessage screenshots based on the directory they are contained within" do
add_screenshot("/Screenshots/iMessage/en-GB/iPhone8-01First{750x1334}.jpg")
screenshots = collect_screenshots_from_dir("/Screenshots/")
expect(screenshots.count).to eq(1)
expect(screenshots.first.is_messages?).to be_truthy
end
it "should raise an error if unsupported screenshot sizes are in iMessage directory" do
add_screenshot("/Screenshots/iMessage/en-GB/AppleTV-01First{3840x2160}.jpg")
expect do
collect_screenshots_from_dir("/Screenshots/")
end.to raise_error(FastlaneCore::Interface::FastlaneError, /Canceled uploading screenshot/)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/app_screenshot_validator_spec.rb | deliver/spec/app_screenshot_validator_spec.rb | require 'deliver/app_screenshot'
require 'deliver/setup'
describe Deliver::AppScreenshotValidator do
DisplayType = Deliver::AppScreenshot::DisplayType
Error = Deliver::AppScreenshotValidator::ValidationError
def app_screenshot_with(display_type, format = :png, path = 'image.png', language = 'en-US')
allow(Deliver::AppScreenshot).to receive(:calculate_display_type).and_return(display_type)
allow(FastImage).to receive(:type).and_return(format)
Deliver::AppScreenshot.new(path, language)
end
describe '.validate' do
def expect_errors_to_include(screenshot, *error_types)
errors_to_collect = []
described_class.validate(screenshot, errors_to_collect)
expect(errors_to_collect).to satisfy("be the same as \"#{error_types.join(', ')}\"") do |errors|
errors.all? { |error| error_types.any?(error.type) }
end
expect(errors_to_collect).not_to be_empty
end
def expect_no_error(screenshot)
expect(described_class.validate(screenshot, [])).to be(true)
end
it 'should return true for valid screenshot' do
expect_no_error(app_screenshot_with(DisplayType::APP_IPHONE_65, :png, 'image.png'))
expect_no_error(app_screenshot_with(DisplayType::APP_IPHONE_65, :jpeg, 'image.jpeg'))
expect_no_error(app_screenshot_with(DisplayType::APP_IPHONE_67, :png, 'image.png'))
expect_no_error(app_screenshot_with(DisplayType::APP_IPHONE_67, :jpeg, 'image.jpeg'))
end
it 'should detect invalid size screenshot' do
expect_errors_to_include(app_screenshot_with(nil, :png, 'image.png'), Error::INVALID_SCREEN_SIZE)
end
it 'should detect invalid file extension' do
expect_errors_to_include(app_screenshot_with(DisplayType::APP_IPHONE_65, :gif, 'image.gif'), Error::INVALID_FILE_EXTENSION)
expect_errors_to_include(app_screenshot_with(DisplayType::APP_IPHONE_65, :png, 'image.gif'), Error::INVALID_FILE_EXTENSION, Error::FILE_EXTENSION_MISMATCH)
end
it 'should detect file extension mismatch' do
expect_errors_to_include(app_screenshot_with(DisplayType::APP_IPHONE_65, :jpeg, 'image.png'), Error::FILE_EXTENSION_MISMATCH)
expect_errors_to_include(app_screenshot_with(DisplayType::APP_IPHONE_65, :png, 'image.jpeg'), Error::FILE_EXTENSION_MISMATCH)
end
end
describe '.validate_file_extension_and_format' do
it 'should provide ideal filename to match content format' do
errors_found = []
described_class.validate(app_screenshot_with(DisplayType::APP_IPHONE_65, :png, 'image.jpeg'), errors_found)
error = errors_found.find { |e| e.type == Error::FILE_EXTENSION_MISMATCH }
expect(error.debug_info).to match(/image\.png/)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/app_screenshot_iterator_spec.rb | deliver/spec/app_screenshot_iterator_spec.rb | require 'deliver/app_screenshot_iterator'
require 'spaceship/connect_api/models/app_screenshot_set'
describe Deliver::AppScreenshotIterator do
describe "#each_app_screenshot_set" do
context 'when screenshot is empty' do
it 'should iterates nothing' do
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [])
# Test the result with enumerator returned
expect(described_class.new([localization]).each_app_screenshot_set.to_a).to be_empty
end
end
context 'when a localization has an app_screenshot_set' do
it 'should iterates app_screenshot_set with corresponding localization' do
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet')
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [app_screenshot_set])
expect(described_class.new([localization]).each_app_screenshot_set.to_a).to eq([[localization, app_screenshot_set]])
end
end
context 'when localizations have multiple app_screenshot_sets' do
it 'should iterates app_screenshot_set with corresponding localization' do
app_screenshot_set1 = double('Spaceship::ConnectAPI::AppScreenshotSet')
app_screenshot_set2 = double('Spaceship::ConnectAPI::AppScreenshotSet')
app_screenshot_set3 = double('Spaceship::ConnectAPI::AppScreenshotSet')
app_screenshot_set4 = double('Spaceship::ConnectAPI::AppScreenshotSet')
localization1 = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [app_screenshot_set1, app_screenshot_set2])
localization2 = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [app_screenshot_set3, app_screenshot_set4])
expect(described_class.new([localization1, localization2]).each_app_screenshot_set.to_a)
.to eq([[localization1, app_screenshot_set1], [localization1, app_screenshot_set2], [localization2, app_screenshot_set3], [localization2, app_screenshot_set4]])
end
end
end
describe "#each_app_screenshot" do
context 'when screenshot is empty' do
it 'should iterates nothing' do
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [])
expect(described_class.new([localization]).each_app_screenshot.to_a).to be_empty
end
end
context 'when a localization has an app_screenshot_set' do
it 'should iterates app_screenshot_set with corresponding localization' do
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet', app_screenshots: [])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [app_screenshot_set])
expect(described_class.new([localization]).each_app_screenshot.to_a).to be_empty
end
end
context 'when localizations have multiple app_screenshot_sets which have an app_screenshot' do
it 'should iterates app_screenshot with corresponding localization and app_screenshot_set' do
app_screenshot1 = double('Spaceship::ConnectAPI::AppScreenshot')
app_screenshot2 = double('Spaceship::ConnectAPI::AppScreenshot')
app_screenshot3 = double('Spaceship::ConnectAPI::AppScreenshot')
app_screenshot4 = double('Spaceship::ConnectAPI::AppScreenshot')
app_screenshot_set1 = double('Spaceship::ConnectAPI::AppScreenshotSet', app_screenshots: [app_screenshot1])
app_screenshot_set2 = double('Spaceship::ConnectAPI::AppScreenshotSet', app_screenshots: [app_screenshot2])
app_screenshot_set3 = double('Spaceship::ConnectAPI::AppScreenshotSet', app_screenshots: [app_screenshot3])
app_screenshot_set4 = double('Spaceship::ConnectAPI::AppScreenshotSet', app_screenshots: [app_screenshot4])
localization1 = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [app_screenshot_set1, app_screenshot_set2])
localization2 = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [app_screenshot_set3, app_screenshot_set4])
actual = described_class.new([localization1, localization2]).each_app_screenshot.to_a
expect(actual).to eq([[localization1, app_screenshot_set1, app_screenshot1], [localization1, app_screenshot_set2, app_screenshot2],
[localization2, app_screenshot_set3, app_screenshot3], [localization2, app_screenshot_set4, app_screenshot4]])
end
end
end
describe '#each_local_screenshot' do
context 'when screenshot is empty' do
it 'should iterates nothing' do
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [], locale: ['en-US'])
screenshots_per_language = { 'en-US' => [] }
expect(described_class.new([localization]).each_local_screenshot(screenshots_per_language).to_a).to be_empty
end
end
context 'when locale doesn\'t match the one for given local screenshots' do
it 'should iterates nothing' do
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization', get_app_screenshot_sets: [], locale: ['fr-FR'])
screenshots_per_language = { 'en-US' => [] }
expect(described_class.new([localization]).each_local_screenshot(screenshots_per_language).to_a).to be_empty
end
end
context 'when a localization has an app_screenshot_set' do
it 'should iterates app_screenshot_set with corresponding localization' do
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
app_screenshots: [],
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
get_app_screenshot_sets: [app_screenshot_set],
locale: 'en-US')
screenshots_per_language = { 'en-US' => [] }
expect(described_class.new([localization]).each_local_screenshot(screenshots_per_language).to_a).to be_empty
end
end
context 'when a localization does not have app_screenshot_set yet (happens with new apps)' do
it 'should iterates app_screenshot_set with corresponding localization' do
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
app_screenshots: [],
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
get_app_screenshot_sets: [],
locale: 'en-US')
screenshot = double('Deliver::AppScreenshot', display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => [screenshot] }
expect(localization).to receive(:create_app_screenshot_set)
.with(attributes: { screenshotDisplayType: screenshot.display_type })
.and_return(app_screenshot_set)
actual = described_class.new([localization]).each_local_screenshot(screenshots_per_language).to_a
expect(actual).to eq([[localization, app_screenshot_set, screenshot, 0]])
end
end
context 'when local screenshots are multiple within an app_screenshot_set' do
it 'should give index incremented on each' do
app_screenshot_set1 = double('Spaceship::ConnectAPI::AppScreenshotSet',
app_screenshots: [],
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
app_screenshot_set2 = double('Spaceship::ConnectAPI::AppScreenshotSet',
app_screenshots: [],
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
localization1 = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
get_app_screenshot_sets: [app_screenshot_set1],
locale: 'en-US')
localization2 = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
get_app_screenshot_sets: [app_screenshot_set2],
locale: 'fr-FR')
screenshot1 = double('Deliver::AppScreenshot', display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshot2 = double('Deliver::AppScreenshot', display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshot3 = double('Deliver::AppScreenshot', display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshot4 = double('Deliver::AppScreenshot', display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => [screenshot1, screenshot2], 'fr-FR' => [screenshot3, screenshot4] }
actual = described_class.new([localization1, localization2]).each_local_screenshot(screenshots_per_language).to_a
expect(actual).to eq([[localization1, app_screenshot_set1, screenshot1, 0],
[localization1, app_screenshot_set1, screenshot2, 1],
[localization2, app_screenshot_set2, screenshot3, 0],
[localization2, app_screenshot_set2, screenshot4, 1]])
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/html_generator_spec.rb | deliver/spec/html_generator_spec.rb | require 'deliver/html_generator'
require 'tmpdir'
describe Deliver::HtmlGenerator do
let(:generator) { Deliver::HtmlGenerator.new }
describe :render do
let(:screenshots) { [] }
context 'minimal configuration' do
let(:options) do
{
name: { 'en-US' => 'Fastlane Demo' },
description: { 'en-US' => 'Demo description' }
}
end
it 'renders HTML' do
expect(render(options, screenshots)).to match(/<html>/)
end
end
context 'with keywords' do
let(:options) do
{
name: { 'en-US' => 'Fastlane Demo' },
description: { 'en-US' => 'Demo description' },
keywords: { 'en-US' => 'Some, key, words' }
}
end
it 'renders HTML' do
capture = render(options, screenshots)
expect(capture).to match(/<html>/)
expect(capture).to include('<li>Some</li>')
expect(capture).to include('<li>key</li>')
expect(capture).to include('<li>words</li>')
end
end
context 'with an app icon' do
let(:options) do
{
name: { 'en-US' => 'Fastlane Demo' },
description: { 'en-US' => 'Demo description' },
app_icon: 'fastlane/metadata/app_icon.png'
}
end
it 'renders HTML' do
capture = render(options, screenshots)
expect(capture).to match(/<html>/)
expect(capture).to include('app_icon.png')
end
end
private
def render(options, screenshots)
Dir.mktmpdir do |dir|
path = generator.render(options, screenshots, dir)
return File.read(path)
end
end
end
describe :split_keywords do
context 'only commas' do
let(:keywords) { 'One,Two, Three, Four Token,' }
it 'splits correctly' do
expected = ['One', 'Two', 'Three', 'Four Token']
expect(generator.split_keywords(keywords)).to eq(expected)
end
end
context 'only newlines' do
let(:keywords) { "One\nTwo\r\nThree\nFour Token\n" }
it 'splits correctly' do
expected = ['One', 'Two', 'Three', 'Four Token']
expect(generator.split_keywords(keywords)).to eq(expected)
end
end
context 'mixed' do
let(:keywords) { "One,Two, Three, Four Token,Or\nNewlines\r\nEverywhere" }
it 'splits correctly' do
expected = [
'One',
'Two',
'Three',
'Four Token',
'Or',
'Newlines',
'Everywhere'
]
expect(generator.split_keywords(keywords)).to eq(expected)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/upload_metadata_spec.rb | deliver/spec/upload_metadata_spec.rb | require 'deliver/upload_metadata'
require 'tempfile'
describe Deliver::UploadMetadata do
let(:tmpdir) { Dir.mktmpdir }
describe '#load_from_filesystem' do
context 'with review information' do
let(:options) { { metadata_path: tmpdir, app_review_information: app_review_information } }
let(:uploader) { Deliver::UploadMetadata.new(options) }
def create_metadata(path, text)
File.open(File.join(path), 'w') do |f|
f.write(text)
end
end
before do
base_dir = FileUtils.mkdir_p(File.join(tmpdir, 'review_information'))
{
first_name: 'Alice',
last_name: 'Smith',
phone_number: '+819012345678',
email_address: 'deliver@example.com',
demo_user: 'user',
demo_password: 'password',
notes: 'This is a note from file'
}.each do |prefix, text|
create_metadata(File.join(base_dir, "#{prefix}.txt"), text)
end
end
context 'without app_review_information' do
let(:app_review_information) { nil }
it 'can load review information from file' do
uploader.load_from_filesystem
expect(options[:app_review_information][:first_name]).to eql('Alice')
expect(options[:app_review_information][:last_name]).to eql('Smith')
expect(options[:app_review_information][:phone_number]).to eql('+819012345678')
expect(options[:app_review_information][:email_address]).to eql('deliver@example.com')
expect(options[:app_review_information][:demo_user]).to eql('user')
expect(options[:app_review_information][:demo_password]).to eql('password')
expect(options[:app_review_information][:notes]).to eql('This is a note from file')
end
end
context 'with app_review_information' do
let(:app_review_information) { { notes: 'This is a note from option' } }
it 'values will be masked by the in options' do
uploader.load_from_filesystem
expect(options[:app_review_information][:first_name]).to eql('Alice')
expect(options[:app_review_information][:last_name]).to eql('Smith')
expect(options[:app_review_information][:phone_number]).to eql('+819012345678')
expect(options[:app_review_information][:email_address]).to eql('deliver@example.com')
expect(options[:app_review_information][:demo_user]).to eql('user')
expect(options[:app_review_information][:demo_password]).to eql('password')
expect(options[:app_review_information][:notes]).to eql('This is a note from option')
end
end
after do
FileUtils.remove_entry_secure(tmpdir)
end
end
end
describe "#app_rating" do
let(:options) { { app_rating_config_path: "/tmp/fake-age-rating.json" } }
let(:uploader) { Deliver::UploadMetadata.new(options) }
it "skips age rating upload when app info cannot be fetched (nil)" do
expect(File).not_to receive(:read)
expect(FastlaneCore::UI).not_to receive(:message).with("Setting the app's age rating...")
expect(FastlaneCore::UI).to receive(:important).with("Skipping age rating update because app info could not be fetched.")
uploader.send("app_rating", nil)
end
end
describe "#review_information" do
let(:options) { { metadata_path: tmpdir, app_review_information: app_review_information } }
let(:version) { double("version") }
let(:app_store_review_detail) { double("app_store_review_detail") }
let(:uploader) { Deliver::UploadMetadata.new(options) }
context "with review_information" do
let(:app_review_information) do
{ first_name: "Alice",
last_name: "Smith",
phone_number: "+819012345678",
email_address: "deliver@example.com",
demo_user: "user",
demo_password: "password",
notes: "This is a note" }
end
it "skips review information with empty app_review_information" do
options[:app_review_information] = {}
expect(FastlaneCore::UI).not_to receive(:message).with("Uploading app review information to App Store Connect")
uploader.send("review_information", version)
end
it "successfully set review information" do
expect(version).to receive(:fetch_app_store_review_detail).and_return(app_store_review_detail)
expect(app_store_review_detail).to receive(:update).with(attributes: {
"contact_first_name" => app_review_information[:first_name],
"contact_last_name" => app_review_information[:last_name],
"contact_phone" => app_review_information[:phone_number],
"contact_email" => app_review_information[:email_address],
"demo_account_name" => app_review_information[:demo_user],
"demo_account_password" => app_review_information[:demo_password],
"demo_account_required" => true,
"notes" => app_review_information[:notes]
})
expect(FastlaneCore::UI).to receive(:message).with("Uploading app review information to App Store Connect")
uploader.send("review_information", version)
end
end
context "with demo_user and demo_password" do
context "with string" do
let(:app_review_information) { { demo_user: "user", demo_password: "password" } }
it "review_user_needed is true" do
expect(version).to receive(:fetch_app_store_review_detail).and_return(app_store_review_detail)
expect(app_store_review_detail).to receive(:update).with(attributes: {
"demo_account_name" => app_review_information[:demo_user],
"demo_account_password" => app_review_information[:demo_password],
"demo_account_required" => true
})
uploader.send("review_information", version)
end
end
context "with empty string" do
let(:app_review_information) { { demo_user: "", demo_password: "" } }
it "review_user_needed is false" do
expect(version).to receive(:fetch_app_store_review_detail).and_return(app_store_review_detail)
expect(app_store_review_detail).to receive(:update).with(attributes: {
"demo_account_required" => false
})
uploader.send("review_information", version)
end
end
context "with newline" do
let(:app_review_information) { { demo_user: "\n", demo_password: "\n" } }
it "review_user_needed is false" do
expect(version).to receive(:fetch_app_store_review_detail).and_return(app_store_review_detail)
expect(app_store_review_detail).to receive(:update).with(attributes: {
"demo_account_required" => false
})
uploader.send("review_information", version)
end
end
end
end
context "with metadata" do
let(:app) { double('app') }
let(:id) do
double('id')
end
let(:version) do
double('version',
version_string: '1.0.0')
end
let(:version_localization_en) do
double('version_localization_en',
locale: 'en-US')
end
let(:app_info) { double('app_info') }
let(:live_app_info) { nil }
let(:app_info_localization_en) do
double('app_info_localization_en',
locale: 'en-US')
end
let(:app_review_detail) do
double('app_review_detail')
end
let(:app_store_versions) do
double('app_store_versions',
count: 0)
end
let(:options) { { version_check_wait_retry_limit: 5 } }
let(:uploader) { Deliver::UploadMetadata.new(options) }
let(:metadata_path) { Dir.mktmpdir }
context "fetch app edit" do
context "#fetch_edit_app_store_version" do
it "no retry" do
expect(app).to receive(:get_edit_app_store_version).and_return(version)
edit_version = uploader.fetch_edit_app_store_version(app, 'IOS')
expect(edit_version).to eq(version)
end
it "1 retry" do
expect(Kernel).to receive(:sleep).once.with(20)
expect(app).to receive(:get_edit_app_store_version).and_return(nil)
expect(app).to receive(:get_edit_app_store_version).and_return(version)
edit_version = uploader.fetch_edit_app_store_version(app, 'IOS')
expect(edit_version).to eq(version)
end
it "5 retry" do
expect(Kernel).to receive(:sleep).exactly(5).times
expect(app).to receive(:get_edit_app_store_version).and_return(nil).exactly(5).times
edit_version = uploader.fetch_edit_app_store_version(app, 'IOS')
expect(edit_version).to eq(nil)
end
end
context "#fetch_edit_app_info" do
it "no retry" do
expect(app).to receive(:fetch_edit_app_info).and_return(app_info)
edit_app_info = uploader.fetch_edit_app_info(app)
expect(edit_app_info).to eq(app_info)
end
it "1 retry" do
expect(Kernel).to receive(:sleep).once.with(20)
expect(app).to receive(:fetch_edit_app_info).and_return(nil)
expect(app).to receive(:fetch_edit_app_info).and_return(app_info)
edit_app_info = uploader.fetch_edit_app_info(app)
expect(edit_app_info).to eq(app_info)
end
it "5 retry" do
expect(Kernel).to receive(:sleep).exactly(5).times
expect(app).to receive(:fetch_edit_app_info).and_return(nil).exactly(5).times
edit_app_info = uploader.fetch_edit_app_info(app)
expect(edit_app_info).to eq(nil)
end
end
end
context "#upload" do
let(:options) { {} }
before do
allow(Deliver).to receive(:cache).and_return({ app: app })
allow(uploader).to receive(:review_information)
allow(uploader).to receive(:review_attachment_file)
allow(uploader).to receive(:app_rating)
# Verify available languages
expect(app).to receive(:id).and_return(id)
expect(app).to receive(:get_edit_app_store_version).and_return(version)
expect(uploader).to receive(:fetch_edit_app_info).and_return(app_info)
# Get versions
expect(app).to receive(:get_edit_app_store_version).and_return(version)
expect(version).to receive(:get_app_store_version_localizations).and_return([version_localization_en])
# Get app infos
if app_info
expect(app_info).to receive(:get_app_info_localizations).and_return([app_info_localization_en])
else
expect(live_app_info).to receive(:get_app_info_localizations).and_return([app_info_localization_en])
end
end
context "normal metadata" do
it "saves metadata" do
options[:platform] = "ios"
options[:metadata_path] = metadata_path
options[:name] = { "en-US" => "App name" }
options[:description] = { "en-US" => "App description" }
options[:version_check_wait_retry_limit] = 5
# Get number of versions (used for if whats_new should be sent)
expect(Spaceship::ConnectAPI).to receive(:get_app_store_versions).and_return(app_store_versions)
expect(version).to receive(:update).with(attributes: {})
# Get app info
expect(app_info).to receive(:get_app_info_localizations).and_return([app_info_localization_en])
# Get app info localization English (Used to compare with data to upload)
expect(app_info_localization_en).to receive(:name).and_return('App Name')
# Update version localization
expect(version_localization_en).to receive(:update).with(attributes: {
"description" => options[:description]["en-US"]
})
# Update app info localization
expect(app_info_localization_en).to receive(:update).with(attributes: {
"name" => options[:name]["en-US"]
})
# Update app info
expect(app_info).to receive(:update_categories).with(category_id_map: {})
uploader.upload
end
end
context "with privacy_url" do
it 'saves privacy_url' do
options[:platform] = "ios"
options[:metadata_path] = metadata_path
options[:privacy_url] = { "en-US" => "https://fastlane.tools" }
options[:apple_tv_privacy_policy] = { "en-US" => "https://fastlane.tools/tv" }
options[:version_check_wait_retry_limit] = 5
# Get number of versions (used for if whats_new should be sent)
expect(Spaceship::ConnectAPI).to receive(:get_app_store_versions).and_return(app_store_versions)
expect(version).to receive(:update).with(attributes: {})
# Validate symbol names used when comparing privacy urls before upload
expect(app_info_localization_en).to receive(:privacy_policy_url).and_return(options[:privacy_url]["en-US"])
expect(app_info_localization_en).to receive(:privacy_policy_text).and_return(options[:apple_tv_privacy_policy]["en-US"])
# Update app info
expect(app_info).to receive(:update_categories).with(category_id_map: {})
uploader.upload
end
end
context "with auto_release_date" do
it 'with date' do
options[:platform] = "ios"
options[:metadata_path] = metadata_path
options[:auto_release_date] = 1_595_395_800_000
options[:version_check_wait_retry_limit] = 5
# Get number of version (used for if whats_new should be sent)
expect(Spaceship::ConnectAPI).to receive(:get_app_store_versions).and_return(app_store_versions)
expect(version).to receive(:update).with(attributes: {
"releaseType" => "SCHEDULED",
"earliestReleaseDate" => "2020-07-22T05:00:00+00:00"
})
# Update app info
expect(app_info).to receive(:update_categories).with(category_id_map: {})
uploader.upload
end
end
context "with phased_release" do
it 'with true' do
options[:platform] = "ios"
options[:metadata_path] = metadata_path
options[:phased_release] = true
options[:automatic_release] = false
options[:version_check_wait_retry_limit] = 5
# Get number of version (used for if whats_new should be sent)
expect(Spaceship::ConnectAPI).to receive(:get_app_store_versions).and_return(app_store_versions)
# Defaults to release type manual
expect(version).to receive(:update).with(attributes: {
"releaseType" => "MANUAL"
})
# Get phased release
expect(version).to receive(:fetch_app_store_version_phased_release).and_return(nil)
# Create a phased release
expect(version).to receive(:create_app_store_version_phased_release).with(attributes: {
phasedReleaseState: Spaceship::ConnectAPI::AppStoreVersionPhasedRelease::PhasedReleaseState::INACTIVE
})
# Update app info
expect(app_info).to receive(:update_categories).with(category_id_map: {})
uploader.upload
end
it 'with false' do
options[:platform] = "ios"
options[:metadata_path] = metadata_path
options[:phased_release] = false
options[:version_check_wait_retry_limit] = 5
# Get number of version (used for if whats_new should be sent)
expect(Spaceship::ConnectAPI).to receive(:get_app_store_versions).and_return(app_store_versions)
# Defaults to release type manual
expect(version).to receive(:update).with(attributes: {})
# Get phased release
phased_release = double('phased_release')
expect(version).to receive(:fetch_app_store_version_phased_release).and_return(phased_release)
# Delete phased release
expect(phased_release).to receive(:delete!)
# Update app info
expect(app_info).to receive(:update_categories).with(category_id_map: {})
uploader.upload
end
end
context "with reset_ratings" do
it 'with select reset_ratings' do
options[:platform] = "ios"
options[:metadata_path] = metadata_path
options[:reset_ratings] = true
options[:version_check_wait_retry_limit] = 5
# Get number of version (used for if whats_new should be sent)
expect(Spaceship::ConnectAPI).to receive(:get_app_store_versions).and_return(app_store_versions)
# Defaults to release type manual
expect(version).to receive(:update).with(attributes: {})
# Get reset ratings request
expect(version).to receive(:fetch_reset_ratings_request).and_return(nil)
# Create a reset ratings request
expect(version).to receive(:create_reset_ratings_request)
# Update app info
expect(app_info).to receive(:update_categories).with(category_id_map: {})
uploader.upload
end
it 'does not select reset_ratings' do
options[:platform] = "ios"
options[:metadata_path] = metadata_path
options[:reset_ratings] = false
options[:version_check_wait_retry_limit] = 5
# Get number of version (used for if whats_new should be sent)
expect(Spaceship::ConnectAPI).to receive(:get_app_store_versions).and_return(app_store_versions)
# Defaults to release type manual
expect(version).to receive(:update).with(attributes: {})
# Get reset ratings request
reset_ratings_request = double('reset_ratings_request')
expect(version).to receive(:fetch_reset_ratings_request).and_return(reset_ratings_request)
# Delete reset ratings request
expect(reset_ratings_request).to receive(:delete!)
# Update app info
expect(app_info).to receive(:update_categories).with(category_id_map: {})
uploader.upload
end
end
context "with no editable app info" do
let(:live_app_info) { double('app_info') }
let(:app_info) { nil }
it 'no new app info provided by user' do
options[:platform] = "ios"
options[:metadata_path] = metadata_path
options[:version_check_wait_retry_limit] = 5
# Get live app info
expect(app).to receive(:fetch_live_app_info).and_return(live_app_info)
# Get number of versions (used for if whats_new should be sent)
expect(Spaceship::ConnectAPI).to receive(:get_app_store_versions).and_return(app_store_versions)
expect(version).to receive(:update).with(attributes: {})
uploader.upload
end
it 'same app info as live version' do
options[:platform] = "ios"
options[:metadata_path] = metadata_path
options[:name] = { "en-US" => "App name" }
options[:version_check_wait_retry_limit] = 5
# Get live app info
expect(app).to receive(:fetch_live_app_info).and_return(live_app_info)
# Get number of versions (used for if whats_new should be sent)
expect(Spaceship::ConnectAPI).to receive(:get_app_store_versions).and_return(app_store_versions)
expect(version).to receive(:update).with(attributes: {})
# Get app info localization in English (used to compare with data to upload)
expect(app_info_localization_en).to receive(:name).and_return('App name')
uploader.upload
end
end
end
context "fail when not allowed to update" do
let(:live_app_info) { double('app_info') }
let(:app_info) { nil }
let(:options) {
{
platform: "ios",
metadata_path: metadata_path,
name: { "en-US" => "New app name" },
version_check_wait_retry_limit: 5,
}
}
it 'different app info than live version' do
allow(Deliver).to receive(:cache).and_return({ app: app })
allow(uploader).to receive(:review_information)
allow(uploader).to receive(:review_attachment_file)
allow(uploader).to receive(:app_rating)
# Get app info
expect(uploader).to receive(:fetch_edit_app_info).and_return(app_info)
expect(app).to receive(:fetch_live_app_info).and_return(live_app_info)
expect(live_app_info).to receive(:get_app_info_localizations).and_return([app_info_localization_en])
# Get versions
expect(app).to receive(:get_edit_app_store_version).and_return(version)
expect(version).to receive(:get_app_store_version_localizations).and_return([version_localization_en])
# Get app info localization in English (used to compare with data to upload)
expect(app_info_localization_en).to receive(:name).and_return('App name')
# Fail because app info can't be updated
expect(FastlaneCore::UI).to receive(:user_error!).with("Cannot update languages - could not find an editable 'App Info'. Verify that your app is in one of the editable states in App Store Connect").and_call_original
# Get app info localization in English (used to compare with data to upload)
expect { uploader.upload }.to raise_error(FastlaneCore::Interface::FastlaneError)
end
end
end
describe "#languages" do
let(:options) { { metadata_path: tmpdir } }
let(:uploader) { Deliver::UploadMetadata.new(options) }
def create_metadata(path, text)
File.open(File.join(path), 'w') do |f|
f.write(text)
end
end
def create_filesystem_language(name)
require 'fileutils'
FileUtils.mkdir_p("#{tmpdir}/#{name}")
end
context "detected languages with only file system" do
it "languages are 'de-DE', 'el', 'en-US'" do
options[:languages] = []
create_filesystem_language('en-US')
create_filesystem_language('de-DE')
create_filesystem_language('el')
uploader.load_from_filesystem
languages = uploader.detect_languages
expect(languages.sort).to eql(['de-DE', 'el', 'en-US'])
end
it "languages are 'en-US', 'default'" do
options[:languages] = []
create_filesystem_language('default')
create_filesystem_language('en-US')
uploader.load_from_filesystem
languages = uploader.detect_languages
expect(languages.sort).to eql(['default', 'en-US'])
end
end
context "detected languages with only config options" do
it "languages are 'en-AU', 'en-CA', 'en-GB'" do
options[:languages] = ['en-AU', 'en-CA', 'en-GB']
uploader.load_from_filesystem
languages = uploader.detect_languages
expect(languages.sort).to eql(['en-AU', 'en-CA', 'en-GB'])
end
end
context "detected languages with only release notes" do
it "languages are 'default', 'es-MX'" do
options[:languages] = []
options[:release_notes] = {
'default' => 'something',
'es-MX' => 'something else'
}
uploader.load_from_filesystem
languages = uploader.detect_languages
expect(languages.sort).to eql(['default', 'es-MX'])
end
end
context 'detect languages with file system with default folder' do
it "languages are 'en-US', 'default'" do
options[:languages] = []
create_filesystem_language('default')
create_filesystem_language('en-US')
create_metadata(
File.join(tmpdir, 'default', "#{Deliver::UploadMetadata::LOCALISED_VERSION_VALUES[:description]}.txt"),
'something'
)
uploader.load_from_filesystem
languages = uploader.detect_languages
expect(languages.sort).to eql(['default', 'en-US'])
end
end
context "detected languages with both file system and config options and release notes" do
it "languages are 'de-DE', 'default', 'el', 'en-AU', 'en-CA', 'en-GB', 'en-US', 'es-MX'" do
options[:languages] = ['en-AU', 'en-CA', 'en-GB']
options[:release_notes] = {
'default' => 'something',
'en-US' => 'something else',
'es-MX' => 'something else else'
}
create_filesystem_language('en-US')
create_filesystem_language('de-DE')
create_filesystem_language('el')
uploader.load_from_filesystem
languages = uploader.detect_languages
expect(languages.sort).to eql(['de-DE', 'default', 'el', 'en-AU', 'en-CA', 'en-GB', 'en-US', 'es-MX'])
end
end
context "with localized version values for release notes" do
it "default value set for unspecified languages" do
options[:languages] = ['en-AU', 'en-CA', 'en-GB']
options[:release_notes] = {
'default' => 'something',
'en-US' => 'something else',
'es-MX' => 'something else else'
}
create_filesystem_language('en-US')
create_filesystem_language('de-DE')
create_filesystem_language('el')
uploader.load_from_filesystem
uploader.assign_defaults
expect(options[:release_notes]["en-US"]).to eql('something else')
expect(options[:release_notes]["es-MX"]).to eql('something else else')
expect(options[:release_notes]["en-AU"]).to eql('something')
expect(options[:release_notes]["en-CA"]).to eql('something')
expect(options[:release_notes]["en-GB"]).to eql('something')
expect(options[:release_notes]["de-DE"]).to eql('something')
expect(options[:release_notes]["el"]).to eql('something')
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/runner_spec.rb | deliver/spec/runner_spec.rb | require 'deliver/runner'
class MockSession
def teams
[
{ 'contentProvider' => { 'contentProviderId' => 'abc', 'name' => 'A B C' } },
{ 'contentProvider' => { 'contentProviderId' => 'def', 'name' => 'D E F' } }
]
end
def team_id
'abc'
end
def csrf_tokens
nil
end
end
class MockTransporter
def provider_ids
{
'A B C' => 'abc',
'D E F' => 'somelegacything'
}
end
end
describe Deliver::Runner do
let(:runner) do
allow(Spaceship::ConnectAPI).to receive(:login).and_return(true)
allow(Spaceship::ConnectAPI).to receive(:select_team).and_return(true)
mock_session = MockSession.new
allow(Spaceship::Tunes).to receive(:client).and_return(mock_session)
allow(Spaceship::ConnectAPI).to receive_message_chain('client.tunes_client').and_return(mock_session)
allow_any_instance_of(Deliver::DetectValues).to receive(:run!) { |opt| opt }
Deliver::Runner.new(options)
end
let(:options) do
# A typical options hash expected from Deliver::DetectValues
{
username: 'bill@acme.com',
ipa: 'ACME.ipa',
app_identifier: 'com.acme.acme',
app_version: '1.0.7',
platform: 'ios'
}
end
let(:fake_team_api_key_json_path) { File.absolute_path("./spaceship/spec/connect_api/fixtures/asc_key.json") }
let(:fake_individual_api_key_json_path) { File.absolute_path("./spaceship/spec/connect_api/fixtures/asc_individual_key.json") }
before do
allow(Deliver).to receive(:cache).and_return({
app: double('app', { id: 'YI8C2AS' })
})
end
describe :upload_binary do
let(:transporter) { MockTransporter.new }
before do
allow(FastlaneCore::ItunesTransporter).to receive(:new).and_return(transporter)
end
describe 'with an IPA file for iOS' do
it 'uploads the IPA for the iOS platform' do
expect_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate)
.with(app_id: 'YI8C2AS', ipa_path: 'ACME.ipa', package_path: '/tmp', platform: 'ios')
.and_return('path')
expect(transporter).to receive(:upload).with(package_path: 'path', asset_path: 'ACME.ipa', platform: 'ios').and_return(true)
runner.upload_binary
end
end
describe 'with an IPA file for tvOS' do
before do
options[:platform] = 'appletvos'
end
it 'uploads the IPA for the tvOS platform' do
expect_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate)
.with(app_id: 'YI8C2AS', ipa_path: 'ACME.ipa', package_path: '/tmp', platform: 'appletvos')
.and_return('path')
expect(transporter).to receive(:upload).with(package_path: 'path', asset_path: 'ACME.ipa', platform: 'appletvos').and_return(true)
runner.upload_binary
end
end
describe 'with an IPA file for visionOS' do
before do
options[:platform] = 'xros'
end
it 'uploads the IPA for the visionOS platform' do
expect_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate)
.with(app_id: 'YI8C2AS', ipa_path: 'ACME.ipa', package_path: '/tmp', platform: 'xros')
.and_return('path')
expect(transporter).to receive(:upload).with(package_path: 'path', asset_path: 'ACME.ipa', platform: 'xros').and_return(true)
runner.upload_binary
end
end
describe 'with a PKG file for macOS' do
before do
options[:platform] = 'osx'
options[:pkg] = 'ACME.pkg'
options[:ipa] = nil
end
it 'uploads the PKG for the macOS platform' do
expect_any_instance_of(FastlaneCore::PkgUploadPackageBuilder).to receive(:generate)
.with(app_id: 'YI8C2AS', pkg_path: 'ACME.pkg', package_path: '/tmp', platform: 'osx')
.and_return('path')
expect(transporter).to receive(:upload).with(package_path: 'path', asset_path: 'ACME.pkg', platform: 'osx').and_return(true)
runner.upload_binary
end
end
describe 'with Team API Key' do
before do
options[:api_key] = JSON.load_file(fake_team_api_key_json_path, symbolize_names: true)
end
it 'initializes transporter with API key' do
token = instance_double(Spaceship::ConnectAPI::Token, {
text: 'API_TOKEN',
expired?: false
})
allow(Spaceship::ConnectAPI).to receive(:token).and_return(token)
allow(Spaceship::ConnectAPI).to receive(:token=)
expect_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate).and_return('path')
expect(FastlaneCore::ItunesTransporter).to receive(:new)
.with(
nil,
nil,
false,
nil,
'API_TOKEN',
{
altool_compatible_command: true,
api_key: options[:api_key],
}
)
.and_return(transporter)
expect(transporter).to receive(:upload).with(package_path: 'path', asset_path: 'ACME.ipa', platform: 'ios').and_return(true)
runner.upload_binary
end
end
describe 'with Individual API Key' do
before do
options[:api_key] = JSON.load_file(fake_individual_api_key_json_path, symbolize_names: true)
end
it 'initializes transporter with username' do
token = instance_double(Spaceship::ConnectAPI::Token, {
text: 'API_TOKEN',
expired?: false
})
allow(Spaceship::ConnectAPI).to receive(:token).and_return(token)
allow(Spaceship::ConnectAPI).to receive(:token=)
expect_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate).and_return('path')
expect(FastlaneCore::ItunesTransporter).to receive(:new)
.with(
'bill@acme.com',
nil,
false,
nil,
{
altool_compatible_command: true,
api_key: nil,
}
)
.and_return(transporter)
expect(transporter).to receive(:upload).and_return(true)
runner.upload_binary
end
end
end
describe :verify_binary do
let(:transporter) { MockTransporter.new }
before do
allow(FastlaneCore::ItunesTransporter).to receive(:new).and_return(transporter)
end
describe 'with an IPA file for iOS' do
it 'verifies the IPA for the iOS platform' do
expect_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate)
.with(app_id: 'YI8C2AS', ipa_path: 'ACME.ipa', package_path: '/tmp', platform: 'ios')
.and_return('path')
expect(transporter).to receive(:verify).with(asset_path: "ACME.ipa", package_path: 'path', platform: "ios").and_return(true)
runner.verify_binary
end
end
describe 'with an IPA file for tvOS' do
before do
options[:platform] = 'appletvos'
end
it 'verifies the IPA for the tvOS platform' do
expect_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate)
.with(app_id: 'YI8C2AS', ipa_path: 'ACME.ipa', package_path: '/tmp', platform: 'appletvos')
.and_return('path')
expect(transporter).to receive(:verify).with(asset_path: "ACME.ipa", package_path: 'path', platform: "appletvos").and_return(true)
runner.verify_binary
end
end
describe 'with an IPA file for visionOS' do
before do
options[:platform] = 'xros'
end
it 'verifies the IPA for the visionOS platform' do
expect_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate)
.with(app_id: 'YI8C2AS', ipa_path: 'ACME.ipa', package_path: '/tmp', platform: 'xros')
.and_return('path')
expect(transporter).to receive(:verify).with(asset_path: "ACME.ipa", package_path: 'path', platform: "xros").and_return(true)
runner.verify_binary
end
end
describe 'with a PKG file for macOS' do
before do
options[:platform] = 'osx'
options[:pkg] = 'ACME.pkg'
options[:ipa] = nil
end
it 'verifies the PKG for the macOS platform' do
expect_any_instance_of(FastlaneCore::PkgUploadPackageBuilder).to receive(:generate)
.with(app_id: 'YI8C2AS', pkg_path: 'ACME.pkg', package_path: '/tmp', platform: 'osx')
.and_return('path')
expect(transporter).to receive(:verify).with(asset_path: "ACME.pkg", package_path: 'path', platform: "osx").and_return(true)
runner.verify_binary
end
end
describe 'with Team API Key' do
before do
options[:api_key] = JSON.load_file(fake_team_api_key_json_path, symbolize_names: true)
end
it 'initializes transporter with API Key' do
token = instance_double(Spaceship::ConnectAPI::Token, {
text: 'API_TOKEN',
expired?: false
})
allow(Spaceship::ConnectAPI).to receive(:token).and_return(token)
allow(Spaceship::ConnectAPI).to receive(:token=)
allow_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate).and_return('path')
expect(FastlaneCore::ItunesTransporter).to receive(:new)
.with(
nil,
nil,
false,
nil,
'API_TOKEN',
{
altool_compatible_command: true,
api_key: options[:api_key],
}
)
.and_return(transporter)
expect(transporter).to receive(:verify).and_return(true)
runner.verify_binary
end
end
describe 'with Individual API Key' do
before do
options[:api_key] = JSON.load_file(fake_individual_api_key_json_path, symbolize_names: true)
end
it 'initializes transporter with username' do
token = instance_double(Spaceship::ConnectAPI::Token, {
text: 'API_TOKEN',
expired?: false
})
allow(Spaceship::ConnectAPI).to receive(:token).and_return(token)
allow(Spaceship::ConnectAPI).to receive(:token=)
allow_any_instance_of(FastlaneCore::IpaUploadPackageBuilder).to receive(:generate).and_return('path')
expect(FastlaneCore::ItunesTransporter).to receive(:new)
.with(
'bill@acme.com',
nil,
false,
nil,
{
altool_compatible_command: true,
api_key: nil,
}
)
.and_return(transporter)
expect(transporter).to receive(:verify).and_return(true)
runner.verify_binary
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/detect_values_spec.rb | deliver/spec/detect_values_spec.rb | require 'deliver/detect_values'
describe Deliver::DetectValues do
let(:value_detector) { Deliver::DetectValues.new }
describe :find_folders do
describe 'when folders are not specified in options' do
let(:options) { { screenshots_path: nil, metadata_path: nil } }
describe 'running with fastlane' do
before do
allow(FastlaneCore::Helper).to receive(:fastlane_enabled?).and_return(true)
allow(FastlaneCore::FastlaneFolder).to receive(:path).and_return('./fastlane')
value_detector.find_folders(options)
end
it 'sets up screenshots folder in fastlane folder' do
expect(options[:screenshots_path]).to eq('./fastlane/screenshots')
end
it 'sets up metadata folder in fastlane folder' do
expect(options[:metadata_path]).to eq('./fastlane/metadata')
end
end
describe 'running without fastlane' do
before do
allow(FastlaneCore::Helper).to receive(:fastlane_enabled?).and_return(false)
value_detector.find_folders(options)
end
it 'sets up screenshots folder in current folder' do
expect(options[:screenshots_path]).to eq('./screenshots')
end
it 'sets up metadata folder in current folder' do
expect(options[:metadata_path]).to eq('./metadata')
end
end
end
describe 'when folders are specified in options' do
let(:options) { { screenshots_path: './screenshots', metadata_path: './metadata' } }
it 'keeps the specified screenshots folder' do
expect(options[:screenshots_path]).to eq('./screenshots')
end
it 'keeps the specified metadata folder' do
expect(options[:metadata_path]).to eq('./metadata')
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/spec/upload_screenshots_spec.rb | deliver/spec/upload_screenshots_spec.rb | require 'deliver/upload_screenshots'
require 'fakefs/spec_helpers'
describe Deliver::UploadScreenshots do
describe '#delete_screenshots' do
context 'when localization has a screenshot' do
it 'should delete screenshots by screenshot_sets that AppScreenshotIterator gives' do
# return empty by `app_screenshots` as `each_app_screenshot_set` mocked needs it empty
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
screenshots_per_language = { 'en-US' => [] }
# emulate Deliver::AppScreenshotIterator#each_app_screenshot_set's two behaviors with or without given block
allow_any_instance_of(Deliver::AppScreenshotIterator).to receive(:each_app_screenshot_set) do |&args|
next([[localization, app_screenshot_set]]) unless args
args.call(localization, app_screenshot_set)
end
expect(app_screenshot_set).to receive(:delete!)
described_class.new.delete_screenshots([localization], screenshots_per_language)
end
end
context 'when deletion fails once' do
it 'should retry to delete screenshots' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot', id: 'some-id')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
screenshots_per_language = { 'en-US' => [] }
# emulate Deliver::AppScreenshotIterator#each_app_screenshot_set's two behaviors with or without given block
allow_any_instance_of(Deliver::AppScreenshotIterator).to receive(:each_app_screenshot_set) do |&args|
next([[localization, app_screenshot_set]]) unless args
args.call(localization, app_screenshot_set)
end
# Return a screenshot once to fail validation and then return empty next time to pass it
allow(app_screenshot_set).to receive(:app_screenshots).exactly(2).times.and_return([app_screenshot], [])
# Try `delete!` twice by retry
expect(app_screenshot_set).to receive(:delete!).twice
described_class.new.delete_screenshots([localization], screenshots_per_language)
end
end
context 'when screenshots_per_language do not cover all localizations' do
it 'should only attempt to delete screenshots for selected localizations' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot', id: 'some-id')
en_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [])
fr_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
en_localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [en_screenshot_set])
fr_localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'fr-FR',
get_app_screenshot_sets: [fr_screenshot_set])
# Only en-US in screenshots_per_language, fr-FR should be ignored
screenshots_per_language = { 'en-US' => [] }
allow_any_instance_of(Deliver::AppScreenshotIterator).to receive(:each_app_screenshot_set) do |&args|
result = [[en_localization, en_screenshot_set], [fr_localization, fr_screenshot_set]]
next(result) unless args
result.each { |loc, set| args.call(loc, set) }
end
# en-US set should be deleted, fr-FR should NOT be deleted
expect(en_screenshot_set).to receive(:delete!)
expect(fr_screenshot_set).to_not(receive(:delete!))
# Should succeed since en-US count is 0 (fr-FR's screenshot is not counted)
expect(UI).to_not(receive(:user_error!))
described_class.new.delete_screenshots([en_localization, fr_localization], screenshots_per_language)
end
end
end
describe '#upload_screenshots' do
subject { described_class.new }
before do
# mock these methods partially to simplify test cases
allow(subject).to receive(:wait_for_complete)
allow(subject).to receive(:retry_upload_screenshots_if_needed)
end
context 'when localization has no screenshot uploaded' do
context 'with nil' do
it 'should upload screenshots with app_screenshot_set' do
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: nil)
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
local_screenshot = double('Deliver::AppScreenshot',
path: '/path/to/screenshot',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => [local_screenshot] }
allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true)
allow(described_class).to receive(:calculate_checksum).and_return('checksum')
expect(app_screenshot_set).to receive(:upload_screenshot).with(path: local_screenshot.path, wait_for_processing: false)
subject.upload_screenshots([localization], screenshots_per_language, 3600)
end
end
context 'with empty array' do
it 'should upload screenshots with app_screenshot_set' do
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
local_screenshot = double('Deliver::AppScreenshot',
path: '/path/to/screenshot',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => [local_screenshot] }
allow(described_class).to receive(:calculate_checksum).and_return('checksum')
allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true)
expect(app_screenshot_set).to receive(:upload_screenshot).with(path: local_screenshot.path, wait_for_processing: false)
subject.upload_screenshots([localization], screenshots_per_language, 3600)
end
end
end
context 'when localization has no screenshot uploaded' do
it 'should upload screenshots with app_screenshot_set' do
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
local_screenshot = double('Deliver::AppScreenshot',
path: '/path/to/screenshot',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => [local_screenshot] }
allow(described_class).to receive(:calculate_checksum).and_return('checksum')
allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true)
expect(app_screenshot_set).to receive(:upload_screenshot).with(path: local_screenshot.path, wait_for_processing: false)
subject.upload_screenshots([localization], screenshots_per_language, 3600)
end
end
context 'when localization has the exact same screenshot uploaded already' do
it 'should skip that screenshot' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot',
source_file_checksum: 'checksum')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
local_screenshot = double('Deliver::AppScreenshot',
path: '/path/to/screenshot',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => [local_screenshot] }
allow(described_class).to receive(:calculate_checksum).with(local_screenshot.path).and_return('checksum')
allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true)
expect(app_screenshot_set).to_not(receive(:upload_screenshot))
subject.upload_screenshots([localization], screenshots_per_language, 3600)
end
end
context 'when there are 11 screenshots to upload locally' do
it 'should skip 11th screenshot' do
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
local_screenshot = double('Deliver::AppScreenshot',
path: '/path/to/screenshot',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => Array.new(11, local_screenshot) }
allow(described_class).to receive(:calculate_checksum).with(local_screenshot.path).and_return('checksum')
allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true)
expect(app_screenshot_set).to receive(:upload_screenshot).exactly(10).times
subject.upload_screenshots([localization], screenshots_per_language, 3600)
end
end
context 'when localization has 10 screenshots uploaded already and try uploading another new screenshot' do
it 'should skip 11th screenshot' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot',
source_file_checksum: 'checksum')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: Array.new(10, app_screenshot))
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
uploaded_local_screenshot = double('Deliver::AppScreenshot',
path: '/path/to/screenshot',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
new_local_screenshot = double('Deliver::AppScreenshot',
path: '/path/to/new_screenshot',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => [*Array.new(10, uploaded_local_screenshot), new_local_screenshot] }
allow(described_class).to receive(:calculate_checksum).with(uploaded_local_screenshot.path).and_return('checksum')
allow(described_class).to receive(:calculate_checksum).with(new_local_screenshot.path).and_return('another_checksum')
allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true)
expect(app_screenshot_set).to_not(receive(:upload_screenshot))
subject.upload_screenshots([localization], screenshots_per_language, 3600)
end
end
context 'when localization has 10 screenshots uploaded already and try inserting another new screenshot to the top of the list' do
it 'should skip new screenshot' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot',
source_file_checksum: 'checksum')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: Array.new(10, app_screenshot))
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
uploaded_local_screenshot = double('Deliver::AppScreenshot',
path: 'screenshot.jpg',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
new_local_screenshot = double('Deliver::AppScreenshot',
path: '0_screenshot.jpg',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
# The new screenshot appears prior to others in the iterator
screenshots_per_language = { 'en-US' => [new_local_screenshot, *Array.new(10, uploaded_local_screenshot)] }
allow(described_class).to receive(:calculate_checksum).with(uploaded_local_screenshot.path).and_return('checksum')
allow(described_class).to receive(:calculate_checksum).with(new_local_screenshot.path).and_return('another_checksum')
allow(FastlaneCore::Helper).to receive(:show_loading_indicator).and_return(true)
expect(app_screenshot_set).to_not(receive(:upload_screenshot))
subject.upload_screenshots([localization], screenshots_per_language, 3600)
end
end
end
describe '#wait_for_complete' do
context 'when all the screenshots are COMPLETE state' do
it 'should finish without sleep' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot',
asset_delivery_state: { 'state' => 'COMPLETE' })
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
allow(Time).to receive(:now).and_return(0)
expect(::Kernel).to_not(receive(:sleep))
expect(subject.wait_for_complete(iterator, 3600)).to eq('COMPLETE' => 1)
end
end
context 'when all the screenshots are UPLOAD_COMPLETE state initially and then become COMPLETE state' do
it 'should finish waiting with sleep' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
allow(Time).to receive(:now).and_return(0)
expect_any_instance_of(Object).to receive(:sleep).with(kind_of(Numeric)).once
expect(app_screenshot).to receive(:asset_delivery_state).and_return({ 'state' => 'UPLOAD_COMPLETE' }, { 'state' => 'COMPLETE' })
expect(subject.wait_for_complete(iterator, 3600)).to eq('COMPLETE' => 1)
end
end
context 'when timeout is exceeded' do
it 'should exit the loop and return the current states' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot', asset_delivery_state: { 'state' => 'UPLOAD_COMPLETE' })
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
states = { 'UPLOAD_COMPLETE' => 1 }
allow(Time).to receive(:now).and_return(0, 3601)
expect(subject.wait_for_complete(iterator, 3600)).to eq(states)
end
end
end
describe '#retry_upload_screenshots_if_needed' do
context 'when all the screenshots are COMPLETE state' do
it 'should not retry upload_screenshots' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
states = { 'FAILD' => 0, 'COMPLETE' => 1 }
expect(subject).to_not(receive(:upload_screenshots))
subject.retry_upload_screenshots_if_needed(iterator, states, 1, 1, 0, [], {})
end
end
context 'when one of the screenshots is FAILD state and tries remains non zero' do
it 'should retry upload_screenshots' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot', 'complete?' => false, 'error?' => true)
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
states = { 'FAILED' => 1, 'COMPLETE' => 0 }
expect(subject).to receive(:upload_screenshots).with(any_args)
expect(app_screenshot).to receive(:delete!)
subject.retry_upload_screenshots_if_needed(iterator, states, 1, 1, 0, [], {})
end
end
context 'when given number_of_screenshots doesn\'t match numbers in states in total' do
it 'should retry upload_screenshots' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot', 'complete?' => true, 'error?' => false)
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
states = { 'FAILED' => 1, 'COMPLETE' => 0 }
expect(subject).to receive(:upload_screenshots).with(any_args)
subject.retry_upload_screenshots_if_needed(iterator, states, 999, 1, 0, [], {})
end
end
context 'when retry count left is 0' do
it 'should raise error' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot',
'complete?' => false,
'error?' => true,
file_name: '5.5_1.jpg',
error_messages: ['error_message'])
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
states = { 'FAILED' => 1, 'COMPLETE' => 0 }
expect(subject).to_not(receive(:upload_screenshots).with(any_args))
expect(UI).to receive(:user_error!)
subject.retry_upload_screenshots_if_needed(iterator, states, 1, 0, 0, [], {})
end
end
context 'when there is nothing to upload locally but some exist on App Store Connect' do
let(:number_of_screenshots) { 0 } # This is 0 since no image exists locally
let(:screenshots_per_language) { {} } # This is empty due to the same reason
it 'should just finish' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot', 'complete?' => true)
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
states = { 'COMPLETE' => 1 }
expect(subject).to_not(receive(:upload_screenshots).with(any_args))
expect(UI).to_not(receive(:user_error!))
subject.retry_upload_screenshots_if_needed(iterator, states, number_of_screenshots, 0, 0, [], screenshots_per_language)
end
end
context 'when screenshots are in UPLOAD_COMPLETE state' do
it 'should trigger retry logic' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot',
'complete?' => false,
'error?' => false,
file_name: '5.5_1.jpg',
error_messages: ['error_message'])
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
localizations = [localization]
iterator = Deliver::AppScreenshotIterator.new(localizations)
states = { 'UPLOAD_COMPLETE' => 1 }
expect(subject).to receive(:upload_screenshots).with(any_args)
expect(app_screenshot).to receive(:delete!)
subject.retry_upload_screenshots_if_needed(iterator, states, 1, 1, 0, localizations, {})
end
end
end
describe '#verify_local_screenshots_are_uploaded' do
context 'when checksums for local screenshots all exist on App Store Connect' do
it 'should return true' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot', source_file_checksum: 'checksum')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
local_screenshot = double('Deliver::AppScreenshot',
path: '/path/to/new_screenshot',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => [local_screenshot] }
expect(described_class).to receive(:calculate_checksum).with(local_screenshot.path).and_return('checksum')
expect(subject.verify_local_screenshots_are_uploaded(iterator, screenshots_per_language)).to be(true)
end
end
context 'when some checksums for local screenshots don\'t exist on App Store Connect' do
it 'should return false' do
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot', source_file_checksum: 'checksum_not_matched')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
iterator = Deliver::AppScreenshotIterator.new([localization])
local_screenshot = double('Deliver::AppScreenshot',
path: '/path/to/new_screenshot',
language: 'en-US',
display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55)
screenshots_per_language = { 'en-US' => [local_screenshot] }
expect(described_class).to receive(:calculate_checksum).with(local_screenshot.path).and_return('checksum')
expect(subject.verify_local_screenshots_are_uploaded(iterator, screenshots_per_language)).to be(false)
end
end
end
describe '#sort_screenshots' do
def make_app_screenshot(id: nil, file_name: nil, is_complete: true)
app_screenshot = double('Spaceship::ConnectAPI::AppScreenshot', id: id, file_name: file_name)
# `complete?` needed to be mocked by this way since Rubocop using 2.0 parser can't handle `{ 'complete?': false }` format
allow(app_screenshot).to receive(:complete?).and_return(is_complete)
app_screenshot
end
context 'when localization has screenshots uploaded in wrong order' do
it 'should reorder screenshots' do
app_screenshot1 = make_app_screenshot(id: '1', file_name: '6.5_1.jpg')
app_screenshot2 = make_app_screenshot(id: '2', file_name: '6.5_2.jpg')
app_screenshot3 = make_app_screenshot(id: '3', file_name: '6.5_3.jpg')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot3, app_screenshot2, app_screenshot1])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
expect(app_screenshot_set).to receive(:reorder_screenshots).with(app_screenshot_ids: ['1', '2', '3'])
described_class.new.sort_screenshots([localization])
end
end
context 'when localization has screenshots uploaded in wrong order with trailing numbers up to 10' do
it 'should reorder screenshots' do
app_screenshot1 = make_app_screenshot(id: '1', file_name: '6.5_1.jpg')
app_screenshot2 = make_app_screenshot(id: '2', file_name: '6.5_2.jpg')
app_screenshot10 = make_app_screenshot(id: '10', file_name: '6.5_10.jpg')
app_screenshot_set = double('Spaceship::ConnectAPI::AppScreenshotSet',
screenshot_display_type: Spaceship::ConnectAPI::AppScreenshotSet::DisplayType::APP_IPHONE_55,
app_screenshots: [app_screenshot10, app_screenshot2, app_screenshot1])
localization = double('Spaceship::ConnectAPI::AppStoreVersionLocalization',
locale: 'en-US',
get_app_screenshot_sets: [app_screenshot_set])
expect(app_screenshot_set).to receive(:reorder_screenshots).with(app_screenshot_ids: ['1', '2', '10'])
described_class.new.sort_screenshots([localization])
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver.rb | deliver/lib/deliver.rb | require_relative 'deliver/languages'
require_relative 'deliver/loader'
require_relative 'deliver/options'
require_relative 'deliver/commands_generator'
require_relative 'deliver/detect_values'
require_relative 'deliver/runner'
require_relative 'deliver/upload_metadata'
require_relative 'deliver/upload_screenshots'
require_relative 'deliver/upload_price_tier'
require_relative 'deliver/submit_for_review'
require_relative 'deliver/app_screenshot'
require_relative 'deliver/html_generator'
require_relative 'deliver/generate_summary'
require_relative 'deliver/module'
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/setup.rb | deliver/lib/deliver/setup.rb | require 'spaceship/tunes/tunes'
require_relative 'module'
require_relative 'download_screenshots'
require_relative 'upload_metadata'
module Deliver
class Setup
attr_accessor :is_swift
def run(options, is_swift: false)
containing = Helper.fastlane_enabled_folder_path
self.is_swift = is_swift
if is_swift
file_path = File.join(containing, 'Deliverfile.swift')
else
file_path = File.join(containing, 'Deliverfile')
end
data = generate_deliver_file(containing, options)
setup_deliver(file_path, data, containing, options)
end
def setup_deliver(file_path, data, deliver_path, options)
File.write(file_path, data)
screenshots_path = options[:screenshots_path] || File.join(deliver_path, 'screenshots')
unless options[:skip_screenshots]
download_screenshots(screenshots_path, options)
# Add a README to the screenshots folder
FileUtils.mkdir_p(screenshots_path) # just in case the fetching didn't work
File.write(File.join(screenshots_path, 'README.txt'), File.read("#{Deliver::ROOT}/lib/assets/ScreenshotsHelp"))
end
UI.success("Successfully created new Deliverfile at path '#{file_path}'")
end
# This method takes care of creating a new 'deliver' folder, containing the app metadata
# and screenshots folders
def generate_deliver_file(deliver_path, options)
app = Deliver.cache[:app]
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
v = app.get_latest_app_store_version(platform: platform)
metadata_path = options[:metadata_path] || File.join(deliver_path, 'metadata')
generate_metadata_files(app, v, metadata_path, options)
# Generate the final Deliverfile here
return File.read(deliverfile_path)
end
def deliverfile_path
if self.is_swift
return "#{Deliver::ROOT}/lib/assets/DeliverfileDefault.swift"
else
return "#{Deliver::ROOT}/lib/assets/DeliverfileDefault"
end
end
def generate_metadata_files(app, version, path, options)
# App info localizations
if options[:use_live_version]
app_info = app.fetch_live_app_info
UI.user_error!("The option `use_live_version` was set to `true`, however no live app was found on App Store Connect.") unless app_info
else
app_info = app.fetch_edit_app_info || app.fetch_live_app_info
end
app_info_localizations = app_info.get_app_info_localizations
app_info_localizations.each do |localization|
language = localization.locale
UploadMetadata::LOCALISED_APP_VALUES.each do |file_key, attribute_name|
content = localization.send(attribute_name.to_slug) || ""
content += "\n"
resulting_path = File.join(path, language, "#{file_key}.txt")
FileUtils.mkdir_p(File.expand_path('..', resulting_path))
File.write(resulting_path, content)
UI.message("Writing to '#{resulting_path}'")
end
end
# Version localizations
version_localizations = version.get_app_store_version_localizations
version_localizations.each do |localization|
language = localization.locale
UploadMetadata::LOCALISED_VERSION_VALUES.each do |file_key, attribute_name|
content = localization.send(attribute_name) || ""
content += "\n"
resulting_path = File.join(path, language, "#{file_key}.txt")
FileUtils.mkdir_p(File.expand_path('..', resulting_path))
File.write(resulting_path, content)
UI.message("Writing to '#{resulting_path}'")
end
end
# App info (categories)
UploadMetadata::NON_LOCALISED_APP_VALUES.each do |file_key, attribute_name|
category = app_info.send(attribute_name)
content = category ? category.id.to_s : ""
content += "\n"
resulting_path = File.join(path, "#{file_key}.txt")
FileUtils.mkdir_p(File.expand_path('..', resulting_path))
File.write(resulting_path, content)
UI.message("Writing to '#{resulting_path}'")
end
# Version
UploadMetadata::NON_LOCALISED_VERSION_VALUES.each do |file_key, attribute_name|
content = version.send(attribute_name) || ""
content += "\n"
resulting_path = File.join(path, "#{file_key}.txt")
FileUtils.mkdir_p(File.expand_path('..', resulting_path))
File.write(resulting_path, content)
UI.message("Writing to '#{resulting_path}'")
end
# Review information
app_store_review_detail = begin
version.fetch_app_store_review_detail
rescue
nil
end # errors if doesn't exist
UploadMetadata::REVIEW_INFORMATION_VALUES.each do |file_key, attribute_name|
if app_store_review_detail
content = app_store_review_detail.send(attribute_name) || ""
else
content = ""
end
content += "\n"
base_dir = File.join(path, UploadMetadata::REVIEW_INFORMATION_DIR)
resulting_path = File.join(base_dir, "#{file_key}.txt")
FileUtils.mkdir_p(File.expand_path('..', resulting_path))
File.write(resulting_path, content)
UI.message("Writing to '#{resulting_path}'")
end
end
def generate_metadata_files_old(v, path)
app_details = v.application.details
# All the localised metadata
(UploadMetadata::LOCALISED_VERSION_VALUES.keys + UploadMetadata::LOCALISED_APP_VALUES.keys).each do |key|
v.description.languages.each do |language|
if UploadMetadata::LOCALISED_VERSION_VALUES.keys.include?(key)
content = v.send(key)[language].to_s
else
content = app_details.send(key)[language].to_s
end
content += "\n"
resulting_path = File.join(path, language, "#{key}.txt")
FileUtils.mkdir_p(File.expand_path('..', resulting_path))
File.write(resulting_path, content)
UI.message("Writing to '#{resulting_path}'")
end
end
# All non-localised metadata
(UploadMetadata::NON_LOCALISED_VERSION_VALUES.keys + UploadMetadata::NON_LOCALISED_APP_VALUES).each do |key|
if UploadMetadata::NON_LOCALISED_VERSION_VALUES.keys.include?(key)
content = v.send(key).to_s
else
content = app_details.send(key).to_s
end
content += "\n"
resulting_path = File.join(path, "#{key}.txt")
File.write(resulting_path, content)
UI.message("Writing to '#{resulting_path}'")
end
# Review information
UploadMetadata::REVIEW_INFORMATION_VALUES_LEGACY.each do |key, option_name|
content = v.send(key).to_s
content += "\n"
base_dir = File.join(path, UploadMetadata::REVIEW_INFORMATION_DIR)
FileUtils.mkdir_p(base_dir)
resulting_path = File.join(base_dir, "#{option_name}.txt")
File.write(resulting_path, content)
UI.message("Writing to '#{resulting_path}'")
end
UI.success("Successfully created new configuration files.")
end
def download_screenshots(path, options)
FileUtils.mkdir_p(path)
Deliver::DownloadScreenshots.run(options, path)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/download_screenshots.rb | deliver/lib/deliver/download_screenshots.rb | require_relative 'module'
require 'spaceship'
require 'open-uri'
module Deliver
class DownloadScreenshots
def self.run(options, path)
UI.message("Downloading all existing screenshots...")
download(options, path)
UI.success("Successfully downloaded all existing screenshots")
rescue => ex
UI.error(ex)
UI.error("Couldn't download already existing screenshots from App Store Connect.")
end
def self.download(options, folder_path)
app = Deliver.cache[:app]
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
if options[:use_live_version]
version = app.get_live_app_store_version(platform: platform)
UI.user_error!("Could not find a live version on App Store Connect. Try using '--use_live_version false'") if version.nil?
else
version = app.get_edit_app_store_version(platform: platform)
UI.user_error!("Could not find an edit version on App Store Connect. Try using '--use_live_version true'") if version.nil?
end
localizations = version.get_app_store_version_localizations
threads = []
localizations.each do |localization|
threads << Thread.new do
download_screenshots(folder_path, localization)
end
end
threads.each(&:join)
end
def self.download_screenshots(folder_path, localization)
language = localization.locale
screenshot_sets = localization.get_app_screenshot_sets
screenshot_sets.each do |screenshot_set|
screenshot_set.app_screenshots.each_with_index do |screenshot, index|
file_name = [index, screenshot_set.screenshot_display_type, index].join("_")
original_file_extension = File.extname(screenshot.file_name).strip.downcase[1..-1]
file_name += "." + original_file_extension
url = screenshot.image_asset_url(type: original_file_extension)
next if url.nil?
UI.message("Downloading existing screenshot '#{file_name}' for language '#{language}'")
# If the screen shot is for an appleTV we need to store it in a way that we'll know it's an appleTV
# screen shot later as the screen size is the same as an iPhone 6 Plus in landscape.
if screenshot_set.apple_tv?
containing_folder = File.join(folder_path, "appleTV", language)
else
containing_folder = File.join(folder_path, language)
end
if screenshot_set.imessage?
containing_folder = File.join(folder_path, "iMessage", language)
end
begin
FileUtils.mkdir_p(containing_folder)
rescue
# if it's already there
end
path = File.join(containing_folder, file_name)
File.binwrite(path, URI.open(url).read)
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/options.rb | deliver/lib/deliver/options.rb | require 'fastlane_core/configuration/config_item'
require 'credentials_manager/appfile_config'
require_relative 'module'
module Deliver
# rubocop:disable Metrics/ClassLength
class Options
def self.available_options
user = CredentialsManager::AppfileConfig.try_fetch_value(:itunes_connect_id)
user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)
user ||= ENV["DELIVER_USER"]
[
FastlaneCore::ConfigItem.new(key: :api_key_path,
env_names: ["DELIVER_API_KEY_PATH", "APP_STORE_CONNECT_API_KEY_PATH"],
description: "Path to your App Store Connect API Key JSON file (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-json-file)",
optional: true,
conflicting_options: [:api_key],
verify_block: proc do |value|
UI.user_error!("Couldn't find API key JSON file at path '#{value}'") unless File.exist?(value)
end),
FastlaneCore::ConfigItem.new(key: :api_key,
env_names: ["DELIVER_API_KEY", "APP_STORE_CONNECT_API_KEY"],
description: "Your App Store Connect API Key information (https://docs.fastlane.tools/app-store-connect-api/#using-fastlane-api-key-hash-option)",
type: Hash,
optional: true,
sensitive: true,
conflicting_options: [:api_key_path]),
FastlaneCore::ConfigItem.new(key: :username,
short_option: "-u",
env_name: "DELIVER_USERNAME",
description: "Your Apple ID Username",
optional: true,
default_value: user,
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :app_identifier,
short_option: "-a",
env_name: "DELIVER_APP_IDENTIFIER",
description: "The bundle identifier of your app",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier),
default_value_dynamic: true),
# version
FastlaneCore::ConfigItem.new(key: :app_version,
short_option: '-z',
env_name: "DELIVER_APP_VERSION",
description: "The version that should be edited or created",
optional: true),
# binary / build
FastlaneCore::ConfigItem.new(key: :ipa,
short_option: "-i",
optional: true,
env_name: "DELIVER_IPA_PATH",
description: "Path to your ipa file",
code_gen_sensitive: true,
default_value: Dir["*.ipa"].sort_by { |x| File.mtime(x) }.last,
default_value_dynamic: true,
verify_block: proc do |value|
UI.user_error!("Could not find ipa file at path '#{File.expand_path(value)}'") unless File.exist?(value)
UI.user_error!("'#{value}' doesn't seem to be an ipa file") unless value.end_with?(".ipa")
end,
conflicting_options: [:pkg],
conflict_block: proc do |value|
UI.user_error!("You can't use 'ipa' and '#{value.key}' options in one run.")
end),
FastlaneCore::ConfigItem.new(key: :pkg,
short_option: "-c",
optional: true,
env_name: "DELIVER_PKG_PATH",
description: "Path to your pkg file",
code_gen_sensitive: true,
default_value: Dir["*.pkg"].sort_by { |x| File.mtime(x) }.last,
default_value_dynamic: true,
verify_block: proc do |value|
UI.user_error!("Could not find pkg file at path '#{File.expand_path(value)}'") unless File.exist?(value)
UI.user_error!("'#{value}' doesn't seem to be a pkg file") unless value.end_with?(".pkg")
end,
conflicting_options: [:ipa],
conflict_block: proc do |value|
UI.user_error!("You can't use 'pkg' and '#{value.key}' options in one run.")
end),
FastlaneCore::ConfigItem.new(key: :build_number,
short_option: "-n",
env_name: "DELIVER_BUILD_NUMBER",
description: "If set the given build number (already uploaded to iTC) will be used instead of the current built one",
optional: true,
conflicting_options: [:ipa, :pkg],
conflict_block: proc do |value|
UI.user_error!("You can't use 'build_number' and '#{value.key}' options in one run.")
end),
FastlaneCore::ConfigItem.new(key: :platform,
short_option: "-j",
env_name: "DELIVER_PLATFORM",
description: "The platform to use (optional)",
optional: true,
default_value: "ios",
verify_block: proc do |value|
UI.user_error!("The platform can only be ios, appletvos/tvos, xros or osx") unless %w(ios appletvos tvos xros osx).include?(value)
end),
# live version
FastlaneCore::ConfigItem.new(key: :edit_live,
short_option: "-o",
optional: true,
default_value: false,
env_name: "DELIVER_EDIT_LIVE",
description: "Modify live metadata, this option disables ipa upload and screenshot upload",
type: Boolean),
FastlaneCore::ConfigItem.new(key: :use_live_version,
env_name: "DELIVER_USE_LIVE_VERSION",
description: "Force usage of live version rather than edit version",
type: Boolean,
default_value: false),
# paths
FastlaneCore::ConfigItem.new(key: :metadata_path,
short_option: '-m',
env_name: "DELIVER_METADATA_PATH",
description: "Path to the folder containing the metadata files",
optional: true),
FastlaneCore::ConfigItem.new(key: :screenshots_path,
short_option: '-w',
env_name: "DELIVER_SCREENSHOTS_PATH",
description: "Path to the folder containing the screenshots",
optional: true),
# skip
FastlaneCore::ConfigItem.new(key: :skip_binary_upload,
env_name: "DELIVER_SKIP_BINARY_UPLOAD",
description: "Skip uploading an ipa or pkg to App Store Connect",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :skip_screenshots,
env_name: "DELIVER_SKIP_SCREENSHOTS",
description: "Don't upload the screenshots",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :skip_metadata,
env_name: "DELIVER_SKIP_METADATA",
description: "Don't upload the metadata (e.g. title, description). This will still upload screenshots",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :skip_app_version_update,
env_name: "DELIVER_SKIP_APP_VERSION_UPDATE",
description: "Don’t create or update the app version that is being prepared for submission",
type: Boolean,
default_value: false),
# how to operate
FastlaneCore::ConfigItem.new(key: :force,
short_option: "-f",
env_name: "DELIVER_FORCE",
description: "Skip verification of HTML preview file",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :overwrite_screenshots,
env_name: "DELIVER_OVERWRITE_SCREENSHOTS",
description: "Clear all previously uploaded screenshots before uploading the new ones",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :screenshot_processing_timeout,
env_name: "DELIVER_SCREENSHOT_PROCESSING_TIMEOUT",
description: "Timeout in seconds to wait before considering screenshot processing as failed, used to handle cases where uploads to the App Store are stuck in processing",
type: Integer,
default_value: 3600),
FastlaneCore::ConfigItem.new(key: :sync_screenshots,
env_name: "DELIVER_SYNC_SCREENSHOTS",
description: "Sync screenshots with local ones. This is currently beta option so set true to 'FASTLANE_ENABLE_BETA_DELIVER_SYNC_SCREENSHOTS' environment variable as well",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :submit_for_review,
env_name: "DELIVER_SUBMIT_FOR_REVIEW",
description: "Submit the new version for Review after uploading everything",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :verify_only,
env_name: "DELIVER_VERIFY_ONLY",
description: "Verifies archive with App Store Connect without uploading",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :reject_if_possible,
env_name: "DELIVER_REJECT_IF_POSSIBLE",
description: "Rejects the previously submitted build if it's in a state where it's possible",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :version_check_wait_retry_limit,
env_name: "DELIVER_VERSION_CHECK_WAIT_RETRY_LIMIT",
description: "After submitting a new version, App Store Connect takes some time to recognize the new version and we must wait until it's available before attempting to upload metadata for it. There is a mechanism that will check if it's available and retry with an exponential backoff if it's not available yet. " \
"This option specifies how many times we should retry before giving up. Setting this to a value below 5 is not recommended and will likely cause failures. Increase this parameter when Apple servers seem to be degraded or slow",
type: Integer,
default_value: 7,
verify_block: proc do |value|
UI.user_error!("'#{value}' needs to be greater than 0") if value <= 0
end),
# release
FastlaneCore::ConfigItem.new(key: :automatic_release,
env_name: "DELIVER_AUTOMATIC_RELEASE",
description: "Should the app be automatically released once it's approved? (Cannot be used together with `auto_release_date`)",
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :auto_release_date,
env_name: "DELIVER_AUTO_RELEASE_DATE",
description: "Date in milliseconds for automatically releasing on pending approval (Cannot be used together with `automatic_release`)",
type: Integer,
optional: true,
conflicting_options: [:automatic_release],
conflict_block: proc do |value|
UI.user_error!("You can't use 'auto_release_date' and '#{value.key}' options together.")
end,
verify_block: proc do |value|
now_in_ms = Time.now.to_i * 1000
if value < now_in_ms
UI.user_error!("'#{value}' needs to be in the future and in milliseconds (current time is '#{now_in_ms}')")
end
end),
FastlaneCore::ConfigItem.new(key: :phased_release,
env_name: "DELIVER_PHASED_RELEASE",
description: "Enable the phased release feature of iTC",
optional: true,
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :reset_ratings,
env_name: "DELIVER_RESET_RATINGS",
description: "Reset the summary rating when you release a new version of the application",
optional: true,
type: Boolean,
default_value: false),
# other app configuration
FastlaneCore::ConfigItem.new(key: :price_tier,
short_option: "-r",
env_name: "DELIVER_PRICE_TIER",
description: "The price tier of this application",
type: Integer,
optional: true),
FastlaneCore::ConfigItem.new(key: :app_rating_config_path,
short_option: "-g",
env_name: "DELIVER_APP_RATING_CONFIG_PATH",
description: "Path to the app rating's config",
optional: true,
verify_block: proc do |value|
UI.user_error!("Could not find config file at path '#{File.expand_path(value)}'") unless File.exist?(value)
UI.user_error!("'#{value}' doesn't seem to be a JSON file") unless FastlaneCore::Helper.json_file?(File.expand_path(value))
end),
FastlaneCore::ConfigItem.new(key: :submission_information,
short_option: "-b",
description: "Extra information for the submission (e.g. compliance specifications)",
type: Hash,
optional: true),
# affiliation
FastlaneCore::ConfigItem.new(key: :team_id,
short_option: "-k",
env_name: "DELIVER_TEAM_ID",
description: "The ID of your App Store Connect team if you're in multiple teams",
optional: true,
skip_type_validation: true, # as we also allow integers, which we convert to strings anyway
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:itc_team_id),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_ITC_TEAM_ID"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :team_name,
short_option: "-e",
env_name: "DELIVER_TEAM_NAME",
description: "The name of your App Store Connect team if you're in multiple teams",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:itc_team_name),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_ITC_TEAM_NAME"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :dev_portal_team_id,
short_option: "-s",
env_name: "DELIVER_DEV_PORTAL_TEAM_ID",
description: "The short ID of your Developer Portal team, if you're in multiple teams. Different from your iTC team ID!",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_id),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_TEAM_ID"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :dev_portal_team_name,
short_option: "-y",
env_name: "DELIVER_DEV_PORTAL_TEAM_NAME",
description: "The name of your Developer Portal team if you're in multiple teams",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_name),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_TEAM_NAME"] = value.to_s
end),
# rubocop:disable Layout/LineLength
FastlaneCore::ConfigItem.new(key: :itc_provider,
env_name: "DELIVER_ITC_PROVIDER",
description: "The provider short name to be used with the iTMSTransporter to identify your team. This value will override the automatically detected provider short name. To get provider short name run `pathToXcode.app/Contents/Applications/Application\\ Loader.app/Contents/itms/bin/iTMSTransporter -m provider -u 'USERNAME' -p 'PASSWORD' -account_type itunes_connect -v off`. The short names of providers should be listed in the second column",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:itc_provider),
default_value_dynamic: true),
# rubocop:enable Layout/LineLength
# precheck
FastlaneCore::ConfigItem.new(key: :run_precheck_before_submit,
short_option: "-x",
env_name: "DELIVER_RUN_PRECHECK_BEFORE_SUBMIT",
description: "Run precheck before submitting to app review",
type: Boolean,
default_value: true),
FastlaneCore::ConfigItem.new(key: :precheck_default_rule_level,
short_option: "-d",
env_name: "DELIVER_PRECHECK_DEFAULT_RULE_LEVEL",
description: "The default precheck rule level unless otherwise configured",
type: Symbol,
default_value: :warn),
# App Metadata
FastlaneCore::ConfigItem.new(key: :individual_metadata_items,
env_names: ["DELIVER_INDIVUDAL_METADATA_ITEMS", "DELIVER_INDIVIDUAL_METADATA_ITEMS"], # The version with typo must be deprecated
description: "An array of localized metadata items to upload individually by language so that errors can be identified. E.g. ['name', 'keywords', 'description']. Note: slow",
deprecated: "Removed after the migration to the new App Store Connect API in June 2020",
type: Array,
optional: true),
# Non Localised
FastlaneCore::ConfigItem.new(key: :app_icon,
env_name: "DELIVER_APP_ICON_PATH",
description: "Metadata: The path to the app icon",
deprecated: "Removed after the migration to the new App Store Connect API in June 2020",
optional: true,
short_option: "-l"),
FastlaneCore::ConfigItem.new(key: :apple_watch_app_icon,
env_name: "DELIVER_APPLE_WATCH_APP_ICON_PATH",
description: "Metadata: The path to the Apple Watch app icon",
deprecated: "Removed after the migration to the new App Store Connect API in June 2020",
optional: true,
short_option: "-q"),
FastlaneCore::ConfigItem.new(key: :copyright,
env_name: "DELIVER_COPYRIGHT",
description: "Metadata: The copyright notice",
optional: true),
FastlaneCore::ConfigItem.new(key: :primary_category,
env_name: "DELIVER_PRIMARY_CATEGORY",
description: "Metadata: The english name of the primary category (e.g. `Business`, `Books`)",
optional: true),
FastlaneCore::ConfigItem.new(key: :secondary_category,
env_name: "DELIVER_SECONDARY_CATEGORY",
description: "Metadata: The english name of the secondary category (e.g. `Business`, `Books`)",
optional: true),
FastlaneCore::ConfigItem.new(key: :primary_first_sub_category,
env_name: "DELIVER_PRIMARY_FIRST_SUB_CATEGORY",
description: "Metadata: The english name of the primary first sub category (e.g. `Educational`, `Puzzle`)",
optional: true),
FastlaneCore::ConfigItem.new(key: :primary_second_sub_category,
env_name: "DELIVER_PRIMARY_SECOND_SUB_CATEGORY",
description: "Metadata: The english name of the primary second sub category (e.g. `Educational`, `Puzzle`)",
optional: true),
FastlaneCore::ConfigItem.new(key: :secondary_first_sub_category,
env_name: "DELIVER_SECONDARY_FIRST_SUB_CATEGORY",
description: "Metadata: The english name of the secondary first sub category (e.g. `Educational`, `Puzzle`)",
optional: true),
FastlaneCore::ConfigItem.new(key: :secondary_second_sub_category,
env_name: "DELIVER_SECONDARY_SECOND_SUB_CATEGORY",
description: "Metadata: The english name of the secondary second sub category (e.g. `Educational`, `Puzzle`)",
optional: true),
FastlaneCore::ConfigItem.new(key: :trade_representative_contact_information,
description: "Metadata: A hash containing the trade representative contact information",
optional: true,
deprecated: "This is no longer used by App Store Connect",
type: Hash),
FastlaneCore::ConfigItem.new(key: :app_review_information,
description: "Metadata: A hash containing the review information",
optional: true,
type: Hash),
FastlaneCore::ConfigItem.new(key: :app_review_attachment_file,
env_name: "DELIVER_APP_REVIEW_ATTACHMENT_FILE",
description: "Metadata: Path to the app review attachment file",
optional: true),
# Localised
FastlaneCore::ConfigItem.new(key: :description,
description: "Metadata: The localised app description",
optional: true,
type: Hash),
FastlaneCore::ConfigItem.new(key: :name,
description: "Metadata: The localised app name",
optional: true,
type: Hash),
FastlaneCore::ConfigItem.new(key: :subtitle,
description: "Metadata: The localised app subtitle",
optional: true,
type: Hash,
verify_block: proc do |value|
UI.user_error!(":subtitle must be a hash, with the language being the key") unless value.kind_of?(Hash)
end),
FastlaneCore::ConfigItem.new(key: :keywords,
description: "Metadata: An array of localised keywords",
optional: true,
type: Hash,
verify_block: proc do |value|
UI.user_error!(":keywords must be a hash, with the language being the key") unless value.kind_of?(Hash)
value.each do |language, keywords|
# Auto-convert array to string
keywords = keywords.join(", ") if keywords.kind_of?(Array)
value[language] = keywords
UI.user_error!("keywords must be a hash with all values being strings") unless keywords.kind_of?(String)
end
end),
FastlaneCore::ConfigItem.new(key: :promotional_text,
description: "Metadata: An array of localised promotional texts",
optional: true,
type: Hash,
verify_block: proc do |value|
UI.user_error!(":keywords must be a hash, with the language being the key") unless value.kind_of?(Hash)
end),
FastlaneCore::ConfigItem.new(key: :release_notes,
description: "Metadata: Localised release notes for this version",
optional: true,
type: Hash),
FastlaneCore::ConfigItem.new(key: :privacy_url,
description: "Metadata: Localised privacy url",
optional: true,
type: Hash),
FastlaneCore::ConfigItem.new(key: :apple_tv_privacy_policy,
description: "Metadata: Localised Apple TV privacy policy text",
optional: true,
type: Hash),
FastlaneCore::ConfigItem.new(key: :support_url,
description: "Metadata: Localised support url",
optional: true,
type: Hash),
FastlaneCore::ConfigItem.new(key: :marketing_url,
description: "Metadata: Localised marketing url",
optional: true,
type: Hash),
# The verify_block has been removed from here and verification now happens in Deliver::DetectValues
# Verification needed Spaceship::Tunes.client which required the Deliver::Runner to already by started
FastlaneCore::ConfigItem.new(key: :languages,
env_name: "DELIVER_LANGUAGES",
description: "Metadata: List of languages to activate",
type: Array,
optional: true),
FastlaneCore::ConfigItem.new(key: :ignore_language_directory_validation,
env_name: "DELIVER_IGNORE_LANGUAGE_DIRECTORY_VALIDATION",
description: "Ignore errors when invalid languages are found in metadata and screenshot directories",
default_value: false,
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | true |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/detect_values.rb | deliver/lib/deliver/detect_values.rb | require 'fastlane_core/fastlane_folder'
require 'fastlane_core/ipa_file_analyser'
require 'fastlane_core/pkg_file_analyser'
require 'spaceship/tunes/tunes'
require 'spaceship/tunes/application'
require_relative 'module'
require_relative 'languages'
module Deliver
class DetectValues
def run!(options, skip_params = {})
Deliver.cache = {}
find_platform(options)
find_app_identifier(options)
find_app(options)
find_folders(options)
ensure_folders_created(options)
find_version(options) unless skip_params[:skip_version]
verify_languages!(options)
end
def find_app_identifier(options)
return if options[:app_identifier]
if options[:ipa]
identifier = FastlaneCore::IpaFileAnalyser.fetch_app_identifier(options[:ipa])
elsif options[:pkg]
identifier = FastlaneCore::PkgFileAnalyser.fetch_app_identifier(options[:pkg])
end
options[:app_identifier] = identifier if identifier.to_s.length > 0
options[:app_identifier] ||= UI.input("The Bundle Identifier of your App: ")
rescue => ex
UI.error("#{ex.message}\n#{ex.backtrace.join('\n')}")
UI.user_error!("Could not infer your App's Bundle Identifier")
end
def find_app(options)
app_identifier = options[:app_identifier]
app_id = options[:app] if app_identifier.to_s.empty?
if !app_identifier.to_s.empty?
app = Spaceship::ConnectAPI::App.find(app_identifier)
elsif !app_id.kind_of?(Spaceship::ConnectAPI::App) && !app_id.to_s.empty?
app = Spaceship::ConnectAPI::App.get(app_id: app_id)
end
Deliver.cache[:app] = app
unless app
UI.user_error!("Could not find app with app identifier '#{options[:app_identifier]}' in your App Store Connect account (#{options[:username]} - Team: #{Spaceship::Tunes.client.team_id})")
end
end
def find_folders(options)
containing = Helper.fastlane_enabled? ? FastlaneCore::FastlaneFolder.path : '.'
options[:screenshots_path] ||= File.join(containing, 'screenshots')
options[:metadata_path] ||= File.join(containing, 'metadata')
end
def ensure_folders_created(options)
FileUtils.mkdir_p(options[:screenshots_path])
FileUtils.mkdir_p(options[:metadata_path])
end
def find_version(options)
return if options[:app_version]
if options[:ipa]
options[:app_version] ||= FastlaneCore::IpaFileAnalyser.fetch_app_version(options[:ipa])
elsif options[:pkg]
options[:app_version] ||= FastlaneCore::PkgFileAnalyser.fetch_app_version(options[:pkg])
end
rescue => ex
UI.error("#{ex.message}\n#{ex.backtrace.join('\n')}")
UI.user_error!("Could not infer your app's version")
end
def find_platform(options)
if options[:ipa]
options[:platform] ||= FastlaneCore::IpaFileAnalyser.fetch_app_platform(options[:ipa])
elsif options[:pkg]
options[:platform] = 'osx'
end
end
def verify_languages!(options)
languages = options[:languages]
return unless languages
# 2020-08-24 - Available locales are not available as an endpoint in App Store Connect
# Update with Spaceship::Tunes.client.available_languages.sort (as long as endpoint is available)
all_languages = Deliver::Languages::ALL_LANGUAGES
diff = languages - all_languages
unless diff.empty?
UI.user_error!("The following languages are invalid and cannot be activated: #{diff.join(',')}\n\nValid languages are: #{all_languages}")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/loader.rb | deliver/lib/deliver/loader.rb | require_relative 'module'
require_relative 'app_screenshot'
require_relative 'app_screenshot_validator'
require_relative 'upload_metadata'
require_relative 'languages'
module Deliver
module Loader
# The directory 'appleTV' and `iMessage` are special folders that will cause our screenshot gathering code to iterate
# through it as well searching for language folders.
APPLE_TV_DIR_NAME = "appleTV".freeze
IMESSAGE_DIR_NAME = "iMessage".freeze
DEFAULT_DIR_NAME = "default".freeze
EXPANDABLE_DIR_NAMES = [APPLE_TV_DIR_NAME, IMESSAGE_DIR_NAME].freeze
SPECIAL_DIR_NAMES = [APPLE_TV_DIR_NAME, IMESSAGE_DIR_NAME, DEFAULT_DIR_NAME].freeze
# Some exception directories may exist from other actions that should not be iterated through
SUPPLY_DIR_NAME = "android".freeze
FRAMEIT_FONTS_DIR_NAME = "fonts".freeze
META_DIR_NAMES = UploadMetadata::ALL_META_SUB_DIRS.map(&:downcase)
EXCEPTION_DIRECTORIES = (META_DIR_NAMES << SUPPLY_DIR_NAME << FRAMEIT_FONTS_DIR_NAME).freeze
# A class that represents language folder under screenshots or metadata folder
class LanguageFolder
attr_reader :path
# @return [String] A normalized language name that corresponds to the directory's name
attr_reader :language
def self.available_languages
# 2020-08-24 - Available locales are not available as an endpoint in App Store Connect
# Update with Spaceship::Tunes.client.available_languages.sort (as long as endpoint is available)
Deliver::Languages::ALL_LANGUAGES
end
def self.allowed_directory_names_with_case
available_languages + SPECIAL_DIR_NAMES
end
# @param path [String] A directory path otherwise this initializer fails
# @param nested [Boolean] Whether given path is nested of another special directory.
# This affects `expandable?` to return `false` when this set to `true`.
def initialize(path, nested: false)
raise(ArgumentError, "Given path must be a directory path - #{path}") unless File.directory?(path)
@path = path
@language = self.class.available_languages.find { |lang| basename.casecmp?(lang) }
@nested = nested
end
def nested?
@nested
end
def valid?
self.class.allowed_directory_names_with_case.any? { |name| name.casecmp?(basename) }
end
def expandable?
!nested? && EXPANDABLE_DIR_NAMES.any? { |name| name.casecmp?(basename) }
end
def skip?
EXCEPTION_DIRECTORIES.map(&:downcase).include?(basename.downcase)
end
def file_paths(extensions = '{png,jpg,jpeg}')
Dir.glob(File.join(path, "*.#{extensions}"), File::FNM_CASEFOLD).sort
end
def framed_file_paths(extensions = '{png,jpg,jpeg}')
Dir.glob(File.join(path, "*_framed.#{extensions}"), File::FNM_CASEFOLD).sort
end
def basename
File.basename(@path)
end
end
# Returns the list of valid app screenshot. When detecting invalid screenshots, this will cause an error.
#
# @param root [String] A directory path
# @param ignore_validation [String] Set false not to raise the error when finding invalid folder name
# @return [Array<Deliver::AppScreenshot>] The list of AppScreenshot that exist under given `root` directory
def self.load_app_screenshots(root, ignore_validation)
screenshots = language_folders(root, ignore_validation, true).flat_map do |language_folder|
paths = if language_folder.framed_file_paths.count > 0
UI.important("Framed screenshots are detected! 🖼 Non-framed screenshot files may be skipped. 🏃")
# watchOS screenshots can be picked up even when framed ones were found since frameit doesn't support watchOS screenshots
framed_or_watch, skipped = language_folder.file_paths.partition { |path| path.downcase.include?('framed') || path.downcase.include?('watch') }
skipped.each { |path| UI.important("🏃 Skipping screenshot file: #{path}") }
framed_or_watch
else
language_folder.file_paths
end
paths.map { |path| AppScreenshot.new(path, language_folder.language) }
end
errors = []
valid_screenshots = screenshots.select { |screenshot| Deliver::AppScreenshotValidator.validate(screenshot, errors) }
unless errors.empty?
UI.important("🚫 Invalid screenshots were detected! Here are the reasons:")
errors.each { |error| UI.error(error) }
UI.user_error!("Canceled uploading screenshots. Please check the error messages above and fix the screenshots.")
end
valid_screenshots
end
# Returns the list of language folders
#
# @param roort [String] A directory path to get the list of language folders
# @param ignore_validation [Boolean] Set false not to raise the error when finding invalid folder name
# @param expand_sub_folders [Boolean] Set true to expand special folders; such as "iMessage" to nested language folders
# @return [Array<LanguageFolder>] The list of LanguageFolder whose each of them
def self.language_folders(root, ignore_validation, expand_sub_folders = false)
folders = Dir.glob(File.join(root, '*'))
.select { |path| File.directory?(path) }
.map { |path| LanguageFolder.new(path, nested: false) }
.reject(&:skip?)
selected_folders, rejected_folders = folders.partition(&:valid?)
if !ignore_validation && !rejected_folders.empty?
rejected_folders = rejected_folders.map(&:basename)
UI.user_error!("Unsupported directory name(s) for screenshots/metadata in '#{root}': #{rejected_folders.join(', ')}" \
"\nValid directory names are: #{LanguageFolder.allowed_directory_names_with_case}" \
"\n\nEnable 'ignore_language_directory_validation' to prevent this validation from happening")
end
# Expand selected_folders for the special directories
if expand_sub_folders
selected_folders = selected_folders.flat_map do |folder|
if folder.expandable?
Dir.glob(File.join(folder.path, '*'))
.select { |p| File.directory?(p) }
.map { |p| LanguageFolder.new(p, nested: true) }
.select(&:valid?)
else
folder
end
end
end
selected_folders
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/generate_summary.rb | deliver/lib/deliver/generate_summary.rb | require_relative 'upload_metadata'
require_relative 'html_generator'
require_relative 'upload_screenshots'
module Deliver
class GenerateSummary
def run(options)
screenshots = UploadScreenshots.new.collect_screenshots(options)
UploadMetadata.new(options).load_from_filesystem
HtmlGenerator.new.render(options, screenshots, '.')
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/app_screenshot_iterator.rb | deliver/lib/deliver/app_screenshot_iterator.rb | require_relative 'module'
module Deliver
# This is a convenient class that enumerates app store connect's screenshots in various degrees.
class AppScreenshotIterator
NUMBER_OF_THREADS = Helper.test? ? 1 : [ENV.fetch("DELIVER_NUMBER_OF_THREADS", 10).to_i, 10].min
# @param localizations [Array<Spaceship::ConnectAPI::AppStoreVersionLocalization>]
def initialize(localizations)
@localizations = localizations
end
# Iterate app_screenshot_set over localizations
#
# @yield [localization, app_screenshot_set]
# @yieldparam [optional, Spaceship::ConnectAPI::AppStoreVersionLocalization] localization
# @yieldparam [optional, Spaceship::ConnectAPI::AppStoreScreenshotSet] app_screenshot_set
def each_app_screenshot_set(localizations = @localizations, &block)
return enum_for(__method__, localizations) unless block_given?
# Collect app_screenshot_sets from localizations in parallel but
# limit the number of threads working at a time with using `lazy` and `force` controls
# to not attack App Store Connect
results = localizations.each_slice(NUMBER_OF_THREADS).lazy.map do |localizations_grouped|
localizations_grouped.map do |localization|
Thread.new do
[localization, localization.get_app_screenshot_sets]
end
end
end.flat_map do |threads|
threads.map { |t| t.join.value }
end.force
results.each do |localization, app_screenshot_sets|
app_screenshot_sets.each do |app_screenshot_set|
yield(localization, app_screenshot_set)
end
end
end
# Iterate app_screenshot over localizations and app_screenshot_sets
#
# @yield [localization, app_screenshot_set, app_screenshot]
# @yieldparam [optional, Spaceship::ConnectAPI::AppStoreVersionLocalization] localization
# @yieldparam [optional, Spaceship::ConnectAPI::AppStoreScreenshotSet] app_screenshot_set
# @yieldparam [optional, Spaceship::ConnectAPI::AppStoreScreenshot] app_screenshot
def each_app_screenshot(&block)
return enum_for(__method__) unless block_given?
each_app_screenshot_set do |localization, app_screenshot_set|
app_screenshot_set.app_screenshots.each do |app_screenshot|
yield(localization, app_screenshot_set, app_screenshot)
end
end
end
# Iterate given local app_screenshot over localizations and app_screenshot_sets
#
# @param screenshots_per_language [Hash<String, Array<Deliver::AppScreenshot>]
# @yield [localization, app_screenshot_set, app_screenshot]
# @yieldparam [optional, Spaceship::ConnectAPI::AppStoreVersionLocalization] localization
# @yieldparam [optional, Spaceship::ConnectAPI::AppStoreScreenshotSet] app_screenshot_set
# @yieldparam [optional, Deliver::AppScreenshot] screenshot
# @yieldparam [optional, Integer] index a number represents which position the screenshot will be
def each_local_screenshot(screenshots_per_language, &block)
return enum_for(__method__, screenshots_per_language) unless block_given?
# filter unnecessary localizations
supported_localizations = @localizations.reject { |l| screenshots_per_language[l.locale].nil? }
# build a hash that can access app_screenshot_set corresponding to given locale and display_type
# via parallelized each_app_screenshot_set to gain performance
app_screenshot_set_per_locale_and_display_type = each_app_screenshot_set(supported_localizations)
.each_with_object({}) do |(localization, app_screenshot_set), hash|
hash[localization.locale] ||= {}
hash[localization.locale][app_screenshot_set.screenshot_display_type] = app_screenshot_set
end
# iterate over screenshots per localization
screenshots_per_language.each do |language, screenshots_for_language|
localization = supported_localizations.find { |l| l.locale == language }
screenshots_per_display_type = screenshots_for_language.reject { |screenshot| screenshot.display_type.nil? }.group_by(&:display_type)
screenshots_per_display_type.each do |display_type, screenshots|
# create AppScreenshotSet for given display_type if it doesn't exist
UI.verbose("Setting up screenshot set for #{language}, #{display_type}")
app_screenshot_set = (app_screenshot_set_per_locale_and_display_type[language] || {})[display_type]
app_screenshot_set ||= localization.create_app_screenshot_set(attributes: { screenshotDisplayType: display_type })
# iterate over screenshots per display size with index
screenshots.each.with_index do |screenshot, index|
yield(localization, app_screenshot_set, screenshot, index)
end
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/sync_screenshots.rb | deliver/lib/deliver/sync_screenshots.rb | require 'fastlane_core'
require 'digest/md5'
require 'naturally'
require_relative 'app_screenshot'
require_relative 'app_screenshot_iterator'
require_relative 'loader'
require_relative 'screenshot_comparable'
module Deliver
class SyncScreenshots
DeleteScreenshotJob = Struct.new(:app_screenshot, :locale)
UploadScreenshotJob = Struct.new(:app_screenshot_set, :path)
class UploadResult
attr_reader :asset_delivery_state_counts, :failing_screenshots
def initialize(asset_delivery_state_counts:, failing_screenshots:)
@asset_delivery_state_counts = asset_delivery_state_counts
@failing_screenshots = failing_screenshots
end
def processing?
@asset_delivery_state_counts.fetch('UPLOAD_COMPLETE', 0) > 0
end
def screenshot_count
@asset_delivery_state_counts.fetch('COMPLETE', 0)
end
end
def initialize(app:, platform:)
@app = app
@platform = platform
end
def sync_from_path(screenshots_path)
# load local screenshots
screenshots = Deliver::Loader.load_app_screenshots(screenshots_path, true)
sync(screenshots)
end
def sync(screenshots)
UI.important('This is currently a beta feature in fastlane. This may cause some errors on your environment.')
unless FastlaneCore::Feature.enabled?('FASTLANE_ENABLE_BETA_DELIVER_SYNC_SCREENSHOTS')
UI.user_error!('Please set a value to "FASTLANE_ENABLE_BETA_DELIVER_SYNC_SCREENSHOTS" environment variable ' \
'if you acknowledge the risk and try this out.')
end
UI.important("Will begin uploading snapshots for '#{version.version_string}' on App Store Connect")
# enable localizations that will be used
screenshots_per_language = screenshots.group_by(&:language)
enable_localizations(screenshots_per_language.keys)
# create iterator
localizations = fetch_localizations
iterator = Deliver::AppScreenshotIterator.new(localizations)
# sync local screenshots with remote settings by deleting and uploading
UI.message("Starting with the upload of screenshots...")
replace_screenshots(iterator, screenshots)
# ensure screenshots within screenshot sets are sorted in right order
sort_screenshots(iterator)
UI.important('Screenshots are synced successfully!')
end
def enable_localizations(locales)
localizations = fetch_localizations
locales_to_enable = locales - localizations.map(&:locale)
Helper.show_loading_indicator("Activating localizations for #{locales_to_enable.join(', ')}...")
locales_to_enable.each do |locale|
version.create_app_store_version_localization(attributes: { locale: locale })
end
Helper.hide_loading_indicator
end
def replace_screenshots(iterator, screenshots, retries = 3)
# delete and upload screenshots to get App Store Connect in sync
do_replace_screenshots(iterator, screenshots, create_delete_worker, create_upload_worker)
# wait for screenshots to be processed on App Store Connect end and
# ensure the number of uploaded screenshots matches the one in local
result = wait_for_complete(iterator)
return if !result.processing? && result.screenshot_count == screenshots.count
if retries.zero?
UI.crash!("Retried uploading screenshots #{retries} but there are still failures of processing screenshots." \
"Check App Store Connect console to work out which screenshots processed unsuccessfully.")
end
# retry with deleting failing screenshots
result.failing_screenshots.each(&:delete!)
replace_screenshots(iterator, screenshots, retries - 1)
end
# This is a testable method that focuses on figuring out what to update
def do_replace_screenshots(iterator, screenshots, delete_worker, upload_worker)
remote_screenshots = iterator.each_app_screenshot.map do |localization, app_screenshot_set, app_screenshot|
ScreenshotComparable.create_from_remote(app_screenshot: app_screenshot, locale: localization.locale)
end
local_screenshots = iterator.each_local_screenshot(screenshots.group_by(&:language)).map do |localization, app_screenshot_set, screenshot, index|
if index >= 10
UI.user_error!("Found #{localization.locale} has more than 10 screenshots for #{app_screenshot_set.screenshot_display_type}. "\
"Make sure contains only necessary screenshots.")
end
ScreenshotComparable.create_from_local(screenshot: screenshot, app_screenshot_set: app_screenshot_set)
end
# Thanks to `Array#-` API and `ScreenshotComparable`, working out diffs between local screenshot directory and App Store Connect
# is as easy as you can see below. The former one finds what is missing in local and the latter one is visa versa.
screenshots_to_delete = remote_screenshots - local_screenshots
screenshots_to_upload = local_screenshots - remote_screenshots
delete_jobs = screenshots_to_delete.map { |x| DeleteScreenshotJob.new(x.context[:app_screenshot], x.context[:locale]) }
delete_worker.batch_enqueue(delete_jobs)
delete_worker.start
upload_jobs = screenshots_to_upload.map { |x| UploadScreenshotJob.new(x.context[:app_screenshot_set], x.context[:screenshot].path) }
upload_worker.batch_enqueue(upload_jobs)
upload_worker.start
end
def wait_for_complete(iterator)
retry_count = 0
Helper.show_loading_indicator("Waiting for all the screenshots processed...")
loop do
failing_screenshots = []
state_counts = iterator.each_app_screenshot.map { |_, _, app_screenshot| app_screenshot }.each_with_object({}) do |app_screenshot, hash|
state = app_screenshot.asset_delivery_state['state']
hash[state] ||= 0
hash[state] += 1
failing_screenshots << app_screenshot if app_screenshot.error?
end
result = UploadResult.new(asset_delivery_state_counts: state_counts, failing_screenshots: failing_screenshots)
return result unless result.processing?
# sleep with exponential backoff
interval = 5 + (2**retry_count)
UI.message("There are still incomplete screenshots. Will check the states again in #{interval} secs - #{state_counts}")
sleep(interval)
retry_count += 1
end
ensure
Helper.hide_loading_indicator
end
def sort_screenshots(iterator)
Helper.show_loading_indicator("Sorting screenshots uploaded...")
sort_worker = create_sort_worker
sort_worker.batch_enqueue(iterator.each_app_screenshot_set.to_a.map { |_, set| set })
sort_worker.start
Helper.hide_loading_indicator
end
private
def version
@version ||= @app.get_edit_app_store_version(platform: @platform)
end
def fetch_localizations
version.get_app_store_version_localizations
end
def create_upload_worker
FastlaneCore::QueueWorker.new do |job|
UI.verbose("Uploading '#{job.path}'...")
start_time = Time.now
job.app_screenshot_set.upload_screenshot(path: job.path, wait_for_processing: false)
UI.message("Uploaded '#{job.path}'... (#{Time.now - start_time} secs)")
end
end
def create_delete_worker
FastlaneCore::QueueWorker.new do |job|
target = "id=#{job.app_screenshot.id} #{job.locale} #{job.app_screenshot.file_name}"
UI.verbose("Deleting '#{target}'")
start_time = Time.now
job.app_screenshot.delete!
UI.message("Deleted '#{target}' - (#{Time.now - start_time} secs)")
end
end
def create_sort_worker
FastlaneCore::QueueWorker.new do |app_screenshot_set|
original_ids = app_screenshot_set.app_screenshots.map(&:id)
sorted_ids = Naturally.sort(app_screenshot_set.app_screenshots, by: :file_name).map(&:id)
if original_ids != sorted_ids
app_screenshot_set.reorder_screenshots(app_screenshot_ids: sorted_ids)
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/app_screenshot_validator.rb | deliver/lib/deliver/app_screenshot_validator.rb | require 'fastimage'
module Deliver
class AppScreenshotValidator
# A simple structure that holds error information as well as formatted error messages consistently
class ValidationError
# Constants that can be given to `type` param
INVALID_SCREEN_SIZE = 'Invalid screen size'.freeze
INVALID_FILE_EXTENSION = 'Invalid file extension'.freeze
FILE_EXTENSION_MISMATCH = 'File extension mismatches its image format'.freeze
attr_reader :type, :path, :debug_info
def initialize(type: nil, path: nil, debug_info: nil)
@type = type
@path = path
@debug_info = debug_info
end
def to_s
"🚫 Error: #{path} - #{type} (#{debug_info})"
end
def inspect
"\"#{type}\""
end
end
# Access each array by symbol returned from FastImage.type
ALLOWED_SCREENSHOT_FILE_EXTENSION = { png: ['png', 'PNG'], jpeg: ['jpg', 'JPG', 'jpeg', 'JPEG'] }.freeze
APP_SCREENSHOT_SPEC_URL = 'https://help.apple.com/app-store-connect/#/devd274dd925'.freeze
# Validate a screenshot and inform an error message via `errors` parameter. `errors` is mutated
# to append the messages and each message should contain the corresponding path to let users know which file is throwing the error.
#
# @param screenshot [AppScreenshot]
# @param errors [Array<Deliver::AppScreenshotValidator::ValidationError>] Pass an array object to add validation errors when detecting errors.
# This will be mutated to add more error objects as validation detects errors.
# @return [Boolean] true if given screenshot is valid
def self.validate(screenshot, errors)
# Given screenshot will be diagnosed and errors found are accumulated
errors_found = []
validate_screen_size(screenshot, errors_found)
validate_file_extension_and_format(screenshot, errors_found)
# Merge errors found into given errors array
errors_found.each { |error| errors.push(error) }
errors_found.empty?
end
def self.validate_screen_size(screenshot, errors_found)
if screenshot.display_type.nil?
errors_found << ValidationError.new(type: ValidationError::INVALID_SCREEN_SIZE,
path: screenshot.path,
debug_info: "Screenshot size is not supported. Actual size is #{get_formatted_size(screenshot)}. See the specifications to fix #{APP_SCREENSHOT_SPEC_URL}")
end
end
def self.validate_file_extension_and_format(screenshot, errors_found)
extension = File.extname(screenshot.path).delete('.')
valid_file_extensions = ALLOWED_SCREENSHOT_FILE_EXTENSION.values.flatten
is_valid_extension = valid_file_extensions.include?(extension)
unless is_valid_extension
errors_found << ValidationError.new(type: ValidationError::INVALID_FILE_EXTENSION,
path: screenshot.path,
debug_info: "Only #{valid_file_extensions.join(', ')} are allowed")
end
format = FastImage.type(screenshot.path)
is_extension_matched = ALLOWED_SCREENSHOT_FILE_EXTENSION[format] &&
ALLOWED_SCREENSHOT_FILE_EXTENSION[format].include?(extension)
# This error only appears when file extension is valid
if is_valid_extension && !is_extension_matched
expected_extension = ALLOWED_SCREENSHOT_FILE_EXTENSION[format].first
expected_filename = File.basename(screenshot.path, File.extname(screenshot.path)) + ".#{expected_extension}"
errors_found << ValidationError.new(type: ValidationError::FILE_EXTENSION_MISMATCH,
path: screenshot.path,
debug_info: %(Actual format is "#{format}". Rename the filename to "#{expected_filename}".))
end
end
def self.get_formatted_size(screenshot)
size = FastImage.size(screenshot.path)
return size.join('x') if size
nil
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/app_screenshot.rb | deliver/lib/deliver/app_screenshot.rb | require 'fastimage'
require_relative 'module'
require 'spaceship/connect_api/models/app_screenshot_set'
module Deliver
# AppScreenshot represents one screenshots for one specific locale and
# device type.
class AppScreenshot
# Shorthand for DisplayType constants
DisplayType = Spaceship::ConnectAPI::AppScreenshotSet::DisplayType
FORMATTED_NAMES = {
DisplayType::APP_IPHONE_35 => "iPhone 4",
DisplayType::APP_IPHONE_40 => "iPhone 5",
DisplayType::APP_IPHONE_47 => "iPhone 6",
DisplayType::APP_IPHONE_55 => "iPhone 6 Plus",
DisplayType::APP_IPHONE_58 => "iPhone XS",
DisplayType::APP_IPHONE_61 => "iPhone 14 Pro",
DisplayType::APP_IPHONE_65 => "iPhone XS Max",
DisplayType::APP_IPHONE_67 => "iPhone 14 Pro Max",
DisplayType::APP_IPAD_97 => "iPad",
DisplayType::APP_IPAD_105 => "iPad 10.5",
DisplayType::APP_IPAD_PRO_3GEN_11 => "iPad 11",
DisplayType::APP_IPAD_PRO_129 => "iPad Pro",
DisplayType::APP_IPAD_PRO_3GEN_129 => "iPad Pro (12.9-inch) (3rd generation)",
DisplayType::IMESSAGE_APP_IPHONE_40 => "iPhone 5 (iMessage)",
DisplayType::IMESSAGE_APP_IPHONE_47 => "iPhone 6 (iMessage)",
DisplayType::IMESSAGE_APP_IPHONE_55 => "iPhone 6 Plus (iMessage)",
DisplayType::IMESSAGE_APP_IPHONE_58 => "iPhone XS (iMessage)",
DisplayType::IMESSAGE_APP_IPHONE_61 => "iPhone 14 Pro (iMessage)",
DisplayType::IMESSAGE_APP_IPHONE_65 => "iPhone XS Max (iMessage)",
DisplayType::IMESSAGE_APP_IPHONE_67 => "iPhone 14 Pro Max (iMessage)",
DisplayType::IMESSAGE_APP_IPAD_97 => "iPad (iMessage)",
DisplayType::IMESSAGE_APP_IPAD_PRO_129 => "iPad Pro (iMessage)",
DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_129 => "iPad Pro (12.9-inch) (3rd generation) (iMessage)",
DisplayType::IMESSAGE_APP_IPAD_105 => "iPad 10.5 (iMessage)",
DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_11 => "iPad 11 (iMessage)",
DisplayType::APP_DESKTOP => "Mac",
DisplayType::APP_WATCH_SERIES_3 => "Watch",
DisplayType::APP_WATCH_SERIES_4 => "Watch Series4",
DisplayType::APP_WATCH_SERIES_7 => "Watch Series7",
DisplayType::APP_WATCH_SERIES_10 => "Watch Series10",
DisplayType::APP_WATCH_ULTRA => "Watch Ultra",
DisplayType::APP_APPLE_TV => "Apple TV",
DisplayType::APP_APPLE_VISION_PRO => "Vision Pro"
}.freeze
# reference: https://help.apple.com/app-store-connect/#/devd274dd925
# Returns a hash mapping DisplayType constants to their supported resolutions.
DEVICE_RESOLUTIONS = {
# These are actually 6.9" iPhones
DisplayType::APP_IPHONE_67 => [
[1260, 2736],
[2736, 1260],
[1290, 2796],
[2796, 1290],
[1320, 2868],
[2868, 1320]
],
DisplayType::APP_IPHONE_65 => [
[1242, 2688],
[2688, 1242],
[1284, 2778],
[2778, 1284]
],
# These are actually 6.3" iPhones
DisplayType::APP_IPHONE_61 => [
[1179, 2556],
[2556, 1179],
[1206, 2622],
[2622, 1206]
],
# These are actually 6.1" iPhones
DisplayType::APP_IPHONE_58 => [
[1170, 2532],
[2532, 1170],
[1125, 2436],
[2436, 1125],
[1080, 2340],
[2340, 1080]
],
DisplayType::APP_IPHONE_55 => [
[1242, 2208],
[2208, 1242]
],
DisplayType::APP_IPHONE_47 => [
[750, 1334],
[1334, 750]
],
DisplayType::APP_IPHONE_40 => [
[640, 1096],
[640, 1136],
[1136, 600],
[1136, 640]
],
DisplayType::APP_IPHONE_35 => [
[640, 920],
[640, 960],
[960, 600],
[960, 640]
],
DisplayType::APP_IPAD_97 => [
[1024, 748],
[1024, 768],
[2048, 1496],
[2048, 1536],
[768, 1004],
[768, 1024],
[1536, 2008],
[1536, 2048]
],
DisplayType::APP_IPAD_105 => [
[1668, 2224],
[2224, 1668]
],
DisplayType::APP_IPAD_PRO_3GEN_11 => [
[1488, 2266],
[2266, 1488],
[1668, 2420],
[2420, 1668],
[1668, 2388],
[2388, 1668],
[1640, 2360],
[2360, 1640]
],
# These are 12.9" iPads
DisplayType::APP_IPAD_PRO_129 => [
[2048, 2732],
[2732, 2048]
],
# These are actually 13" iPads
DisplayType::APP_IPAD_PRO_3GEN_129 => [
[2048, 2732],
[2732, 2048],
[2064, 2752],
[2752, 2064]
],
DisplayType::APP_DESKTOP => [
[1280, 800],
[1440, 900],
[2560, 1600],
[2880, 1800]
],
DisplayType::APP_WATCH_SERIES_3 => [
[312, 390]
],
DisplayType::APP_WATCH_SERIES_4 => [
[368, 448]
],
DisplayType::APP_WATCH_SERIES_7 => [
[396, 484]
],
DisplayType::APP_WATCH_SERIES_10 => [
[416, 496]
],
DisplayType::APP_WATCH_ULTRA => [
[410, 502],
[422, 514]
],
DisplayType::APP_APPLE_TV => [
[1920, 1080],
[3840, 2160]
],
DisplayType::APP_APPLE_VISION_PRO => [
[3840, 2160]
]
}.freeze
DEVICE_RESOLUTIONS_MESSAGES = {
DisplayType::IMESSAGE_APP_IPHONE_40 => DEVICE_RESOLUTIONS[DisplayType::APP_IPHONE_40],
DisplayType::IMESSAGE_APP_IPHONE_47 => DEVICE_RESOLUTIONS[DisplayType::APP_IPHONE_47],
DisplayType::IMESSAGE_APP_IPHONE_55 => DEVICE_RESOLUTIONS[DisplayType::APP_IPHONE_55],
DisplayType::IMESSAGE_APP_IPHONE_58 => DEVICE_RESOLUTIONS[DisplayType::APP_IPHONE_58],
DisplayType::IMESSAGE_APP_IPHONE_61 => DEVICE_RESOLUTIONS[DisplayType::APP_IPHONE_61],
DisplayType::IMESSAGE_APP_IPHONE_65 => DEVICE_RESOLUTIONS[DisplayType::APP_IPHONE_65],
DisplayType::IMESSAGE_APP_IPHONE_67 => DEVICE_RESOLUTIONS[DisplayType::APP_IPHONE_67],
DisplayType::IMESSAGE_APP_IPAD_97 => DEVICE_RESOLUTIONS[DisplayType::APP_IPAD_97],
DisplayType::IMESSAGE_APP_IPAD_105 => DEVICE_RESOLUTIONS[DisplayType::APP_IPAD_105],
DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_11 => DEVICE_RESOLUTIONS[DisplayType::APP_IPAD_PRO_3GEN_11],
DisplayType::IMESSAGE_APP_IPAD_PRO_129 => DEVICE_RESOLUTIONS[DisplayType::APP_IPAD_PRO_129],
DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_129 => DEVICE_RESOLUTIONS[DisplayType::APP_IPAD_PRO_3GEN_129]
}.freeze
# Resolutions that are shared by multiple device types
CONFLICTING_RESOLUTIONS = [
# iPad Pro 12.9" (2nd gen) and iPad Pro 13" (3rd+ gen)
[2048, 2732],
[2732, 2048],
# Apple TV and Apple Vision Pro
[3840, 2160]
].freeze
# @return [Spaceship::ConnectAPI::AppScreenshotSet::DisplayType] the display type
attr_accessor :display_type
attr_accessor :path
attr_accessor :language
# @param path (String) path to the screenshot file
# @param language (String) Language of this screenshot (e.g. English)
def initialize(path, language)
self.path = path
self.language = language
self.display_type = self.class.calculate_display_type(path)
end
# Nice name
def formatted_name
return FORMATTED_NAMES[self.display_type]
end
# Validates the given screenshots (size and format)
def is_valid?
UI.deprecated('Deliver::AppScreenshot#is_valid? is deprecated in favor of Deliver::AppScreenshotValidator')
return false unless ["png", "PNG", "jpg", "JPG", "jpeg", "JPEG"].include?(self.path.split(".").last)
return self.display_type == self.class.calculate_display_type(self.path)
end
def is_messages?
# rubocop:disable Require/MissingRequireStatement
return DisplayType::ALL_IMESSAGE.include?(self.display_type)
# rubocop:enable Require/MissingRequireStatement
end
def self.calculate_display_type(path)
size = FastImage.size(path)
UI.user_error!("Could not find or parse file at path '#{path}'") if size.nil? || size.count == 0
path_component = Pathname.new(path).each_filename.to_a[-3]
is_imessage = path_component.eql?("iMessage")
devices = is_imessage ? DEVICE_RESOLUTIONS_MESSAGES : DEVICE_RESOLUTIONS
matching_display_type = devices.find { |_display_type, resolutions| resolutions.include?(size) }&.first
return nil unless matching_display_type
return matching_display_type unless CONFLICTING_RESOLUTIONS.include?(size)
path_lower = path.downcase
case size
# iPad Pro conflict
when [2048, 2732], [2732, 2048]
is_2gen = path_lower.include?("app_ipad_pro_129") ||
(path_lower.include?("12.9") && path_lower.include?("2nd generation")) # e.g. iPad Pro (12.9-inch) (2nd generation)
# rubocop:disable Require/MissingRequireStatement
if is_2gen
return is_imessage ? DisplayType::IMESSAGE_APP_IPAD_PRO_129 : DisplayType::APP_IPAD_PRO_129
else
return is_imessage ? DisplayType::IMESSAGE_APP_IPAD_PRO_3GEN_129 : DisplayType::APP_IPAD_PRO_3GEN_129
end
# Apple TV vs Vision Pro conflict
when [3840, 2160]
return path_lower.include?("vision") ? DisplayType::APP_APPLE_VISION_PRO : DisplayType::APP_APPLE_TV
# rubocop:enable Require/MissingRequireStatement
else
matching_display_type
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/commands_generator.rb | deliver/lib/deliver/commands_generator.rb | require 'commander'
require 'fastlane/version'
require 'fastlane_core/ui/help_formatter'
require_relative 'download_screenshots'
require_relative 'options'
require_relative 'module'
require_relative 'generate_summary'
require_relative 'runner'
HighLine.track_eof = false
module Deliver
class CommandsGenerator
include Commander::Methods
def self.start
self.new.run
end
def deliverfile_options(skip_verification: false)
available_options = Deliver::Options.available_options
return available_options unless skip_verification
# These don't matter for downloading metadata, so verification can be skipped
irrelevant_options_keys = [:ipa, :pkg, :app_rating_config_path]
available_options.each do |opt|
next unless irrelevant_options_keys.include?(opt.key)
opt.verify_block = nil
opt.conflicting_options = nil
end
return available_options
end
def self.force_overwrite_metadata?(options, path)
res = options[:force]
res ||= ENV["DELIVER_FORCE_OVERWRITE"] # for backward compatibility
res ||= UI.confirm("Do you want to overwrite existing metadata on path '#{File.expand_path(path)}'?") if UI.interactive?
res
end
# rubocop:disable Metrics/PerceivedComplexity
def run
program :name, 'deliver'
program :version, Fastlane::VERSION
program :description, Deliver::DESCRIPTION
program :help, 'Author', 'Felix Krause <deliver@krausefx.com>'
program :help, 'Website', 'https://fastlane.tools'
program :help, 'Documentation', 'https://docs.fastlane.tools/actions/deliver/'
program :help_formatter, FastlaneCore::HelpFormatter
global_option('--verbose') { FastlaneCore::Globals.verbose = true }
global_option('--env STRING[,STRING2]', String, 'Add environment(s) to use with `dotenv`')
always_trace!
command :run do |c|
c.syntax = 'fastlane deliver'
c.description = 'Upload metadata and binary to App Store Connect'
FastlaneCore::CommanderGenerator.new.generate(deliverfile_options, command: c)
c.action do |args, options|
options = FastlaneCore::Configuration.create(deliverfile_options, options.__hash__)
loaded = options.load_configuration_file("Deliverfile")
# Check if we already have a deliver setup in the current directory
loaded = true if options[:description] || options[:ipa] || options[:pkg]
loaded = true if File.exist?(File.join(FastlaneCore::FastlaneFolder.path || ".", "metadata"))
unless loaded
if UI.confirm("No deliver configuration found in the current directory. Do you want to setup deliver?")
is_swift = UI.confirm("Would you like to use Swift instead of Ruby?")
require 'deliver/setup'
Deliver::Runner.new(options) # to login...
Deliver::Setup.new.run(options, is_swift: is_swift)
return 0
end
end
Deliver::Runner.new(options).run
end
end
command :submit_build do |c|
c.syntax = 'fastlane deliver submit_build'
c.description = 'Submit a specific build-nr for review, use latest for the latest build'
FastlaneCore::CommanderGenerator.new.generate(deliverfile_options, command: c)
c.action do |args, options|
options = FastlaneCore::Configuration.create(deliverfile_options, options.__hash__)
options.load_configuration_file("Deliverfile")
options[:submit_for_review] = true
options[:build_number] = "latest" unless options[:build_number]
Deliver::Runner.new(options).run
end
end
command :init do |c|
c.syntax = 'fastlane deliver init'
c.description = 'Create the initial `deliver` configuration based on an existing app'
FastlaneCore::CommanderGenerator.new.generate(deliverfile_options, command: c)
c.action do |args, options|
if File.exist?("Deliverfile") || File.exist?("fastlane/Deliverfile")
UI.important("You already have a running deliver setup in this directory")
return 0
end
require 'deliver/setup'
options = FastlaneCore::Configuration.create(deliverfile_options, options.__hash__)
options[:run_precheck_before_submit] = false # precheck doesn't need to run during init
Deliver::Runner.new(options) # to login...
Deliver::Setup.new.run(options)
end
end
command :generate_summary do |c|
c.syntax = 'fastlane deliver generate_summary'
c.description = 'Generate HTML Summary without uploading/downloading anything'
FastlaneCore::CommanderGenerator.new.generate(deliverfile_options, command: c)
c.action do |args, options|
options = FastlaneCore::Configuration.create(deliverfile_options, options.__hash__)
options.load_configuration_file("Deliverfile")
Deliver::Runner.new(options)
html_path = Deliver::GenerateSummary.new.run(options)
UI.success("Successfully generated HTML report at '#{html_path}'")
system("open '#{html_path}'") unless options[:force]
end
end
command :download_screenshots do |c|
c.syntax = 'fastlane deliver download_screenshots'
c.description = "Downloads all existing screenshots from App Store Connect and stores them in the screenshots folder"
FastlaneCore::CommanderGenerator.new.generate(deliverfile_options, command: c)
c.action do |args, options|
options = FastlaneCore::Configuration.create(deliverfile_options(skip_verification: true), options.__hash__)
options.load_configuration_file("Deliverfile")
Deliver::Runner.new(options, skip_version: true) # to login...
containing = FastlaneCore::Helper.fastlane_enabled_folder_path
path = options[:screenshots_path] || File.join(containing, 'screenshots')
Deliver::DownloadScreenshots.run(options, path)
end
end
command :download_metadata do |c|
c.syntax = 'fastlane deliver download_metadata'
c.description = "Downloads existing metadata and stores it locally. This overwrites the local files."
FastlaneCore::CommanderGenerator.new.generate(deliverfile_options, command: c)
c.action do |args, options|
options = FastlaneCore::Configuration.create(deliverfile_options(skip_verification: true), options.__hash__)
options.load_configuration_file("Deliverfile")
Deliver::Runner.new(options) # to login...
containing = FastlaneCore::Helper.fastlane_enabled_folder_path
path = options[:metadata_path] || File.join(containing, 'metadata')
res = Deliver::CommandsGenerator.force_overwrite_metadata?(options, path)
return 0 unless res
require 'deliver/setup'
app = Deliver.cache[:app]
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
v = app.get_latest_app_store_version(platform: platform)
if options[:app_version].to_s.length > 0
v = app.get_live_app_store_version(platform: platform) if v.version_string != options[:app_version]
if v.nil? || v.version_string != options[:app_version]
raise "Neither the current nor live version match specified app_version \"#{options[:app_version]}\""
end
end
Deliver::Setup.new.generate_metadata_files(app, v, path, options)
end
end
default_command(:run)
run!
end
# rubocop:enable Metrics/PerceivedComplexity
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/upload_price_tier.rb | deliver/lib/deliver/upload_price_tier.rb | require_relative 'module'
require 'spaceship'
module Deliver
# Set the app's pricing
class UploadPriceTier
def upload(options)
return unless options[:price_tier]
price_tier = options[:price_tier].to_s
app = Deliver.cache[:app]
attributes = {}
# Check App update method to understand how to use territory_ids.
territory_ids = nil # nil won't update app's territory_ids, empty array would remove app from sale.
# As of 2020-09-14:
# Official App Store Connect does not have an endpoint to get app prices for an app
# Need to get prices from the app's relationships
# Prices from app's relationship does not have price tier so need to fetch app price with price tier relationship
app_prices = app.prices
if app_prices&.first
app_price = Spaceship::ConnectAPI.get_app_price(app_price_id: app_prices.first.id, includes: "priceTier").first
old_price = app_price.price_tier.id
else
UI.message("App has no prices yet... Enabling all countries in App Store Connect")
territory_ids = Spaceship::ConnectAPI::Territory.all.map(&:id)
attributes[:availableInNewTerritories] = true
end
if price_tier == old_price
UI.success("Price Tier unchanged (tier #{old_price})")
return
end
app.update(attributes: attributes, app_price_tier_id: price_tier, territory_ids: territory_ids)
UI.success("Successfully updated the pricing from #{old_price} to #{price_tier}")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/submit_for_review.rb | deliver/lib/deliver/submit_for_review.rb | require_relative 'module'
require 'fastlane_core/build_watcher'
require 'fastlane_core/ipa_file_analyser'
require 'fastlane_core/pkg_file_analyser'
module Deliver
class SubmitForReview
def submit!(options)
app = Deliver.cache[:app]
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
version = app.get_edit_app_store_version(platform: platform)
unless version
UI.user_error!("Cannot submit for review - could not find an editable version for '#{platform}'")
return
end
build = select_build(options, app, version, platform)
update_export_compliance(options, app, build)
update_submission_information(options, app)
create_review_submission(options, app, version, platform)
UI.success("Successfully submitted the app for review!")
end
private
def create_review_submission(options, app, version, platform)
# Can't submit a review if there is already a review in progress
if app.get_in_progress_review_submission(platform: platform)
UI.user_error!("Cannot submit for review - A review submission is already in progress")
end
# There can only be one open submission per platform per app
# There might be a submission already created so we need to check
# 1. Create the submission if its not already created
# 2. Error if submission already contains some items for review (because we don't know what they are)
submission = app.get_ready_review_submission(platform: platform, includes: "items")
if submission.nil?
submission = app.create_review_submission(platform: platform)
elsif !submission.items.empty?
UI.user_error!("Cannot submit for review - A review submission already exists with items not managed by fastlane. Please cancel or remove items from submission for the App Store Connect website")
end
submission.add_app_store_version_to_review_items(app_store_version_id: version.id)
10.times do
version_with_latest_info = Spaceship::ConnectAPI::AppStoreVersion.get(app_store_version_id: version.id)
if version_with_latest_info.app_version_state == Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::READY_FOR_REVIEW
break
end
UI.message("Waiting for the state of the version to become #{Spaceship::ConnectAPI::AppStoreVersion::AppVersionState::READY_FOR_REVIEW}...")
sleep(15)
end
submission.submit_for_review
end
def select_build(options, app, version, platform)
if options[:build_number] && options[:build_number] != "latest"
UI.message("Selecting existing build-number: #{options[:build_number]}")
build = Spaceship::ConnectAPI::Build.all(
app_id: app.id,
version: options[:app_version],
build_number: options[:build_number],
platform: platform
).first
unless build
UI.user_error!("Build number: #{options[:build_number]} does not exist")
end
else
UI.message("Selecting the latest build...")
build = wait_for_build_processing_to_be_complete(app: app, platform: platform, options: options)
end
UI.message("Selecting build #{build.app_version} (#{build.version})...")
version.select_build(build_id: build.id)
UI.success("Successfully selected build")
return build
end
def update_export_compliance(options, app, build)
submission_information = options[:submission_information] || {}
submission_information = submission_information.transform_keys(&:to_sym)
uses_encryption = submission_information[:export_compliance_uses_encryption]
if build.uses_non_exempt_encryption.nil?
UI.verbose("Updating build for export compliance status of '#{uses_encryption}'")
if uses_encryption.to_s.empty?
message = [
"Export compliance is required to submit",
"Add information to the :submission_information option...",
" Docs: http://docs.fastlane.tools/actions/deliver/#compliance-and-idfa-settings",
" Example: submission_information: { export_compliance_uses_encryption: false }",
" Example CLI:",
" --submission_information \"{\\\"export_compliance_uses_encryption\\\": false}\"",
"This can also be set in your Info.plist with key 'ITSAppUsesNonExemptEncryption'"
].join("\n")
UI.user_error!(message)
end
build = build.update(attributes: {
usesNonExemptEncryption: uses_encryption
})
UI.verbose("Successfully updated build for export compliance status of '#{build.uses_non_exempt_encryption}' on App Store Connect")
end
end
def update_submission_information(options, app)
submission_information = options[:submission_information] || {}
submission_information = submission_information.transform_keys(&:to_sym)
content_rights = submission_information[:content_rights_contains_third_party_content]
unless content_rights.nil?
value = if content_rights
Spaceship::ConnectAPI::App::ContentRightsDeclaration::USES_THIRD_PARTY_CONTENT
else
Spaceship::ConnectAPI::App::ContentRightsDeclaration::DOES_NOT_USE_THIRD_PARTY_CONTENT
end
UI.verbose("Updating contents rights declaration on App Store Connect")
app.update(attributes: {
contentRightsDeclaration: value
})
UI.success("Successfully updated contents rights declaration on App Store Connect")
end
end
def wait_for_build_processing_to_be_complete(app: nil, platform: nil, options: nil)
app_version = options[:app_version]
app_version ||= FastlaneCore::IpaFileAnalyser.fetch_app_version(options[:ipa]) if options[:ipa]
app_version ||= FastlaneCore::PkgFileAnalyser.fetch_app_version(options[:pkg]) if options[:pkg]
app_build ||= FastlaneCore::IpaFileAnalyser.fetch_app_build(options[:ipa]) if options[:ipa]
app_build ||= FastlaneCore::PkgFileAnalyser.fetch_app_build(options[:pkg]) if options[:pkg]
latest_build = FastlaneCore::BuildWatcher.wait_for_build_processing_to_be_complete(
app_id: app.id,
platform: platform,
app_version: app_version,
build_version: app_build,
poll_interval: 15,
return_when_build_appears: false,
return_spaceship_testflight_build: false,
select_latest: true
)
if !app_version.nil? && !app_build.nil?
unless latest_build.app_version == app_version && latest_build.version == app_build
UI.important("Uploaded app #{app_version} - #{app_build}, but received build #{latest_build.app_version} - #{latest_build.version}.")
end
end
return latest_build
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/runner.rb | deliver/lib/deliver/runner.rb | require 'precheck/options'
require 'precheck/runner'
require 'fastlane_core/configuration/configuration'
require 'fastlane_core/ipa_upload_package_builder'
require 'fastlane_core/pkg_upload_package_builder'
require 'fastlane_core/itunes_transporter'
require 'spaceship'
require_relative 'html_generator'
require_relative 'submit_for_review'
require_relative 'upload_price_tier'
require_relative 'upload_metadata'
require_relative 'upload_screenshots'
require_relative 'sync_screenshots'
require_relative 'detect_values'
module Deliver
class Runner
attr_accessor :options
def initialize(options, skip_auto_detection = {})
self.options = options
login
Deliver::DetectValues.new.run!(self.options, skip_auto_detection)
FastlaneCore::PrintTable.print_values(config: options, hide_keys: [:app], mask_keys: ['app_review_information.demo_password'], title: "deliver #{Fastlane::VERSION} Summary")
end
def login
if (api_token = Spaceship::ConnectAPI::Token.from(hash: options[:api_key], filepath: options[:api_key_path]))
UI.message("Creating authorization token for App Store Connect API")
Spaceship::ConnectAPI.token = api_token
elsif !Spaceship::ConnectAPI.token.nil?
UI.message("Using existing authorization token for App Store Connect API")
else
# Username is now optional since addition of App Store Connect API Key
# Force asking for username to prompt user if not already set
options.fetch(:username, force_ask: true)
# Team selection passed though FASTLANE_TEAM_ID and FASTLANE_TEAM_NAME environment variables
# Prompts select team if multiple teams and none specified
UI.message("Login to App Store Connect (#{options[:username]})")
Spaceship::ConnectAPI.login(options[:username], nil, use_portal: false, use_tunes: true)
UI.message("Login successful")
end
end
def run
if options[:verify_only]
UI.important("Verify flag is set, only package validation will take place and no submission will be made")
verify_binary
return
end
verify_version if options[:app_version].to_s.length > 0 && !options[:skip_app_version_update]
# Rejecting before upload meta
# Screenshots cannot be updated or deleted if the app is in the "waiting for review" state
reject_version_if_possible if options[:reject_if_possible]
upload_metadata
has_binary = (options[:ipa] || options[:pkg])
if !options[:skip_binary_upload] && !options[:build_number] && has_binary
upload_binary
end
UI.success("Finished the upload to App Store Connect") unless options[:skip_binary_upload]
precheck_success = precheck_app
submit_for_review if options[:submit_for_review] && precheck_success
end
# Make sure we pass precheck before uploading
def precheck_app
return true unless options[:run_precheck_before_submit]
UI.message("Running precheck before submitting to review, if you'd like to disable this check you can set run_precheck_before_submit to false")
if options[:submit_for_review]
UI.message("Making sure we pass precheck 👮♀️ 👮 before we submit 🛫")
else
UI.message("Running precheck 👮♀️ 👮")
end
precheck_options = {
default_rule_level: options[:precheck_default_rule_level],
include_in_app_purchases: options[:precheck_include_in_app_purchases],
app_identifier: options[:app_identifier]
}
if options[:api_key] || options[:api_key_path]
if options[:precheck_include_in_app_purchases]
UI.user_error!("Precheck cannot check In-app purchases with the App Store Connect API Key (yet). Exclude In-app purchases from precheck, disable the precheck step in your build step, or use Apple ID login")
end
precheck_options[:api_key] = options[:api_key]
precheck_options[:api_key_path] = options[:api_key_path]
else
precheck_options[:username] = options[:username]
precheck_options[:platform] = options[:platform]
end
precheck_config = FastlaneCore::Configuration.create(Precheck::Options.available_options, precheck_options)
Precheck.config = precheck_config
precheck_success = true
begin
precheck_success = Precheck::Runner.new.run
rescue => ex
UI.error("fastlane precheck just tried to inspect your app's metadata for App Store guideline violations and ran into a problem. We're not sure what the problem was, but precheck failed to finish. You can run it in verbose mode if you want to see the whole error. We'll have a fix out soon 🚀")
UI.verbose(ex.inspect)
UI.verbose(ex.backtrace.join("\n"))
end
return precheck_success
end
# Make sure the version on App Store Connect matches the one in the ipa
# If not, the new version will automatically be created
def verify_version
app_version = options[:app_version]
UI.message("Making sure the latest version on App Store Connect matches '#{app_version}'...")
app = Deliver.cache[:app]
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
changed = app.ensure_version!(app_version, platform: 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
# Upload all metadata, screenshots, pricing information, etc. to App Store Connect
def upload_metadata
upload_metadata = UploadMetadata.new(options)
upload_screenshots = UploadScreenshots.new
# First, collect all the things for the HTML Report
screenshots = upload_screenshots.collect_screenshots(options)
upload_metadata.load_from_filesystem
# Assign "default" values to all languages
upload_metadata.assign_defaults
# Validate
validate_html(screenshots)
# Commit
upload_metadata.upload
if options[:sync_screenshots]
sync_screenshots = SyncScreenshots.new(app: Deliver.cache[:app], platform: Spaceship::ConnectAPI::Platform.map(options[:platform]))
sync_screenshots.sync(screenshots)
else
upload_screenshots.upload(options, screenshots)
end
UploadPriceTier.new.upload(options)
end
# Verify the binary with App Store Connect
def verify_binary
UI.message("Verifying binary with App Store Connect")
ipa_path = options[:ipa]
pkg_path = options[:pkg]
platform = options[:platform]
transporter = transporter_for_selected_team
case platform
when "ios", "appletvos", "xros"
package_path = FastlaneCore::IpaUploadPackageBuilder.new.generate(
app_id: Deliver.cache[:app].id,
ipa_path: ipa_path,
package_path: "/tmp",
platform: platform
)
result = transporter.verify(package_path: package_path, asset_path: ipa_path, platform: platform)
when "osx"
package_path = FastlaneCore::PkgUploadPackageBuilder.new.generate(
app_id: Deliver.cache[:app].id,
pkg_path: pkg_path,
package_path: "/tmp",
platform: platform
)
result = transporter.verify(package_path: package_path, asset_path: pkg_path, platform: platform)
else
UI.user_error!("No suitable file found for verify for platform: #{options[:platform]}")
end
unless result
transporter_errors = transporter.displayable_errors
UI.user_error!("Error verifying the binary file: \n #{transporter_errors}")
end
end
# Upload the binary to App Store Connect
def upload_binary
UI.message("Uploading binary to App Store Connect")
ipa_path = options[:ipa]
pkg_path = options[:pkg]
platform = options[:platform]
transporter = transporter_for_selected_team
case platform
when "ios", "appletvos", "xros"
package_path = FastlaneCore::IpaUploadPackageBuilder.new.generate(
app_id: Deliver.cache[:app].id,
ipa_path: ipa_path,
package_path: "/tmp",
platform: platform
)
result = transporter.upload(package_path: package_path, asset_path: ipa_path, platform: platform)
when "osx"
package_path = FastlaneCore::PkgUploadPackageBuilder.new.generate(
app_id: Deliver.cache[:app].id,
pkg_path: pkg_path,
package_path: "/tmp",
platform: platform
)
result = transporter.upload(package_path: package_path, asset_path: pkg_path, platform: platform)
else
UI.user_error!("No suitable file found for upload for platform: #{options[:platform]}")
end
unless result
transporter_errors = transporter.displayable_errors
file_type = platform == "osx" ? "pkg" : "ipa"
UI.user_error!("Error uploading #{file_type} file: \n #{transporter_errors}")
end
end
def reject_version_if_possible
app = Deliver.cache[:app]
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
submission = app.get_in_progress_review_submission(platform: platform)
if submission
submission.cancel_submission
UI.message("Review submission cancellation has been requested")
# An app version won't get removed from review instantly
# Polling until there is no longer an in-progress version
loop do
break if app.get_in_progress_review_submission(platform: platform).nil?
UI.message("Waiting for cancellation to take effect...")
sleep(15)
end
UI.success("Successfully cancelled previous submission!")
end
end
def submit_for_review
SubmitForReview.new.submit!(options)
end
private
# If App Store Connect API token, use token.
# If api_key is specified and it is an Individual API Key, don't use token but use username.
# 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.
def transporter_for_selected_team
# Use JWT auth
api_token = Spaceship::ConnectAPI.token
api_key = if options[:api_key].nil? && !api_token.nil?
# Load api key info if user set api_key_path, not api_key
{ key_id: api_token.key_id, issuer_id: api_token.issuer_id, key: api_token.key_raw }
elsif !options[:api_key].nil?
api_key = options[:api_key].transform_keys(&:to_sym).dup
# key is still base 64 style if api_key is loaded from option
api_key[:key] = Base64.decode64(api_key[:key]) if api_key[:is_key_content_base64]
api_key
end
# Currently no kind of transporters accept an Individual API Key. Use username and app-specific password instead.
# See https://github.com/fastlane/fastlane/issues/22115
is_individual_key = !api_key.nil? && api_key[:issuer_id].nil?
if is_individual_key
api_key = nil
api_token = nil
end
unless api_token.nil?
api_token.refresh! if api_token.expired?
return FastlaneCore::ItunesTransporter.new(nil, nil, false, nil, api_token.text, altool_compatible_command: true, api_key: api_key)
end
tunes_client = Spaceship::ConnectAPI.client.tunes_client
generic_transporter = FastlaneCore::ItunesTransporter.new(options[:username], nil, false, options[:itc_provider], altool_compatible_command: true, api_key: api_key)
return generic_transporter unless options[:itc_provider].nil? && tunes_client.teams.count > 1
begin
team = tunes_client.teams.find { |t| t['providerId'].to_s == tunes_client.team_id }
name = team['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, altool_compatible_command: true, api_key: api_key)
rescue => ex
UI.verbose("Couldn't infer a provider short name for team with id #{tunes_client.team_id} automatically: #{ex}. Proceeding without provider short name.")
return generic_transporter
end
end
def validate_html(screenshots)
return if options[:force]
return if options[:skip_metadata] && options[:skip_screenshots]
HtmlGenerator.new.run(options, screenshots)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/languages.rb | deliver/lib/deliver/languages.rb | module Deliver
module Languages
# 2020-08-24 - Available locales are not available as an endpoint in App Store Connect
# Update with Spaceship::Tunes.client.available_languages.sort (as long as endpoint is available)
ALL_LANGUAGES = %w[ar-SA ca cs da de-DE el en-AU en-CA en-GB en-US es-ES es-MX fi fr-CA fr-FR he hi hr hu id it ja ko ms nl-NL no pl pt-BR pt-PT ro ru sk sv th tr uk vi zh-Hans zh-Hant]
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/upload_metadata.rb | deliver/lib/deliver/upload_metadata.rb | require 'fastlane_core'
require 'spaceship'
require_relative 'module'
module Deliver
# upload description, rating, etc.
# rubocop:disable Metrics/ClassLength
class UploadMetadata
# All the localised values attached to the version
LOCALISED_VERSION_VALUES = {
description: "description",
keywords: "keywords",
release_notes: "whats_new",
support_url: "support_url",
marketing_url: "marketing_url",
promotional_text: "promotional_text"
}
# Everything attached to the version but not being localised
NON_LOCALISED_VERSION_VALUES = {
copyright: "copyright"
}
# Localised app details values
LOCALISED_APP_VALUES = {
name: "name",
subtitle: "subtitle",
privacy_url: "privacy_policy_url",
apple_tv_privacy_policy: "privacy_policy_text"
}
# Non localized app details values
NON_LOCALISED_APP_VALUES = {
primary_category: :primary_category,
secondary_category: :secondary_category,
primary_first_sub_category: :primary_subcategory_one,
primary_second_sub_category: :primary_subcategory_two,
secondary_first_sub_category: :secondary_subcategory_one,
secondary_second_sub_category: :secondary_subcategory_two
}
# Review information values
REVIEW_INFORMATION_VALUES_LEGACY = {
review_first_name: :first_name,
review_last_name: :last_name,
review_phone_number: :phone_number,
review_email: :email_address,
review_demo_user: :demo_user,
review_demo_password: :demo_password,
review_notes: :notes
}
REVIEW_INFORMATION_VALUES = {
first_name: "contact_first_name",
last_name: "contact_last_name",
phone_number: "contact_phone",
email_address: "contact_email",
demo_user: "demo_account_name",
demo_password: "demo_account_password",
notes: "notes"
}
# Localized app details values, that are editable in live state
LOCALISED_LIVE_VALUES = [:description, :release_notes, :support_url, :marketing_url, :promotional_text, :privacy_url]
# Non localized app details values, that are editable in live state
NON_LOCALISED_LIVE_VALUES = [:copyright]
# Directory name it contains trade representative contact information
TRADE_REPRESENTATIVE_CONTACT_INFORMATION_DIR = "trade_representative_contact_information"
# Directory name it contains review information
REVIEW_INFORMATION_DIR = "review_information"
ALL_META_SUB_DIRS = [TRADE_REPRESENTATIVE_CONTACT_INFORMATION_DIR, REVIEW_INFORMATION_DIR]
# rubocop:disable Metrics/PerceivedComplexity
require_relative 'loader'
attr_accessor :options
def initialize(options)
self.options = options
end
# Make sure to call `load_from_filesystem` before calling upload
def upload
return if options[:skip_metadata]
app = Deliver.cache[:app]
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
enabled_languages = detect_languages
app_store_version_localizations = verify_available_version_languages!(app, enabled_languages) unless options[:edit_live]
app_info = fetch_edit_app_info(app)
app_info_localizations = verify_available_info_languages!(app, app_info, enabled_languages) unless options[:edit_live] || !updating_localized_app_info?(app, app_info)
if options[:edit_live]
# not all values are editable when using live_version
version = app.get_live_app_store_version(platform: platform)
localised_options = LOCALISED_LIVE_VALUES
non_localised_options = NON_LOCALISED_LIVE_VALUES
if version.nil?
UI.message("Couldn't find live version, editing the current version on App Store Connect instead")
version = fetch_edit_app_store_version(app, 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
else
UI.message("Found live version")
end
else
version = fetch_edit_app_store_version(app, platform)
localised_options = (LOCALISED_VERSION_VALUES.keys + LOCALISED_APP_VALUES.keys)
non_localised_options = NON_LOCALISED_VERSION_VALUES.keys
end
# Needed for to filter out release notes from being sent up
number_of_versions = Spaceship::ConnectAPI.get_app_store_versions(
app_id: app.id,
filter: { platform: platform },
limit: 2
).count
is_first_version = number_of_versions == 1
UI.verbose("Version '#{version.version_string}' is the first version on App Store Connect") if is_first_version
UI.important("Will begin uploading metadata for '#{version.version_string}' on App Store Connect")
localized_version_attributes_by_locale = {}
localized_info_attributes_by_locale = {}
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
if key == :release_notes && is_first_version
UI.error("Skipping 'release_notes'... this is the first version of the app")
next
end
current.each do |language, value|
next unless value.to_s.length > 0
strip_value = value.to_s.strip
if LOCALISED_VERSION_VALUES.include?(key) && !strip_value.empty?
attribute_name = LOCALISED_VERSION_VALUES[key]
localized_version_attributes_by_locale[language] ||= {}
localized_version_attributes_by_locale[language][attribute_name] = strip_value
end
next unless LOCALISED_APP_VALUES.include?(key) && !strip_value.empty?
attribute_name = LOCALISED_APP_VALUES[key]
localized_info_attributes_by_locale[language] ||= {}
localized_info_attributes_by_locale[language][attribute_name] = strip_value
end
end
non_localized_version_attributes = {}
non_localised_options.each do |key|
strip_value = options[key].to_s.strip
next unless strip_value.to_s.length > 0
if NON_LOCALISED_VERSION_VALUES.include?(key) && !strip_value.empty?
attribute_name = NON_LOCALISED_VERSION_VALUES[key]
non_localized_version_attributes[attribute_name] = strip_value
end
end
release_type = if options[:auto_release_date]
# Convert time format to 2020-06-17T12:00:00-07:00
time_in_ms = options[:auto_release_date]
date = convert_ms_to_iso8601(time_in_ms)
non_localized_version_attributes['earliestReleaseDate'] = date
Spaceship::ConnectAPI::AppStoreVersion::ReleaseType::SCHEDULED
elsif options[:automatic_release] == true
Spaceship::ConnectAPI::AppStoreVersion::ReleaseType::AFTER_APPROVAL
elsif options[:automatic_release] == false
Spaceship::ConnectAPI::AppStoreVersion::ReleaseType::MANUAL
end
if release_type.nil?
UI.important("Release type will not be set because neither `automatic_release` nor `auto_release_date` were provided. Please explicitly set one of these options if you need a release type set")
else
non_localized_version_attributes['releaseType'] = release_type
end
# Update app store version
# This needs to happen before updating localizations (https://openradar.appspot.com/radar?id=4925914991296512)
#
# Adding some sleeps because the API will sometimes be in a state where releaseType can't be modified
# https://github.com/fastlane/fastlane/issues/16911
UI.message("Uploading metadata to App Store Connect for version")
sleep(2)
version.update(attributes: non_localized_version_attributes)
sleep(1)
# Update app store version localizations
store_version_worker = FastlaneCore::QueueWorker.new do |app_store_version_localization|
attributes = localized_version_attributes_by_locale[app_store_version_localization.locale]
if attributes
UI.message("Uploading metadata to App Store Connect for localized version '#{app_store_version_localization.locale}'")
app_store_version_localization.update(attributes: attributes)
end
end
store_version_worker.batch_enqueue(app_store_version_localizations)
store_version_worker.start
# Update app info localizations
if app_info_localizations
app_info_worker = FastlaneCore::QueueWorker.new do |app_info_localization|
attributes = localized_info_attributes_by_locale[app_info_localization.locale]
if attributes
UI.message("Uploading metadata to App Store Connect for localized info '#{app_info_localization.locale}'")
app_info_localization.update(attributes: attributes)
end
end
app_info_worker.batch_enqueue(app_info_localizations)
app_info_worker.start
end
# Update categories
if app_info
category_id_map = {}
primary_category = options[:primary_category].to_s.strip
secondary_category = options[:secondary_category].to_s.strip
primary_first_sub_category = options[:primary_first_sub_category].to_s.strip
primary_second_sub_category = options[:primary_second_sub_category].to_s.strip
secondary_first_sub_category = options[:secondary_first_sub_category].to_s.strip
secondary_second_sub_category = options[:secondary_second_sub_category].to_s.strip
mapped_values = {}
# Only update primary and secondary category if explicitly set
unless primary_category.empty?
mapped = Spaceship::ConnectAPI::AppCategory.map_category_from_itc(
primary_category
)
mapped_values[primary_category] = mapped
category_id_map[:primary_category_id] = mapped
end
unless secondary_category.empty?
mapped = Spaceship::ConnectAPI::AppCategory.map_category_from_itc(
secondary_category
)
mapped_values[secondary_category] = mapped
category_id_map[:secondary_category_id] = mapped
end
# Only set if primary category is going to be set
unless primary_category.empty?
mapped = Spaceship::ConnectAPI::AppCategory.map_subcategory_from_itc(
primary_first_sub_category
)
mapped_values[primary_first_sub_category] = mapped
category_id_map[:primary_subcategory_one_id] = mapped
end
unless primary_category.empty?
mapped = Spaceship::ConnectAPI::AppCategory.map_subcategory_from_itc(
primary_second_sub_category
)
mapped_values[primary_second_sub_category] = mapped
category_id_map[:primary_subcategory_two_id] = mapped
end
# Only set if secondary category is going to be set
unless secondary_category.empty?
mapped = Spaceship::ConnectAPI::AppCategory.map_subcategory_from_itc(
secondary_first_sub_category
)
mapped_values[secondary_first_sub_category] = mapped
category_id_map[:secondary_subcategory_one_id] = mapped
end
unless secondary_category.empty?
mapped = Spaceship::ConnectAPI::AppCategory.map_subcategory_from_itc(
secondary_second_sub_category
)
mapped_values[secondary_second_sub_category] = mapped
category_id_map[:secondary_subcategory_two_id] = mapped
end
# Print deprecation warnings if category was mapped
has_mapped_values = false
mapped_values.each do |k, v|
next if k.nil? || v.nil?
next if k == v
has_mapped_values = true
UI.deprecated("Category '#{k}' from iTunesConnect has been deprecated. Please replace with '#{v}'")
end
UI.deprecated("You can find more info at https://docs.fastlane.tools/actions/deliver/#reference") if has_mapped_values
app_info.update_categories(category_id_map: category_id_map)
end
# Update phased release
unless options[:phased_release].nil?
phased_release = begin
version.fetch_app_store_version_phased_release
rescue
nil
end # returns no data error so need to rescue
if !!options[:phased_release]
unless phased_release
UI.message("Creating phased release on App Store Connect")
version.create_app_store_version_phased_release(attributes: {
phasedReleaseState: Spaceship::ConnectAPI::AppStoreVersionPhasedRelease::PhasedReleaseState::INACTIVE
})
end
elsif phased_release
UI.message("Removing phased release on App Store Connect")
phased_release.delete!
end
end
# Update rating reset
unless options[:reset_ratings].nil?
reset_rating_request = begin
version.fetch_reset_ratings_request
rescue
nil
end # returns no data error so need to rescue
if !!options[:reset_ratings]
unless reset_rating_request
UI.message("Creating reset ratings request on App Store Connect")
version.create_reset_ratings_request
end
elsif reset_rating_request
UI.message("Removing reset ratings request on App Store Connect")
reset_rating_request.delete!
end
end
review_information(version)
review_attachment_file(version)
app_rating(app_info)
end
# rubocop:enable Metrics/PerceivedComplexity
def convert_ms_to_iso8601(time_in_ms)
time_in_s = time_in_ms / 1000
# Remove minutes and seconds (whole hour)
seconds_in_hour = 60 * 60
time_in_s_to_hour = (time_in_s / seconds_in_hour).to_i * seconds_in_hour
return Time.at(time_in_s_to_hour).utc.strftime("%Y-%m-%dT%H:%M:%S%:z")
end
# If the user is using the 'default' language, then assign values where they are needed
def assign_defaults
# Normalizes languages keys from symbols to strings
normalize_language_keys
# Build a complete list of the required languages
enabled_languages = detect_languages
# Get all languages used in existing settings
(LOCALISED_VERSION_VALUES.keys + LOCALISED_APP_VALUES.keys).each do |key|
current = options[key]
next unless current && current.kind_of?(Hash)
current.each do |language, value|
enabled_languages << language unless enabled_languages.include?(language)
end
end
# Check folder list (an empty folder signifies a language is required)
ignore_validation = options[:ignore_language_directory_validation]
Loader.language_folders(options[:metadata_path], ignore_validation).each do |lang_folder|
enabled_languages << lang_folder.basename unless enabled_languages.include?(lang_folder.basename)
end
return unless enabled_languages.include?("default")
UI.message("Detected languages: " + enabled_languages.to_s)
(LOCALISED_VERSION_VALUES.keys + LOCALISED_APP_VALUES.keys).each do |key|
current = options[key]
next unless current && current.kind_of?(Hash)
default = current["default"]
next if default.nil?
enabled_languages.each do |language|
value = current[language]
next unless value.nil?
current[language] = default
end
current.delete("default")
end
end
def detect_languages
# Build a complete list of the required languages
enabled_languages = options[:languages] || []
# Get all languages used in existing settings
(LOCALISED_VERSION_VALUES.keys + LOCALISED_APP_VALUES.keys).each do |key|
current = options[key]
next unless current && current.kind_of?(Hash)
current.each do |language, value|
enabled_languages << language unless enabled_languages.include?(language)
end
end
# Check folder list (an empty folder signifies a language is required)
ignore_validation = options[:ignore_language_directory_validation]
Loader.language_folders(options[:metadata_path], ignore_validation).each do |lang_folder|
enabled_languages << lang_folder.basename unless enabled_languages.include?(lang_folder.basename)
end
# Mapping to strings because :default symbol can be passed in
enabled_languages
.map(&:to_s)
.uniq
end
def fetch_edit_app_store_version(app, platform)
retry_if_nil("Cannot find edit app store version") do
app.get_edit_app_store_version(platform: platform)
end
end
def fetch_edit_app_info(app)
retry_if_nil("Cannot find edit app info") do
app.fetch_edit_app_info
end
end
def fetch_live_app_info(app)
retry_if_nil("Cannot find live app info") do
app.fetch_live_app_info
end
end
# Retries a block of code if the return value is nil, with an exponential backoff.
def retry_if_nil(message)
tries = options[:version_check_wait_retry_limit]
wait_time = 10
loop do
tries -= 1
value = yield
return value if value
# Calculate sleep time to be the lesser of the exponential backoff or 5 minutes.
# This prevents problems with CI's console output timeouts (of usually 10 minutes), and also
# speeds up the retry time for the user, as waiting longer than 5 minutes is a too long wait for a retry.
sleep_time = [wait_time * 2, 5 * 60].min
UI.message("#{message}... Retrying after #{sleep_time} seconds (remaining: #{tries})")
Kernel.sleep(sleep_time)
return nil if tries.zero?
wait_time *= 2 # Double the wait time for the next iteration
end
end
# Checking if the metadata to update includes localised App Info
def updating_localized_app_info?(app, app_info)
app_info ||= fetch_live_app_info(app)
unless app_info
UI.important("Can't find edit or live App info. Skipping upload.")
return false
end
localizations = app_info.get_app_info_localizations
LOCALISED_APP_VALUES.each do |key, localized_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|
strip_value = value.to_s.strip
next if strip_value.empty?
app_info_locale = localizations.find { |l| l.locale == language }
next if app_info_locale.nil?
begin
current_value = app_info_locale.public_send(localized_key.to_sym)
rescue NoMethodError
next
end
return true if current_value != strip_value
end
end
UI.message('No changes to localized App Info detected. Skipping upload.')
return false
end
# Finding languages to enable
def verify_available_info_languages!(app, app_info, languages)
unless app_info
UI.user_error!("Cannot update languages - could not find an editable 'App Info'. Verify that your app is in one of the editable states in App Store Connect")
return
end
localizations = app_info.get_app_info_localizations
languages = (languages || []).reject { |lang| lang == "default" }
locales_to_enable = languages - localizations.map(&:locale)
if locales_to_enable.count > 0
lng_text = "language"
lng_text += "s" if locales_to_enable.count != 1
Helper.show_loading_indicator("Activating info #{lng_text} #{locales_to_enable.join(', ')}...")
locales_to_enable.each do |locale|
app_info.create_app_info_localization(attributes: {
locale: locale
})
end
Helper.hide_loading_indicator
# Refresh version localizations
localizations = app_info.get_app_info_localizations
end
return localizations
end
# Finding languages to enable
def verify_available_version_languages!(app, languages)
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
version = fetch_edit_app_store_version(app, platform)
unless version
UI.user_error!("Cannot update languages - could not find an editable version for '#{platform}'")
return
end
localizations = version.get_app_store_version_localizations
languages = (languages || []).reject { |lang| lang == "default" }
locales_to_enable = languages - localizations.map(&:locale)
if locales_to_enable.count > 0
lng_text = "language"
lng_text += "s" if locales_to_enable.count != 1
Helper.show_loading_indicator("Activating version #{lng_text} #{locales_to_enable.join(', ')}...")
locales_to_enable.each do |locale|
version.create_app_store_version_localization(attributes: {
locale: locale
})
end
Helper.hide_loading_indicator
# Refresh version localizations
localizations = version.get_app_store_version_localizations
end
return localizations
end
# Loads the metadata files and stores them into the options object
def load_from_filesystem
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|
(LOCALISED_VERSION_VALUES.keys + LOCALISED_APP_VALUES.keys).each do |key|
path = File.join(lang_folder.path, "#{key}.txt")
next unless File.exist?(path)
UI.message("Loading '#{path}'...")
options[key] ||= {}
options[key][lang_folder.basename] ||= File.read(path)
end
end
# Load non localised data
(NON_LOCALISED_VERSION_VALUES.keys + NON_LOCALISED_APP_VALUES.keys).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 review information
# This is used to find the file path for both new and legacy review information filenames
resolve_review_info_path = lambda do |option_name|
path = File.join(options[:metadata_path], REVIEW_INFORMATION_DIR, "#{option_name}.txt")
return nil unless File.exist?(path)
return nil if options[:app_review_information][option_name].to_s.length > 0
UI.message("Loading '#{path}'...")
return path
end
# First try and load review information from legacy filenames
options[:app_review_information] ||= {}
REVIEW_INFORMATION_VALUES_LEGACY.each do |legacy_option_name, option_name|
path = resolve_review_info_path.call(legacy_option_name)
next if path.nil?
options[:app_review_information][option_name] ||= File.read(path)
UI.deprecated("Review rating option '#{legacy_option_name}' from iTunesConnect has been deprecated. Please replace with '#{option_name}'")
end
# Then load review information from new App Store Connect filenames
REVIEW_INFORMATION_VALUES.keys.each do |option_name|
path = resolve_review_info_path.call(option_name)
next if path.nil?
options[:app_review_information][option_name] ||= File.read(path)
end
end
private
# Normalizes languages keys from symbols to strings
def normalize_language_keys
(LOCALISED_VERSION_VALUES.keys + LOCALISED_APP_VALUES.keys).each do |key|
current = options[key]
next unless current && current.kind_of?(Hash)
current.keys.each do |language|
current[language.to_s] = current.delete(language)
end
end
options
end
def review_information(version)
info = options[:app_review_information]
return if info.nil? || info.empty?
info = info.transform_keys(&:to_sym)
UI.user_error!("`app_review_information` must be a hash", show_github_issues: true) unless info.kind_of?(Hash)
attributes = {}
REVIEW_INFORMATION_VALUES.each do |key, attribute_name|
strip_value = info[key].to_s.strip
attributes[attribute_name] = strip_value unless strip_value.empty?
end
if !attributes["demo_account_name"].to_s.empty? && !attributes["demo_account_password"].to_s.empty?
attributes["demo_account_required"] = true
else
attributes["demo_account_required"] = false
end
UI.message("Uploading app review information to App Store Connect")
app_store_review_detail = begin
version.fetch_app_store_review_detail
rescue => error
UI.error("Error fetching app store review detail - #{error.message}")
nil
end # errors if doesn't exist
if app_store_review_detail
app_store_review_detail.update(attributes: attributes)
else
version.create_app_store_review_detail(attributes: attributes)
end
end
def review_attachment_file(version)
app_store_review_detail = version.fetch_app_store_review_detail
app_store_review_attachments = app_store_review_detail.app_store_review_attachments || []
if options[:app_review_attachment_file]
app_store_review_attachments.each do |app_store_review_attachment|
UI.message("Removing previous review attachment file from App Store Connect")
app_store_review_attachment.delete!
end
UI.message("Uploading review attachment file to App Store Connect")
app_store_review_detail.upload_attachment(path: options[:app_review_attachment_file])
else
app_store_review_attachments.each(&:delete!)
UI.message("Removing review attachment file to App Store Connect") unless app_store_review_attachments.empty?
end
end
def app_rating(app_info)
return unless options[:app_rating_config_path]
unless app_info
UI.important("Skipping age rating update because app info could not be fetched.")
return
end
require 'json'
begin
json = JSON.parse(File.read(options[:app_rating_config_path]))
rescue => ex
UI.error(ex.to_s)
UI.user_error!("Error parsing JSON file at path '#{options[:app_rating_config_path]}'")
end
UI.message("Setting the app's age rating...")
# Mapping from legacy ITC values to App Store Connect Values
mapped_values = {}
attributes = {}
json.each do |k, v|
new_key = Spaceship::ConnectAPI::AgeRatingDeclaration.map_key_from_itc(k)
new_value = Spaceship::ConnectAPI::AgeRatingDeclaration.map_value_from_itc(new_key, v)
mapped_values[k] = new_key
mapped_values[v] = new_value
attributes[new_key] = new_value
end
# Print deprecation warnings if category was mapped
has_mapped_values = false
mapped_values.each do |k, v|
next if k.nil? || v.nil?
next if k == v
has_mapped_values = true
UI.deprecated("Age rating '#{k}' from iTunesConnect has been deprecated. Please replace with '#{v}'")
end
# Handle App Store Connect deprecation/migrations of keys/values if possible
attributes, deprecation_messages, errors = Spaceship::ConnectAPI::AgeRatingDeclaration.map_deprecation_if_possible(attributes)
deprecation_messages.each do |message|
UI.deprecated(message)
end
unless errors.empty?
errors.each do |error|
UI.error(error)
end
UI.user_error!("There are Age Rating deprecation errors that cannot be solved automatically... Please apply any fixes and try again")
end
UI.deprecated("You can find more info at https://docs.fastlane.tools/actions/deliver/#reference") if has_mapped_values || !deprecation_messages.empty?
age_rating_declaration = app_info.fetch_age_rating_declaration
age_rating_declaration.update(attributes: attributes)
end
end
# rubocop:enable Metrics/ClassLength
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/html_generator.rb | deliver/lib/deliver/html_generator.rb | require 'spaceship'
require_relative 'module'
module Deliver
class HtmlGenerator
# Splits keywords supporting:
# * separated by commas (with optional whitespace)
# * separated by newlines
KEYWORD_SPLITTER = /(?:,\s?|\r?\n)/
def run(options, screenshots)
begin
# Use fastlane folder or default to current directory
fastlane_path = FastlaneCore::FastlaneFolder.path || "."
html_path = self.render(options, screenshots, fastlane_path)
rescue => ex
UI.error(ex.inspect)
UI.error(ex.backtrace.join("\n"))
okay = UI.input("Could not render HTML preview. Do you still want to continue?")
return if okay
UI.crash!("Could not render HTML page")
end
UI.important("Verifying the upload via the HTML file can be disabled by either adding")
UI.important("`force true` to your Deliverfile or using `fastlane deliver --force`")
system("open '#{html_path}'")
okay = UI.confirm("Does the Preview on path '#{html_path}' look okay for you?")
if okay
UI.success("HTML file confirmed...") # print this to give feedback to the user immediately
else
UI.user_error!("Did not upload the metadata, because the HTML file was rejected by the user")
end
end
# Returns a path relative to FastlaneFolder.path
# This is needed as the Preview.html file is located inside FastlaneFolder.path
def render_relative_path(export_path, path)
export_path = Pathname.new(File.expand_path(export_path))
path = Pathname.new(File.expand_path(path)).relative_path_from(export_path)
return path.to_path
end
# Renders all data available to quickly see if everything was correctly generated.
# @param export_path (String) The path to a folder where the resulting HTML file should be stored.
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 ||= Deliver.cache[:app].name
@languages = options[:description].keys if options[:description]
@languages ||= begin
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
version = Deliver.cache[:app].get_edit_app_store_version(platform: platform)
version.get_app_store_version_localizations.collect(&:locale)
end
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
# Splits a string of keywords separated by comma or newlines into a presentable list
# @param keywords (String)
def split_keywords(keywords)
keywords.split(KEYWORD_SPLITTER)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/upload_screenshots.rb | deliver/lib/deliver/upload_screenshots.rb | require 'fastlane_core'
require 'spaceship/tunes/tunes'
require 'digest/md5'
require_relative 'app_screenshot'
require_relative 'module'
require_relative 'loader'
require_relative 'app_screenshot_iterator'
module Deliver
# upload screenshots to App Store Connect
class UploadScreenshots
DeleteScreenshotSetJob = Struct.new(:app_screenshot_set, :localization)
UploadScreenshotJob = Struct.new(:app_screenshot_set, :path)
def upload(options, screenshots)
return if options[:skip_screenshots]
return if options[:edit_live]
app = Deliver.cache[:app]
platform = Spaceship::ConnectAPI::Platform.map(options[:platform])
version = app.get_edit_app_store_version(platform: platform)
UI.user_error!("Could not find a version to edit for app '#{app.name}' for '#{platform}'") unless version
UI.important("Will begin uploading snapshots for '#{version.version_string}' on App Store Connect")
UI.message("Starting with the upload of screenshots...")
screenshots_per_language = screenshots.group_by(&:language)
localizations = version.get_app_store_version_localizations
if options[:overwrite_screenshots]
delete_screenshots(localizations, screenshots_per_language)
end
# Finding languages to enable
languages = screenshots_per_language.keys
locales_to_enable = languages - localizations.map(&:locale)
if locales_to_enable.count > 0
lng_text = "language"
lng_text += "s" if locales_to_enable.count != 1
Helper.show_loading_indicator("Activating #{lng_text} #{locales_to_enable.join(', ')}...")
locales_to_enable.each do |locale|
version.create_app_store_version_localization(attributes: {
locale: locale
})
end
Helper.hide_loading_indicator
# Refresh version localizations
localizations = version.get_app_store_version_localizations
end
upload_screenshots(localizations, screenshots_per_language, options[:screenshot_processing_timeout])
Helper.show_loading_indicator("Sorting screenshots uploaded...")
sort_screenshots(localizations)
Helper.hide_loading_indicator
UI.success("Successfully uploaded screenshots to App Store Connect")
end
def delete_screenshots(localizations, screenshots_per_language, tries: 5)
tries -= 1
worker = FastlaneCore::QueueWorker.new do |job|
start_time = Time.now
target = "#{job.localization.locale} #{job.app_screenshot_set.screenshot_display_type}"
begin
UI.verbose("Deleting '#{target}'")
job.app_screenshot_set.delete!
UI.message("Deleted '#{target}' - (#{Time.now - start_time} secs)")
rescue => error
UI.error("Failed to delete screenshot #{target} - (#{Time.now - start_time} secs)")
UI.error(error.message)
end
end
iterator = AppScreenshotIterator.new(localizations)
iterator.each_app_screenshot_set do |localization, app_screenshot_set|
# Only delete screenshots if trying to upload
next unless screenshots_per_language.keys.include?(localization.locale)
UI.verbose("Queued delete screenshot set job for #{localization.locale} #{app_screenshot_set.screenshot_display_type}")
worker.enqueue(DeleteScreenshotSetJob.new(app_screenshot_set, localization))
end
worker.start
# Verify all screenshots have been deleted
# Sometimes API requests will fail but screenshots will still be deleted
count = iterator.each_app_screenshot_set
.select { |localization, _| screenshots_per_language.keys.include?(localization.locale) }
.map { |_, app_screenshot_set| app_screenshot_set }
.reduce(0) { |sum, app_screenshot_set| sum + app_screenshot_set.app_screenshots.size }
UI.important("Number of screenshots not deleted: #{count}")
if count > 0
if tries.zero?
UI.user_error!("Failed verification of all screenshots deleted... #{count} screenshot(s) still exist")
else
UI.error("Failed to delete all screenshots... Tries remaining: #{tries}")
delete_screenshots(localizations, screenshots_per_language, tries: tries)
end
else
UI.message("Successfully deleted all screenshots")
end
end
def upload_screenshots(localizations, screenshots_per_language, timeout_seconds, tries: 5)
tries -= 1
# Upload screenshots
worker = FastlaneCore::QueueWorker.new do |job|
begin
UI.verbose("Uploading '#{job.path}'...")
start_time = Time.now
job.app_screenshot_set.upload_screenshot(path: job.path, wait_for_processing: false)
UI.message("Uploaded '#{job.path}'... (#{Time.now - start_time} secs)")
rescue => error
UI.error(error)
end
end
# Each app_screenshot_set can have only 10 images
number_of_screenshots_per_set = {}
total_number_of_screenshots = 0
iterator = AppScreenshotIterator.new(localizations)
iterator.each_local_screenshot(screenshots_per_language) do |localization, app_screenshot_set, screenshot|
# Initialize counter on each app screenshot set
number_of_screenshots_per_set[app_screenshot_set] ||= (app_screenshot_set.app_screenshots || []).count
if number_of_screenshots_per_set[app_screenshot_set] >= 10
UI.error("Too many screenshots found for device '#{screenshot.display_type}' in '#{screenshot.language}', skipping this one (#{screenshot.path})")
next
end
checksum = UploadScreenshots.calculate_checksum(screenshot.path)
duplicate = (app_screenshot_set.app_screenshots || []).any? { |s| s.source_file_checksum == checksum }
# Enqueue uploading job if it's not duplicated otherwise screenshot will be skipped
if duplicate
UI.message("Previous uploaded. Skipping '#{screenshot.path}'...")
else
UI.verbose("Queued upload screenshot job for #{localization.locale} #{app_screenshot_set.screenshot_display_type} #{screenshot.path}")
worker.enqueue(UploadScreenshotJob.new(app_screenshot_set, screenshot.path))
number_of_screenshots_per_set[app_screenshot_set] += 1
end
total_number_of_screenshots += 1
end
worker.start
UI.verbose('Uploading jobs are completed')
Helper.show_loading_indicator("Waiting for all the screenshots to finish being processed...")
states = wait_for_complete(iterator, timeout_seconds)
Helper.hide_loading_indicator
retry_upload_screenshots_if_needed(iterator, states, total_number_of_screenshots, tries, timeout_seconds, localizations, screenshots_per_language)
UI.message("Successfully uploaded all screenshots")
end
# Verify all screenshots have been processed
def wait_for_complete(iterator, timeout_seconds)
start_time = Time.now
loop do
states = iterator.each_app_screenshot.map { |_, _, app_screenshot| app_screenshot }.each_with_object({}) do |app_screenshot, hash|
state = app_screenshot.asset_delivery_state['state']
hash[state] ||= 0
hash[state] += 1
end
is_processing = states.fetch('UPLOAD_COMPLETE', 0) > 0
return states unless is_processing
if Time.now - start_time > timeout_seconds
UI.important("Screenshot upload reached the timeout limit of #{timeout_seconds} seconds. We'll now retry uploading the screenshots that couldn't be uploaded in time.")
return states
end
UI.verbose("There are still incomplete screenshots - #{states}")
sleep(5)
end
end
# Verify all screenshots states on App Store Connect are okay
def retry_upload_screenshots_if_needed(iterator, states, number_of_screenshots, tries, timeout_seconds, localizations, screenshots_per_language)
is_failure = states.fetch("FAILED", 0) > 0
is_processing = states.fetch('UPLOAD_COMPLETE', 0) > 0
is_missing_screenshot = !screenshots_per_language.empty? && !verify_local_screenshots_are_uploaded(iterator, screenshots_per_language)
return unless is_failure || is_missing_screenshot || is_processing
if tries.zero?
iterator.each_app_screenshot.select { |_, _, app_screenshot| app_screenshot.error? }.each do |localization, _, app_screenshot|
UI.error("#{app_screenshot.file_name} for #{localization.locale} has error(s) - #{app_screenshot.error_messages.join(', ')}")
end
incomplete_screenshot_count = states.reject { |k, v| k == 'COMPLETE' }.reduce(0) { |sum, (k, v)| sum + v }
UI.user_error!("Failed verification of all screenshots uploaded... #{incomplete_screenshot_count} incomplete screenshot(s) still exist")
else
UI.error("Failed to upload all screenshots... Tries remaining: #{tries}")
# Delete bad entries before retry
iterator.each_app_screenshot do |_, _, app_screenshot|
app_screenshot.delete! unless app_screenshot.complete?
end
upload_screenshots(localizations, screenshots_per_language, timeout_seconds, tries: tries)
end
end
# Return `true` if all the local screenshots are uploaded to App Store Connect
def verify_local_screenshots_are_uploaded(iterator, screenshots_per_language)
# Check if local screenshots' checksum exist on App Store Connect
checksum_to_app_screenshot = iterator.each_app_screenshot.map { |_, _, app_screenshot| [app_screenshot.source_file_checksum, app_screenshot] }.to_h
number_of_screenshots_per_set = {}
missing_local_screenshots = iterator.each_local_screenshot(screenshots_per_language).select do |_, app_screenshot_set, local_screenshot|
number_of_screenshots_per_set[app_screenshot_set] ||= (app_screenshot_set.app_screenshots || []).count
checksum = UploadScreenshots.calculate_checksum(local_screenshot.path)
if checksum_to_app_screenshot[checksum]
next(false)
else
is_missing = number_of_screenshots_per_set[app_screenshot_set] < 10 # if it's more than 10, it's skipped
number_of_screenshots_per_set[app_screenshot_set] += 1
next(is_missing)
end
end
missing_local_screenshots.each do |_, _, screenshot|
UI.error("#{screenshot.path} is missing on App Store Connect.")
end
missing_local_screenshots.empty?
end
def sort_screenshots(localizations)
require 'naturally'
iterator = AppScreenshotIterator.new(localizations)
# Re-order screenshots within app_screenshot_set
worker = FastlaneCore::QueueWorker.new do |app_screenshot_set|
original_ids = app_screenshot_set.app_screenshots.map(&:id)
sorted_ids = Naturally.sort(app_screenshot_set.app_screenshots, by: :file_name).map(&:id)
if original_ids != sorted_ids
app_screenshot_set.reorder_screenshots(app_screenshot_ids: sorted_ids)
end
end
iterator.each_app_screenshot_set do |_, app_screenshot_set|
worker.enqueue(app_screenshot_set)
end
worker.start
end
def collect_screenshots(options)
return [] if options[:skip_screenshots]
return Loader.load_app_screenshots(options[:screenshots_path], options[:ignore_language_directory_validation])
end
# helper method so Spaceship::Tunes.client.available_languages is easier to test
def self.available_languages
# 2020-08-24 - Available locales are not available as an endpoint in App Store Connect
# Update with Spaceship::Tunes.client.available_languages.sort (as long as endpoint is available)
Deliver::Languages::ALL_LANGUAGES
end
# helper method to mock this step in tests
def self.calculate_checksum(path)
bytes = File.binread(path)
Digest::MD5.hexdigest(bytes)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/module.rb | deliver/lib/deliver/module.rb | require 'fastlane_core/helper'
require 'fastlane_core/ui/ui'
require 'fastlane/boolean'
module Deliver
class << self
attr_accessor :cache
def cache
@cache ||= {}
@cache
end
end
Helper = FastlaneCore::Helper # you gotta love Ruby: Helper.* should use the Helper class contained in FastlaneCore
UI = FastlaneCore::UI
Boolean = Fastlane::Boolean
# Constant that captures the root Pathname for the project. Should be used for building paths to assets or other
# resources that code needs to locate locally
ROOT = Pathname.new(File.expand_path('../../..', __FILE__))
DESCRIPTION = 'Upload screenshots, metadata and your app to the App Store using a single command'
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/deliver/lib/deliver/screenshot_comparable.rb | deliver/lib/deliver/screenshot_comparable.rb | require 'spaceship/connect_api/models/app_screenshot'
require 'spaceship/connect_api/models/app_screenshot_set'
require_relative 'app_screenshot'
module Deliver
# This clsas enables you to compare equality between different representations of the screenshots
# in the standard API `Array#-` that requires objects to implements `eql?` and `hash`.
class ScreenshotComparable
# A unique key value that is consist of locale, filename, and checksum.
attr_reader :key
# A hash object that contains the source data of this representation class
attr_reader :context
def self.create_from_local(screenshot:, app_screenshot_set:)
raise ArgumentError unless screenshot.kind_of?(Deliver::AppScreenshot)
raise ArgumentError unless app_screenshot_set.kind_of?(Spaceship::ConnectAPI::AppScreenshotSet)
new(
path: "#{screenshot.language}/#{File.basename(screenshot.path)}",
checksum: calculate_checksum(screenshot.path),
context: {
screenshot: screenshot,
app_screenshot_set: app_screenshot_set
}
)
end
def self.create_from_remote(app_screenshot:, locale:)
raise ArgumentError unless app_screenshot.kind_of?(Spaceship::ConnectAPI::AppScreenshot)
raise ArgumentError unless locale.kind_of?(String)
new(
path: "#{locale}/#{app_screenshot.file_name}",
checksum: app_screenshot.source_file_checksum,
context: {
app_screenshot: app_screenshot,
locale: locale
}
)
end
def self.calculate_checksum(path)
bytes = File.binread(path)
Digest::MD5.hexdigest(bytes)
end
def initialize(path:, checksum:, context:)
@key = "#{path}/#{checksum}"
@context = context
end
def eql?(other)
key == other.key
end
def hash
key.hash
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pem/spec/commands_generator_spec.rb | pem/spec/commands_generator_spec.rb | require 'pem/commands_generator'
describe PEM::CommandsGenerator do
let(:available_options) { PEM::Options.available_options }
describe ":renew option handling" do
it "can use the save_private_key short flag from tool options" do
# leaving out the command name defaults to 'renew'
stub_commander_runner_args(['-s', 'false'])
expected_options = FastlaneCore::Configuration.create(available_options, { save_private_key: false })
expect(PEM::Manager).to receive(:start)
PEM::CommandsGenerator.start
expect(PEM.config._values).to eq(expected_options._values)
end
it "can use the development flag from tool options" do
# leaving out the command name defaults to 'renew'
stub_commander_runner_args(['--development', 'true'])
expected_options = FastlaneCore::Configuration.create(available_options, { development: true })
expect(PEM::Manager).to receive(:start)
PEM::CommandsGenerator.start
expect(PEM.config._values).to eq(expected_options._values)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pem/spec/manager_spec.rb | pem/spec/manager_spec.rb | describe PEM do
describe PEM::Manager do
before do
ENV["DELIVER_USER"] = "test@fastlane.tools"
ENV["DELIVER_PASSWORD"] = "123"
pem_stub_spaceship
end
before :all do
FileUtils.mkdir("tmp")
end
it "Successful run" do
pem_stub_spaceship_cert(platform: 'ios')
options = { app_identifier: "com.krausefx.app", generate_p12: false }
PEM.config = FastlaneCore::Configuration.create(PEM::Options.available_options, options)
PEM::Manager.start
expect(File.exist?("production_com.krausefx.app_ios.pem")).to eq(true)
expect(File.exist?("production_com.krausefx.app_ios.pkey")).to eq(true)
end
it "Successful run with output_path for ios platform" do
pem_stub_spaceship_cert(platform: 'ios')
options = { app_identifier: "com.krausefx.app", generate_p12: false, output_path: "tmp/" }
PEM.config = FastlaneCore::Configuration.create(PEM::Options.available_options, options)
PEM::Manager.start
expect(File.exist?("tmp/production_com.krausefx.app_ios.pem")).to eq(true)
expect(File.exist?("tmp/production_com.krausefx.app_ios.pkey")).to eq(true)
expect(File.exist?("tmp/production_com.krausefx.app_ios.p12")).to eq(false)
end
it "Successful run with output_path for macos platform" do
pem_stub_spaceship_cert(platform: 'macos')
options = { app_identifier: "com.krausefx.app", generate_p12: false, output_path: "tmp/", platform: 'macos' }
PEM.config = FastlaneCore::Configuration.create(PEM::Options.available_options, options)
PEM::Manager.start
expect(File.exist?("tmp/production_com.krausefx.app_macos.pem")).to eq(true)
expect(File.exist?("tmp/production_com.krausefx.app_macos.pkey")).to eq(true)
expect(File.exist?("tmp/production_com.krausefx.app_macos.p12")).to eq(false)
end
after :all do
FileUtils.rm_r("tmp")
File.delete("production_com.krausefx.app_ios.pem")
File.delete("production_com.krausefx.app_ios.pkey")
ENV.delete("DELIVER_USER")
ENV.delete("DELIVER_PASSWORD")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pem/spec/spec_helper.rb | pem/spec/spec_helper.rb | def pem_stub_spaceship
expect(Spaceship).to receive(:login).and_return(nil)
allow(Spaceship).to receive(:client).and_return("client")
expect(Spaceship.client).to receive(:select_team).and_return(nil)
expect(Spaceship.certificate).to receive(:all).and_return([])
csr = "csr"
pkey = "pkey"
expect(Spaceship.certificate).to receive(:create_certificate_signing_request).and_return([csr, pkey])
expect(pkey).to receive(:to_pem).twice.and_return("to_pem")
end
def pem_stub_spaceship_cert(platform: 'ios')
csr = "csr"
cert = "cert"
x509 = "x509"
case platform
when 'macos'
expect(Spaceship.certificate.mac_production_push).to receive(:create!).with(csr: csr, bundle_id: "com.krausefx.app").and_return(cert)
else
expect(Spaceship.certificate.production_push).to receive(:create!).with(csr: csr, bundle_id: "com.krausefx.app").and_return(cert)
end
expect(cert).to receive(:download).and_return(x509)
expect(x509).to receive(:to_pem).and_return("to_pem")
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pem/lib/pem.rb | pem/lib/pem.rb | require_relative 'pem/manager'
require_relative 'pem/options'
require_relative 'pem/module'
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pem/lib/pem/options.rb | pem/lib/pem/options.rb | require 'fastlane_core/configuration/config_item'
require 'credentials_manager/appfile_config'
require 'fastlane/helper/lane_helper'
require_relative 'module'
module PEM
class Options
def self.available_options
user = CredentialsManager::AppfileConfig.try_fetch_value(:apple_dev_portal_id)
user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)
[
FastlaneCore::ConfigItem.new(key: :platform,
description: "Set certificate's platform. Used for creation of production & development certificates. Supported platforms: ios, macos",
short_option: "-m",
env_name: "PEM_PLATFORM",
default_value: "ios",
verify_block: proc do |value|
UI.user_error!("The platform can only be ios or macos") unless ['ios', 'macos'].include?(value)
end),
FastlaneCore::ConfigItem.new(key: :development,
env_name: "PEM_DEVELOPMENT",
description: "Renew the development push certificate instead of the production one",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :website_push,
env_name: "PEM_WEBSITE_PUSH",
description: "Create a Website Push certificate",
is_string: false,
conflicting_options: [:development],
default_value: false),
FastlaneCore::ConfigItem.new(key: :generate_p12,
env_name: "PEM_GENERATE_P12_FILE",
description: "Generate a p12 file additionally to a PEM file",
is_string: false,
default_value: true),
FastlaneCore::ConfigItem.new(key: :active_days_limit,
env_name: "PEM_ACTIVE_DAYS_LIMIT",
description: "If the current certificate is active for less than this number of days, generate a new one",
default_value: 30,
is_string: false,
type: Integer,
verify_block: proc do |value|
UI.user_error!("Value of active_days_limit must be a positive integer or left blank") unless value.kind_of?(Integer) && value > 0
end),
FastlaneCore::ConfigItem.new(key: :force,
env_name: "PEM_FORCE",
description: "Create a new push certificate, even if the current one is active for 30 (or PEM_ACTIVE_DAYS_LIMIT) more days",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :save_private_key,
short_option: "-s",
env_name: "PEM_SAVE_PRIVATEKEY",
description: "Set to save the private RSA key",
is_string: false,
default_value: true),
FastlaneCore::ConfigItem.new(key: :app_identifier,
short_option: "-a",
env_name: "PEM_APP_IDENTIFIER",
description: "The bundle identifier of your app",
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier),
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :username,
short_option: "-u",
env_name: "PEM_USERNAME",
description: "Your Apple ID Username",
default_value: user,
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :team_id,
short_option: "-b",
env_name: "PEM_TEAM_ID",
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_id),
default_value_dynamic: true,
description: "The ID of your Developer Portal team if you're in multiple teams",
optional: true,
verify_block: proc do |value|
ENV["FASTLANE_TEAM_ID"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :team_name,
short_option: "-l",
env_name: "PEM_TEAM_NAME",
description: "The name of your Developer Portal team if you're in multiple teams",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_name),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_TEAM_NAME"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :p12_password,
short_option: "-p",
env_name: "PEM_P12_PASSWORD",
sensitive: true,
description: "The password that is used for your p12 file",
optional: true),
FastlaneCore::ConfigItem.new(key: :pem_name,
short_option: "-o",
env_name: "PEM_FILE_NAME",
description: "The file name of the generated .pem file",
optional: true),
FastlaneCore::ConfigItem.new(key: :output_path,
short_option: "-e",
env_name: "PEM_OUTPUT_PATH",
description: "The path to a directory in which all certificates and private keys should be stored",
default_value: ".")
]
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pem/lib/pem/commands_generator.rb | pem/lib/pem/commands_generator.rb | require 'commander'
require 'fastlane/version'
require 'fastlane_core/configuration/configuration'
require 'fastlane_core/ui/help_formatter'
require_relative 'options'
require_relative 'manager'
HighLine.track_eof = false
module PEM
class CommandsGenerator
include Commander::Methods
def self.start
self.new.run
end
def run
program :name, 'pem'
program :version, Fastlane::VERSION
program :description, 'CLI for \'PEM\' - Automatically generate and renew your push notification profiles'
program :help, 'Author', 'Felix Krause <pem@krausefx.com>'
program :help, 'Website', 'https://fastlane.tools'
program :help, 'Documentation', 'https://docs.fastlane.tools/actions/pem/'
program :help_formatter, FastlaneCore::HelpFormatter
global_option('--verbose') { FastlaneCore::Globals.verbose = true }
global_option('--env STRING[,STRING2]', String, 'Add environment(s) to use with `dotenv`')
command :renew do |c|
c.syntax = 'fastlane pem renew'
c.description = 'Renews the certificate (in case it expired) and shows the path to the generated pem file'
FastlaneCore::CommanderGenerator.new.generate(PEM::Options.available_options, command: c)
c.action do |args, options|
PEM.config = FastlaneCore::Configuration.create(PEM::Options.available_options, options.__hash__)
PEM::Manager.start
end
end
default_command(:renew)
run!
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pem/lib/pem/manager.rb | pem/lib/pem/manager.rb | require 'pathname'
require 'spaceship'
require 'fastlane_core/print_table'
require_relative 'module'
module PEM
# Creates the push profile and stores it in the correct location
class Manager
class << self
def start
FastlaneCore::PrintTable.print_values(config: PEM.config, hide_keys: [:new_profile], title: "Summary for PEM #{Fastlane::VERSION}")
login
existing_certificate = certificate_sorted.detect do |c|
c.owner_name == PEM.config[:app_identifier]
end
if existing_certificate
remaining_days = (existing_certificate.expires - Time.now) / 60 / 60 / 24
display_platform = ''
unless PEM.config[:website_push]
display_platform = "#{PEM.config[:platform]} "
end
UI.message("Existing #{display_platform}push notification profile for '#{existing_certificate.owner_name}' is valid for #{remaining_days.round} more days.")
if remaining_days > PEM.config[:active_days_limit]
if PEM.config[:force]
UI.success("You already have an existing push certificate, but a new one will be created since the --force option has been set.")
else
UI.success("You already have a push certificate, which is active for more than #{PEM.config[:active_days_limit]} more days. No need to create a new one")
UI.success("If you still want to create a new one, use the --force option when running PEM.")
return false
end
end
end
return create_certificate
end
def login
UI.message("Starting login with user '#{PEM.config[:username]}'")
Spaceship.login(PEM.config[:username], nil)
Spaceship.client.select_team
UI.message("Successfully logged in")
end
def create_certificate
UI.important("Creating a new push certificate for app '#{PEM.config[:app_identifier]}'.")
csr, pkey = Spaceship.certificate.create_certificate_signing_request
begin
cert = certificate.create!(csr: csr, bundle_id: PEM.config[:app_identifier])
rescue => ex
if ex.to_s.include?("You already have a current")
# That's the most common failure probably
UI.message(ex.to_s)
UI.user_error!("You already have 2 active push profiles for this application/environment. You'll need to revoke an old certificate to make room for a new one")
else
raise ex
end
end
x509_certificate = cert.download
filename_base = PEM.config[:pem_name] || "#{certificate_type}_#{PEM.config[:app_identifier]}_#{PEM.config[:platform]}"
filename_base = File.basename(filename_base, ".pem") # strip off the .pem if it was provided.
output_path = File.expand_path(PEM.config[:output_path])
FileUtils.mkdir_p(output_path)
if PEM.config[:save_private_key]
private_key_path = File.join(output_path, "#{filename_base}.pkey")
File.write(private_key_path, pkey.to_pem)
UI.message("Private key: ".green + Pathname.new(private_key_path).realpath.to_s)
end
if PEM.config[:generate_p12]
p12_cert_path = File.join(output_path, "#{filename_base}.p12")
p12_password = PEM.config[:p12_password] == "" ? nil : PEM.config[:p12_password]
p12 = OpenSSL::PKCS12.create(p12_password, certificate_type, pkey, x509_certificate)
File.write(p12_cert_path, p12.to_der.force_encoding("UTF-8"))
UI.message("p12 certificate: ".green + Pathname.new(p12_cert_path).realpath.to_s)
end
x509_cert_path = File.join(output_path, "#{filename_base}.pem")
File.write(x509_cert_path, x509_certificate.to_pem + pkey.to_pem)
UI.message("PEM: ".green + Pathname.new(x509_cert_path).realpath.to_s)
return x509_cert_path
end
def certificate
if PEM.config[:website_push]
Spaceship.certificate.website_push
else
platform = PEM.config[:platform]
UI.user_error!('platform parameter is unspecified.') unless platform
case platform
when 'ios'
if PEM.config[:development]
Spaceship.certificate.development_push
else
Spaceship.certificate.production_push
end
when 'macos'
if PEM.config[:development]
Spaceship.certificate.mac_development_push
else
Spaceship.certificate.mac_production_push
end
else
UI.user_error!("Unsupported platform '#{platform}'. Supported platforms for development and production certificates are 'ios' & 'macos'")
end
end
end
def certificate_type
if PEM.config[:development]
'development'
elsif PEM.config[:website_push]
'website'
else
'production'
end
end
def certificate_sorted
certificate.all.sort { |x, y| y.expires <=> x.expires }
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pem/lib/pem/module.rb | pem/lib/pem/module.rb | require 'fastlane_core/helper'
module PEM
# Use this to just setup the configuration attribute and set it later somewhere else
class << self
attr_accessor :config
end
tmp_dir = Dir.tmpdir
TMP_FOLDER = "#{tmp_dir}/fastlane/PEM/"
FileUtils.mkdir_p(TMP_FOLDER)
ENV['FASTLANE_TEAM_ID'] ||= ENV["PEM_TEAM_ID"]
ENV['DELIVER_USER'] ||= ENV["PEM_USERNAME"]
Helper = FastlaneCore::Helper # you gotta love Ruby: Helper.* should use the Helper class contained in FastlaneCore
UI = FastlaneCore::UI
ROOT = Pathname.new(File.expand_path('../../..', __FILE__))
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/spec/merchant_spec.rb | produce/spec/merchant_spec.rb | require "produce/merchant"
describe Produce::Merchant do
describe ".detect_merchant_identifier" do
it "accesses merchant identifier from produce config" do
config = { merchant_identifier: "merchant.com.example.app" }
result = Produce::Merchant.detect_merchant_identifier(config)
expect(result).to eql("merchant.com.example.app")
end
it "accesses merchant identifier from produce config and prepends with merchant." do
config = { merchant_identifier: "com.example.app" }
result = Produce::Merchant.detect_merchant_identifier(config)
expect(result).to eql("merchant.com.example.app")
end
it "falls back to UI.input when in interactive mode" do
config = {}
allow(UI).to receive(:interactive?).and_return(true)
allow(UI).to receive(:input).and_return("merchant.com.example.app")
result = Produce::Merchant.detect_merchant_identifier(config)
expect(result).to eql("merchant.com.example.app")
end
it "raises error when not in interactive mode and no :merchant_identifier is provided" do
config = {}
allow(UI).to receive(:interactive?).and_return(false)
expect { Produce::Merchant.detect_merchant_identifier(config) }.to raise_error(FastlaneCore::Interface::FastlaneError)
end
end
describe ".prepare_identifier" do
it "doesn't prepend merchant. when it already begins with merchant." do
result = Produce::Merchant.prepare_identifier("merchant.com.example.app")
expect(result).to eql("merchant.com.example.app")
end
it "prepends merchant. when identifier doesn't start with merchant." do
result = Produce::Merchant.prepare_identifier("com.example.app")
expect(result).to eql("merchant.com.example.app")
end
end
describe ".input" do
it "falls back to UI.input when in interactive mode" do
config = {}
allow(UI).to receive(:interactive?).and_return(true)
allow(UI).to receive(:input)
result = Produce::Merchant.input("Some instruction", "whatever")
expect(UI).to have_received(:input).with("Some instruction")
end
it "raises error when not in interactive mode and no :merchant_identifier is provided" do
allow(UI).to receive(:interactive?).and_return(false)
allow(UI).to receive(:user_error!)
Produce::Merchant.input("whatever", "error message")
expect(UI).to have_received(:user_error!).with("error message")
end
end
describe ".find_merchant" do
it "checking cache stores found merchant" do
merchant_0 = Object.new
merchant_repo = Object.new
allow(Produce::Merchant).to receive(:mac?).and_return(true)
allow(merchant_repo).to receive(:find).and_return(merchant_0)
result_0 = Produce::Merchant.find_merchant("some-identifier", merchant: merchant_repo)
result_1 = Produce::Merchant.find_merchant("some-identifier", merchant: merchant_repo)
expect(result_0).to equal(result_1)
end
it "checking cache is only used for the same identifier" do
merchant_0 = Object.new
merchant_1 = Object.new
allow(Produce::Merchant).to receive(:mac?).and_return(true)
merchant_repo = Object.new
allow(merchant_repo).to receive(:find).with("some-identifier-0", any_args).and_return(merchant_0)
allow(merchant_repo).to receive(:find).with("some-identifier-1", any_args).and_return(merchant_1)
result_0 = Produce::Merchant.find_merchant("some-identifier-0", merchant: merchant_repo)
result_1 = Produce::Merchant.find_merchant("some-identifier-1", merchant: merchant_repo)
expect(result_0).to equal(merchant_0)
expect(result_1).to equal(merchant_1)
end
end
describe ".mac?" do
it "returns true when config :platform is 'mac'" do
result = Produce::Merchant.mac?({ platform: "mac" })
expect(result).to be_truthy
end
it "returns false when config :platform is not 'mac'" do
result = Produce::Merchant.mac?({ platform: "ios" })
expect(result).to be_falsey
end
end
describe ".merchant_name_from_identifier" do
it "returns a name derived from identifier" do
result = Produce::Merchant.merchant_name_from_identifier("merchant.com.example.app")
expect(result).to eql("App Example Com Merchant")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/spec/commands_generator_spec.rb | produce/spec/commands_generator_spec.rb | require 'produce/commands_generator'
require 'produce/service'
require 'produce/group'
require 'produce/merchant'
require 'produce/cloud_container'
describe Produce::CommandsGenerator do
let(:available_options) { Produce::Options.available_options }
describe ":create option handling" do
it "can use the skip_itc short flag from tool options" do
# leaving out the command name defaults to 'create'
stub_commander_runner_args(['-i', 'true'])
expected_options = FastlaneCore::Configuration.create(available_options, { skip_itc: true })
expect(Produce::Manager).to receive(:start_producing)
Produce::CommandsGenerator.start
expect(Produce.config[:skip_itc]).to be(true)
end
it "can use the skip_devcenter flag from tool options" do
# leaving out the command name defaults to 'create'
stub_commander_runner_args(['--skip_devcenter', 'true'])
expected_options = FastlaneCore::Configuration.create(available_options, { skip_devcenter: true })
expect(Produce::Manager).to receive(:start_producing)
Produce::CommandsGenerator.start
expect(Produce.config[:skip_devcenter]).to be(true)
end
end
describe ":enable_services option handling" do
it "can use the username short flag from tool options" do
stub_commander_runner_args(['enable_services', '-u', 'me@it.com', '--health-kit'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect(Produce::Service).to receive(:enable) do |options, args|
expect(options.health_kit).to be(true)
expect(args).to eq([])
end
Produce::CommandsGenerator.start
expect(Produce.config[:username]).to eq('me@it.com')
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['enable_services', '--app_identifier', 'your.awesome.App', '--game-center=ios'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect(Produce::Service).to receive(:enable) do |options, args|
expect(options.game_center).to eq("ios")
expect(args).to eq([])
end
Produce::CommandsGenerator.start
expect(Produce.config[:app_identifier]).to eq('your.awesome.App')
end
end
describe ":disable_services option handling" do
it "can use the username short flag from tool options" do
stub_commander_runner_args(['disable_services', '-u', 'me@it.com', '--health-kit'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect(Produce::Service).to receive(:disable) do |options, args|
expect(options.health_kit).to be(true)
expect(args).to eq([])
end
Produce::CommandsGenerator.start
expect(Produce.config[:username]).to eq('me@it.com')
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['disable_services', '--app_identifier', 'your.awesome.App', '--game-center'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect(Produce::Service).to receive(:disable) do |options, args|
expect(options.game_center).to be(true)
expect(args).to eq([])
end
Produce::CommandsGenerator.start
expect(Produce.config[:app_identifier]).to eq('your.awesome.App')
end
end
describe ":group option handling" do
def expect_group_create_with(group_name, group_identifier)
fake_group = "fake_group"
expect(Produce::Group).to receive(:new).and_return(fake_group)
expect(fake_group).to receive(:create) do |options, args|
expect(options.group_name).to eq(group_name)
expect(options.group_identifier).to eq(group_identifier)
expect(args).to eq([])
end
end
it "can use the username short flag from tool options" do
stub_commander_runner_args(['group', '-u', 'me@it.com', '-g', 'group.example.app', '-n', 'Example App Group'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect_group_create_with('Example App Group', 'group.example.app')
Produce::CommandsGenerator.start
expect(Produce.config[:username]).to eq('me@it.com')
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['group', '--app_identifier', 'your.awesome.App', '-g', 'group.example.app', '-n', 'Example App Group'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect_group_create_with('Example App Group', 'group.example.app')
Produce::CommandsGenerator.start
expect(Produce.config[:app_identifier]).to eq('your.awesome.App')
end
end
describe ":associate_group option handling" do
def expect_group_associate_with(group_ids)
fake_group = "fake_group"
expect(Produce::Group).to receive(:new).and_return(fake_group)
expect(fake_group).to receive(:associate) do |options, args|
expect(args).to eq(group_ids)
end
end
it "can use the username short flag from tool options" do
stub_commander_runner_args(['associate_group', '-u', 'me@it.com', 'group1.example.app', 'group2.example.app'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect_group_associate_with(['group1.example.app', 'group2.example.app'])
Produce::CommandsGenerator.start
expect(Produce.config[:username]).to eq('me@it.com')
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['associate_group', '--app_identifier', 'your.awesome.App', 'group1.example.app', 'group2.example.app'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect_group_associate_with(['group1.example.app', 'group2.example.app'])
Produce::CommandsGenerator.start
expect(Produce.config[:app_identifier]).to eq('your.awesome.App')
end
end
describe ":cloud_container option handling" do
def expect_cloud_container_create_with(container_name, container_identifier)
fake_container = "fake_container"
expect(Produce::CloudContainer).to receive(:new).and_return(fake_container)
expect(fake_container).to receive(:create) do |options, args|
expect(options.container_name).to eq(container_name)
expect(options.container_identifier).to eq(container_identifier)
expect(args).to eq([])
end
end
it "can use the username short flag from tool options" do
stub_commander_runner_args(['cloud_container', '-u', 'me@it.com', '-g', 'iCloud.com.example.app', '-n', 'Example iCloud Container'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect_cloud_container_create_with('Example iCloud Container', 'iCloud.com.example.app')
Produce::CommandsGenerator.start
expect(Produce.config[:username]).to eq('me@it.com')
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['cloud_container', '--app_identifier', 'your.awesome.App', '-g', 'iCloud.com.example.app', '-n', 'Example iCloud Container'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect_cloud_container_create_with('Example iCloud Container', 'iCloud.com.example.app')
Produce::CommandsGenerator.start
expect(Produce.config[:app_identifier]).to eq('your.awesome.App')
end
end
describe ":associate_cloud_container option handling" do
def expect_cloud_container_associate_with(container_ids)
fake_container = "fake_container"
expect(Produce::CloudContainer).to receive(:new).and_return(fake_container)
expect(fake_container).to receive(:associate) do |options, args|
expect(args).to eq(container_ids)
end
end
it "can use the username short flag from tool options" do
stub_commander_runner_args(['associate_cloud_container', '-u', 'me@it.com', 'iCloud.com.example.app1', 'iCloud.com.example.app2'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect_cloud_container_associate_with(['iCloud.com.example.app1', 'iCloud.com.example.app2'])
Produce::CommandsGenerator.start
expect(Produce.config[:username]).to eq('me@it.com')
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['associate_cloud_container', '--app_identifier', 'your.awesome.App', 'iCloud.com.example.app1', 'iCloud.com.example.app2'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect_cloud_container_associate_with(['iCloud.com.example.app1', 'iCloud.com.example.app2'])
Produce::CommandsGenerator.start
expect(Produce.config[:app_identifier]).to eq('your.awesome.App')
end
end
describe ":merchant option handling" do
def expect_merchant_create_with(merchant_name, merchant_identifier)
fake_merchant = "fake_merchant"
expect(Produce::Merchant).to receive(:new).and_return(fake_merchant)
expect(fake_merchant).to receive(:create) do |options, args|
expect(options.merchant_name).to eq(merchant_name)
expect(options.merchant_identifier).to eq(merchant_identifier)
expect(args).to eq([])
end
end
it "can use the username short flag from tool options" do
stub_commander_runner_args(['merchant', '-u', 'me@it.com', '-o', 'merchant.example.app.production', '-r', 'Example Merchant'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect_merchant_create_with('Example Merchant', 'merchant.example.app.production')
Produce::CommandsGenerator.start
expect(Produce.config[:username]).to eq('me@it.com')
end
end
describe ":associate_merchant option handling" do
def expect_merchant_associate_with(merchant_ids)
fake_merchant = "fake_merchant"
expect(Produce::Merchant).to receive(:new).and_return(fake_merchant)
expect(fake_merchant).to receive(:associate) do |options, args|
expect(args).to eq(merchant_ids)
end
end
it "can associate multiple merchant identifiers" do
stub_commander_runner_args(['associate_merchant', 'merchant.example.app.sandbox', 'merchant.example.app.production'])
expect_merchant_associate_with(['merchant.example.app.sandbox', 'merchant.example.app.production'])
Produce::CommandsGenerator.start
end
it "can use the username short flag from tool options" do
stub_commander_runner_args(['associate_merchant', '-u', 'me@it.com', 'merchant.example.app.production'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect_merchant_associate_with(['merchant.example.app.production'])
Produce::CommandsGenerator.start
expect(Produce.config[:username]).to eq('me@it.com')
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/spec/manager_spec.rb | produce/spec/manager_spec.rb | describe Produce do
describe "Manager" do
it "should auto convert string hash keys to symbol keys" do
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, {
username: "helmut@januschka.com",
enable_services: { "data_protection" => "complete" },
skip_itc: true
})
instance = Produce::DeveloperCenter.new
features = instance.enable_services
expect(features["dataProtection"].value).to eq("complete")
end
it "accepts symbol'd hash" do
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, {
username: "helmut@januschka.com",
enable_services: { data_protection: "complete" },
skip_itc: true
})
instance = Produce::DeveloperCenter.new
features = instance.enable_services
expect(features["dataProtection"].value).to eq("complete")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce.rb | produce/lib/produce.rb | require_relative 'produce/manager'
require_relative 'produce/options'
require_relative 'produce/developer_center'
require_relative 'produce/itunes_connect'
require_relative 'produce/available_default_languages'
require_relative 'produce/module'
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/developer_center.rb | produce/lib/produce/developer_center.rb | require 'spaceship'
require_relative 'module'
module Produce
class DeveloperCenter
SERVICE_ON = "on"
SERVICE_OFF = "off"
SERVICE_COMPLETE = "complete"
SERVICE_UNLESS_OPEN = "unlessopen"
SERVICE_UNTIL_FIRST_LAUNCH = "untilfirstauth"
SERVICE_LEGACY = "legacy"
SERVICE_CLOUDKIT = "cloudkit"
SERVICE_GAME_CENTER_IOS = "ios"
SERVICE_GAME_CENTER_MAC = "mac"
SERVICE_PRIMARY_APP_CONSENT = "on"
ALLOWED_SERVICES = {
access_wifi: [SERVICE_ON, SERVICE_OFF],
app_attest: [SERVICE_ON, SERVICE_OFF],
app_group: [SERVICE_ON, SERVICE_OFF],
apple_pay: [SERVICE_ON, SERVICE_OFF],
associated_domains: [SERVICE_ON, SERVICE_OFF],
auto_fill_credential: [SERVICE_ON, SERVICE_OFF],
class_kit: [SERVICE_ON, SERVICE_OFF],
declared_age_range: [SERVICE_ON, SERVICE_OFF],
icloud: [SERVICE_LEGACY, SERVICE_CLOUDKIT],
custom_network_protocol: [SERVICE_ON, SERVICE_OFF],
data_protection: [
SERVICE_COMPLETE,
SERVICE_UNLESS_OPEN,
SERVICE_UNTIL_FIRST_LAUNCH
],
extended_virtual_address_space: [SERVICE_ON, SERVICE_OFF],
family_controls: [SERVICE_ON, SERVICE_OFF],
file_provider_testing_mode: [SERVICE_ON, SERVICE_OFF],
fonts: [SERVICE_ON, SERVICE_OFF],
game_center: [SERVICE_GAME_CENTER_IOS, SERVICE_GAME_CENTER_MAC],
health_kit: [SERVICE_ON, SERVICE_OFF],
hls_interstitial_preview: [SERVICE_ON, SERVICE_OFF],
home_kit: [SERVICE_ON, SERVICE_OFF],
hotspot: [SERVICE_ON, SERVICE_OFF],
in_app_purchase: [SERVICE_ON, SERVICE_OFF],
inter_app_audio: [SERVICE_ON, SERVICE_OFF],
low_latency_hls: [SERVICE_ON, SERVICE_OFF],
managed_associated_domains: [SERVICE_ON, SERVICE_OFF],
maps: [SERVICE_ON, SERVICE_OFF],
multipath: [SERVICE_ON, SERVICE_OFF],
network_extension: [SERVICE_ON, SERVICE_OFF],
nfc_tag_reading: [SERVICE_ON, SERVICE_OFF],
personal_vpn: [SERVICE_ON, SERVICE_OFF],
passbook: [SERVICE_ON, SERVICE_OFF],
push_notification: [SERVICE_ON, SERVICE_OFF],
sign_in_with_apple: [SERVICE_PRIMARY_APP_CONSENT],
siri_kit: [SERVICE_ON, SERVICE_OFF],
system_extension: [SERVICE_ON, SERVICE_OFF],
user_management: [SERVICE_ON, SERVICE_OFF],
vpn_configuration: [SERVICE_ON, SERVICE_OFF],
wallet: [SERVICE_ON, SERVICE_OFF],
wireless_accessory: [SERVICE_ON, SERVICE_OFF],
car_play_audio_app: [SERVICE_ON, SERVICE_OFF],
car_play_messaging_app: [SERVICE_ON, SERVICE_OFF],
car_play_navigation_app: [SERVICE_ON, SERVICE_OFF],
car_play_voip_calling_app: [SERVICE_ON, SERVICE_OFF],
critical_alerts: [SERVICE_ON, SERVICE_OFF],
hotspot_helper: [SERVICE_ON, SERVICE_OFF],
driver_kit: [SERVICE_ON, SERVICE_OFF],
driver_kit_endpoint_security: [SERVICE_ON, SERVICE_OFF],
driver_kit_family_hid_device: [SERVICE_ON, SERVICE_OFF],
driver_kit_family_networking: [SERVICE_ON, SERVICE_OFF],
driver_kit_family_serial: [SERVICE_ON, SERVICE_OFF],
driver_kit_hid_event_service: [SERVICE_ON, SERVICE_OFF],
driver_kit_transport_hid: [SERVICE_ON, SERVICE_OFF],
multitasking_camera_access: [SERVICE_ON, SERVICE_OFF],
sf_universal_link_api: [SERVICE_ON, SERVICE_OFF],
vp9_decoder: [SERVICE_ON, SERVICE_OFF],
music_kit: [SERVICE_ON, SERVICE_OFF],
shazam_kit: [SERVICE_ON, SERVICE_OFF],
communication_notifications: [SERVICE_ON, SERVICE_OFF],
group_activities: [SERVICE_ON, SERVICE_OFF],
health_kit_estimate_recalibration: [SERVICE_ON, SERVICE_OFF],
time_sensitive_notifications: [SERVICE_ON, SERVICE_OFF],
}
def run
login
create_new_app
end
def create_new_app
ENV["CREATED_NEW_APP_ID"] = Time.now.to_i.to_s
if app_exists?
UI.success("[DevCenter] App '#{Produce.config[:app_identifier]}' already exists, nothing to do on the Dev Center")
ENV["CREATED_NEW_APP_ID"] = nil
# Nothing to do here
else
app_name = Produce.config[:app_name]
UI.message("Creating new app '#{app_name}' on the Apple Dev Center")
app = Spaceship.app.create!(bundle_id: app_identifier,
name: app_name,
enable_services: enable_services,
mac: platform == "osx")
if app.name != Produce.config[:app_name]
UI.important("Your app name includes non-ASCII characters, which are not supported by the Apple Developer Portal.")
UI.important("To fix this a unique (internal) name '#{app.name}' has been created for you. Your app's real name '#{Produce.config[:app_name]}'")
UI.important("will still show up correctly on App Store Connect and the App Store.")
end
UI.message("Created app #{app.app_id}")
UI.crash!("Something went wrong when creating the new app - it's not listed in the apps list") unless app_exists?
ENV["CREATED_NEW_APP_ID"] = Time.now.to_i.to_s
UI.success("Finished creating new app '#{app_name}' on the Dev Center")
end
return true
end
def enable_services
app_service = Spaceship.app_service
enabled_clean_options = {}
# "enabled_features" was deprecated in favor of "enable_services"
config_enabled_services = Produce.config[:enable_services] || Produce.config[:enabled_features]
config_enabled_services.each do |k, v|
if k.to_sym == :data_protection
case v
when SERVICE_COMPLETE
enabled_clean_options[app_service.data_protection.complete.service_id] = app_service.data_protection.complete
when SERVICE_UNLESS_OPEN
enabled_clean_options[app_service.data_protection.unlessopen.service_id] = app_service.data_protection.unlessopen
when SERVICE_UNTIL_FIRST_LAUNCH
enabled_clean_options[app_service.data_protection.untilfirstauth.service_id] = app_service.data_protection.untilfirstauth
end
elsif k.to_sym == :icloud
case v
when SERVICE_LEGACY
enabled_clean_options[app_service.cloud.on.service_id] = app_service.cloud.on
enabled_clean_options[app_service.cloud_kit.xcode5_compatible.service_id] = app_service.cloud_kit.xcode5_compatible
when SERVICE_CLOUDKIT
enabled_clean_options[app_service.cloud.on.service_id] = app_service.cloud.on
enabled_clean_options[app_service.cloud_kit.cloud_kit.service_id] = app_service.cloud_kit.cloud_kit
end
else
if v == SERVICE_ON
enabled_clean_options[app_service.send(k.to_s).on.service_id] = app_service.send(k.to_s).on
else
enabled_clean_options[app_service.send(k.to_s).off.service_id] = app_service.send(k.to_s).off
end
end
end
enabled_clean_options
end
def app_identifier
Produce.config[:app_identifier].to_s
end
private
def platform
# This was added to support creation of multiple platforms
# Produce::ItunesConnect can take an array of platforms to create for App Store Connect
# but the Developer Center is now platform agnostic so we choose any platform here
#
# Platform won't be needed at all in the future when this is change over to use Spaceship::ConnectAPI
(Produce.config[:platforms] || []).first || Produce.config[:platform]
end
def app_exists?
Spaceship.app.find(app_identifier, mac: platform == "osx") != nil
end
def login
Spaceship.login(Produce.config[:username], nil)
Spaceship.select_team
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/group.rb | produce/lib/produce/group.rb | require 'spaceship'
require_relative 'module'
module Produce
class Group
def create(options, _args)
login
ENV["CREATED_NEW_GROUP_ID"] = Time.now.to_i.to_s
group_identifier = options.group_identifier || UI.input("Group identifier: ")
if app_group_exists?(group_identifier)
UI.success("[DevCenter] Group '#{options.group_name} (#{options.group_identifier})' already exists, nothing to do on the Dev Center")
ENV["CREATED_NEW_GROUP_ID"] = nil
# Nothing to do here
else
group_name = options.group_name || group_identifier.split(".").map(&:capitalize).reverse.join(' ')
UI.success("Creating new app group '#{group_name}' with identifier '#{group_identifier}' on the Apple Dev Center")
group = Spaceship.app_group.create!(group_id: group_identifier,
name: group_name)
if group.name != group_name
UI.important("Your group name includes non-ASCII characters, which are not supported by the Apple Developer Portal.")
UI.important("To fix this a unique (internal) name '#{group.name}' has been created for you.")
end
UI.message("Created group #{group.app_group_id}")
UI.user_error!("Something went wrong when creating the new app group - it's not listed in the app groups list") unless app_group_exists?(group_identifier)
ENV["CREATED_NEW_GROUP_ID"] = Time.now.to_i.to_s
UI.success("Finished creating new app group '#{group_name}' on the Dev Center")
end
return true
end
def associate(_options, args)
login
if !app_exists?
UI.message("[DevCenter] App '#{Produce.config[:app_identifier]}' does not exist, nothing to associate with the groups")
else
app = Spaceship.app.find(app_identifier)
UI.user_error!("Something went wrong when fetching the app - it's not listed in the apps list") if app.nil?
new_groups = []
UI.message("Validating groups before association")
args.each do |group_identifier|
if !app_group_exists?(group_identifier)
UI.message("[DevCenter] App group '#{group_identifier}' does not exist, please create it first, skipping for now")
else
new_groups.push(Spaceship.app_group.find(group_identifier))
end
end
UI.message("Finalising association with #{new_groups.count} groups")
app.associate_groups(new_groups)
UI.success("Done!")
end
return true
end
def login
UI.message("Starting login with user '#{Produce.config[:username]}'")
Spaceship.login(Produce.config[:username], nil)
Spaceship.select_team
UI.message("Successfully logged in")
end
def app_identifier
Produce.config[:app_identifier].to_s
end
def app_group_exists?(identifier)
Spaceship.app_group.find(identifier) != nil
end
def app_exists?
Spaceship.app.find(app_identifier) != nil
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/options.rb | produce/lib/produce/options.rb | require 'fastlane_core/configuration/config_item'
require 'credentials_manager/appfile_config'
require_relative 'module'
require_relative 'developer_center'
module Produce
class Options
def self.available_options
user = CredentialsManager::AppfileConfig.try_fetch_value(:apple_dev_portal_id)
user ||= CredentialsManager::AppfileConfig.try_fetch_value(:apple_id)
[
FastlaneCore::ConfigItem.new(key: :username,
short_option: "-u",
env_name: "PRODUCE_USERNAME",
description: "Your Apple ID Username",
code_gen_sensitive: true,
default_value: user,
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :app_identifier,
env_name: "PRODUCE_APP_IDENTIFIER",
short_option: "-a",
description: "App Identifier (Bundle ID, e.g. com.krausefx.app)",
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier),
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :bundle_identifier_suffix,
short_option: "-e",
env_name: "PRODUCE_APP_IDENTIFIER_SUFFIX",
optional: true,
description: "App Identifier Suffix (Ignored if App Identifier does not end with .*)"),
FastlaneCore::ConfigItem.new(key: :app_name,
env_name: "PRODUCE_APP_NAME",
short_option: "-q",
description: "App Name"),
FastlaneCore::ConfigItem.new(key: :app_version,
short_option: "-z",
optional: true,
env_name: "PRODUCE_VERSION",
description: "Initial version number (e.g. '1.0')"),
FastlaneCore::ConfigItem.new(key: :sku,
env_name: "PRODUCE_SKU",
short_option: "-y",
description: "SKU Number (e.g. '1234')",
code_gen_sensitive: true,
default_value: Time.now.to_i.to_s,
default_value_dynamic: true,
is_string: true),
FastlaneCore::ConfigItem.new(key: :platform,
short_option: "-j",
env_name: "PRODUCE_PLATFORM",
description: "The platform to use (optional)",
conflicting_options: [:platforms],
optional: true,
default_value: "ios",
verify_block: proc do |value|
UI.user_error!("The platform can only be ios, osx or tvos") unless %w(ios osx tvos).include?(value)
end),
FastlaneCore::ConfigItem.new(key: :platforms,
short_option: "-J",
env_name: "PRODUCE_PLATFORMS",
description: "The platforms to use (optional)",
conflicting_options: [:platform],
optional: true,
type: Array,
verify_block: proc do |values|
types = %w(ios osx tvos)
UI.user_error!("The platform can only be #{types}") unless (values - types).empty?
end),
FastlaneCore::ConfigItem.new(key: :language,
short_option: "-m",
env_name: "PRODUCE_LANGUAGE",
description: "Primary Language (e.g. 'en-US', 'fr-FR')",
default_value: "English",
verify_block: proc do |language|
end),
FastlaneCore::ConfigItem.new(key: :company_name,
short_option: "-c",
env_name: "PRODUCE_COMPANY_NAME",
description: "The name of your company. It's used to set company name on App Store Connect team's app pages. Only required if it's the first app you create",
optional: true),
FastlaneCore::ConfigItem.new(key: :skip_itc,
short_option: "-i",
env_name: "PRODUCE_SKIP_ITC",
description: "Skip the creation of the app on App Store Connect",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :itc_users,
short_option: "-s",
env_name: "ITC_USERS",
optional: true,
type: Array,
description: "Array of App Store Connect users. If provided, you can limit access to this newly created app for users with the App Manager, Developer, Marketer or Sales roles",
is_string: false),
# Deprecating this in favor of a rename from "enabled_features" to "enable_services"
FastlaneCore::ConfigItem.new(key: :enabled_features,
deprecated: "Please use `enable_services` instead",
display_in_shell: false,
env_name: "PRODUCE_ENABLED_FEATURES",
description: "Array with Spaceship App Services",
is_string: false,
default_value: {},
verify_block: proc do |value|
allowed_keys = Produce::DeveloperCenter::ALLOWED_SERVICES.keys
UI.user_error!("enabled_features has to be of type Hash") unless value.kind_of?(Hash)
value.each do |key, v|
UI.user_error!("The key: '#{key}' is not supported in `enabled_features' - following keys are available: [#{allowed_keys.join(',')}]") unless allowed_keys.include?(key.to_sym)
end
end),
FastlaneCore::ConfigItem.new(key: :enable_services,
display_in_shell: false,
env_name: "PRODUCE_ENABLE_SERVICES",
description: "Array with Spaceship App Services (e.g. #{allowed_services_description})",
is_string: false,
default_value: {},
verify_block: proc do |value|
allowed_keys = Produce::DeveloperCenter::ALLOWED_SERVICES.keys
UI.user_error!("enable_services has to be of type Hash") unless value.kind_of?(Hash)
value.each do |key, v|
UI.user_error!("The key: '#{key}' is not supported in `enable_services' - following keys are available: [#{allowed_keys.join(',')}]") unless allowed_keys.include?(key.to_sym)
end
end),
FastlaneCore::ConfigItem.new(key: :skip_devcenter,
short_option: "-d",
env_name: "PRODUCE_SKIP_DEVCENTER",
description: "Skip the creation of the app on the Apple Developer Portal",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :team_id,
short_option: "-b",
env_name: "PRODUCE_TEAM_ID",
description: "The ID of your Developer Portal team if you're in multiple teams",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_id),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_TEAM_ID"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :team_name,
short_option: "-l",
env_name: "PRODUCE_TEAM_NAME",
description: "The name of your Developer Portal team if you're in multiple teams",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:team_name),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_TEAM_NAME"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :itc_team_id,
short_option: "-k",
env_name: "PRODUCE_ITC_TEAM_ID",
description: "The ID of your App Store Connect team if you're in multiple teams",
optional: true,
is_string: false, # as we also allow integers, which we convert to strings anyway
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:itc_team_id),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_ITC_TEAM_ID"] = value.to_s
end),
FastlaneCore::ConfigItem.new(key: :itc_team_name,
short_option: "-p",
env_name: "PRODUCE_ITC_TEAM_NAME",
description: "The name of your App Store Connect team if you're in multiple teams",
optional: true,
code_gen_sensitive: true,
default_value: CredentialsManager::AppfileConfig.try_fetch_value(:itc_team_name),
default_value_dynamic: true,
verify_block: proc do |value|
ENV["FASTLANE_ITC_TEAM_NAME"] = value.to_s
end)
]
end
def self.allowed_services_description
return Produce::DeveloperCenter::ALLOWED_SERVICES.map do |k, v|
"#{k}: (#{v.join('|')})"
end.join(", ")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/merchant.rb | produce/lib/produce/merchant.rb | require 'spaceship'
require_relative 'module'
module Produce
class Merchant
def create(_options, _args)
login
merchant_identifier = detect_merchant_identifier
merchant = find_merchant(merchant_identifier)
if merchant
UI.success("[DevCenter] Merchant '#{merchant.bundle_id})' already exists, nothing to do on the Dev Center")
else
merchant_name = Produce.config[:merchant_name] || merchant_name_from_identifier(merchant_identifier)
UI.success("Creating new merchant '#{merchant_name}' with identifier '#{merchant_identifier}' on the Apple Dev Center")
merchant = Spaceship.merchant.create!(bundle_id: merchant_identifier, name: merchant_name, mac: self.class.mac?)
if merchant.name != merchant_name
UI.important("Your merchant name might include non-ASCII characters, which are not supported by the Apple Developer Portal.")
UI.important("To fix this a unique (internal) name '#{merchant.name}' has been created for you.")
end
UI.message("Created merchant #{merchant.merchant_id}")
UI.success("Finished creating new merchant '#{merchant_name}' on the Dev Center")
end
end
def associate(_options, args)
login
app = Spaceship.app.find(app_identifier)
if app
app.update_service(Spaceship.app_service.apple_pay.on)
UI.message("Validating merchants before association")
# associate requires identifiers to exist. This splits the provided identifiers into existing/non-existing. See: https://ruby-doc.org/core/Enumerable.html#method-i-partition
valid_identifiers, errored_identifiers = args.partition { |identifier| merchant_exists?(identifier) }
new_merchants = valid_identifiers.map { |identifier| find_merchant(identifier) }
errored_identifiers.each do |merchant_identifier|
UI.message("[DevCenter] Merchant '#{merchant_identifier}' does not exist, please create it first, skipping for now")
end
UI.message("Finalising association with #{new_merchants.count} #{pluralize('merchant', new_merchants)}")
app.associate_merchants(new_merchants)
UI.success("Done!")
else
UI.message("[DevCenter] App '#{Produce.config[:app_identifier]}' does not exist, nothing to associate with the merchants")
end
end
def login
UI.message("Starting login with user '#{Produce.config[:username]}'")
Spaceship.login(Produce.config[:username], nil)
Spaceship.select_team
UI.message("Successfully logged in")
end
def app_identifier
Produce.config[:app_identifier]
end
def pluralize(singular, arr)
return singular if arr.count == 1
"#{singular}s"
end
def merchant_exists?(identifier)
find_merchant(identifier)
end
def detect_merchant_identifier
self.class.detect_merchant_identifier
end
def self.detect_merchant_identifier(config = Produce.config)
identifier = config[:merchant_identifier] || input("Merchant identifier (reverse-domain name style string starting with 'merchant'): ", ":merchant_identifier option is required")
prepare_identifier(identifier)
end
def self.input(message, error_message)
if UI.interactive?
UI.input(message)
else
UI.user_error!(error_message)
end
end
def self.prepare_identifier(identifier)
return identifier if identifier.start_with?("merchant.")
"merchant.#{identifier}"
end
def find_merchant(identifier)
self.class.find_merchant(identifier)
end
def self.find_merchant(identifier, merchant: Spaceship.merchant)
@cache ||= {}
@cache[identifier] ||= merchant.find(identifier, mac: mac?)
end
def self.mac?(config = Produce.config)
config[:platform].to_s == "mac"
end
def merchant_name_from_identifier(identifier)
self.class.merchant_name_from_identifier(identifier)
end
def self.merchant_name_from_identifier(identifier)
capitalized_words = identifier.split(".").map(&:capitalize)
capitalized_words.reverse.join(' ')
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/commands_generator.rb | produce/lib/produce/commands_generator.rb | require 'commander'
require 'fastlane/version'
require 'fastlane_core/ui/help_formatter'
require 'fastlane_core/configuration/config_item'
require 'fastlane_core/print_table'
require_relative 'module'
require_relative 'manager'
require_relative 'options'
HighLine.track_eof = false
module Produce
class CommandsGenerator
include Commander::Methods
def self.start
self.new.run
end
def run
program :name, 'produce'
program :version, Fastlane::VERSION
program :description, 'CLI for \'produce\''
program :help, 'Author', 'Felix Krause <produce@krausefx.com>'
program :help, 'Website', 'https://fastlane.tools'
program :help, 'Documentation', 'https://docs.fastlane.tools/actions/produce/'
program :help_formatter, FastlaneCore::HelpFormatter
global_option('--verbose') { FastlaneCore::Globals.verbose = true }
global_option('--env STRING[,STRING2]', String, 'Add environment(s) to use with `dotenv`')
command :create do |c|
c.syntax = 'fastlane produce create'
c.description = 'Creates a new app on App Store Connect and the Apple Developer Portal'
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, options.__hash__)
puts(Produce::Manager.start_producing)
end
end
command :enable_services do |c|
c.syntax = 'fastlane produce enable_services -a APP_IDENTIFIER SERVICE1, SERVICE2, ...'
c.description = 'Enable specific Application Services for a specific app on the Apple Developer Portal'
c.example('Enable HealthKit, HomeKit and Passbook', 'fastlane produce enable_services -a com.example.app --healthkit --homekit --passbook')
c.option('--access-wifi', 'Enable Access Wifi')
c.option('--app-attest', 'Enable App Attest')
c.option('--app-group', 'Enable App Group')
c.option('--apple-pay', 'Enable Apple Pay')
c.option('--associated-domains', 'Enable Associated Domains')
c.option('--auto-fill-credential', 'Enable Auto Fill Credential')
c.option('--class-kit', 'Enable Class Kit')
c.option('--icloud STRING', String, 'Enable iCloud, suitable values are "xcode5_compatible" and "xcode6_compatible"')
c.option('--custom-network-protocol', 'Enable Custom Network Protocol')
c.option('--data-protection STRING', String, 'Enable Data Protection, suitable values are "complete", "unlessopen" and "untilfirstauth"')
c.option('--family-controls', 'Enable Family Controls')
c.option('--file-provider-testing-mode', 'Enable File Provider Testing Mode')
c.option('--fonts', 'Enable Fonts')
c.option('--extended-virtual-address-space', 'Enable Extended Virtual Address Space')
c.option('--declared-age-range', 'Enable Declared Age Range capability')
c.option('--game-center STRING', String, 'Enable Game Center, suitable values are "ios" and "macos"')
c.option('--health-kit', 'Enable Health Kit')
c.option('--hls-interstitial-preview', 'Enable Hls Interstitial Preview')
c.option('--home-kit', 'Enable Home Kit')
c.option('--hotspot', 'Enable Hotspot')
c.option('--in-app-purchase', 'Enable In App Purchase')
c.option('--inter-app-audio', 'Enable Inter App Audio')
c.option('--low-latency-hls', 'Enable Low Latency Hls')
c.option('--managed-associated-domains', 'Enable Managed Associated Domains')
c.option('--maps', 'Enable Maps')
c.option('--multipath', 'Enable Multipath')
c.option('--network-extension', 'Enable Network Extension')
c.option('--nfc-tag-reading', 'Enable NFC Tag Reading')
c.option('--personal-vpn', 'Enable Personal VPN')
c.option('--passbook', 'Enable Passbook (deprecated)')
c.option('--push-notification', 'Enable Push Notification')
c.option('--sign-in-with-apple', 'Enable Sign In With Apple')
c.option('--siri-kit', 'Enable Siri Kit')
c.option('--system-extension', 'Enable System Extension')
c.option('--user-management', 'Enable User Management')
c.option('--vpn-configuration', 'Enable Vpn Configuration (deprecated)')
c.option('--wallet', 'Enable Wallet')
c.option('--wireless-accessory', 'Enable Wireless Accessory')
c.option('--car-play-audio-app', 'Enable Car Play Audio App')
c.option('--car-play-messaging-app', 'Enable Car Play Messaging App')
c.option('--car-play-navigation-app', 'Enable Car Play Navigation App')
c.option('--car-play-voip-calling-app', 'Enable Car Play Voip Calling App')
c.option('--critical-alerts', 'Enable Critical Alerts')
c.option('--hotspot-helper', 'Enable Hotspot Helper')
c.option('--driver-kit', 'Enable DriverKit')
c.option('--driver-kit-endpoint-security', 'Enable DriverKit Endpoint Security')
c.option('--driver-kit-family-hid-device', 'Enable DriverKit Family HID Device')
c.option('--driver-kit-family-networking', 'Enable DriverKit Family Networking')
c.option('--driver-kit-family-serial', 'Enable DriverKit Family Serial')
c.option('--driver-kit-hid-event-service', 'Enable DriverKit HID EventService')
c.option('--driver-kit-transport-hid', 'Enable DriverKit Transport HID')
c.option('--multitasking-camera-access', 'Enable Multitasking Camera Access')
c.option('--sf-universal-link-api', 'Enable SFUniversalLink API')
c.option('--vp9-decoder', 'Enable VP9 Decoder')
c.option('--music-kit', 'Enable MusicKit')
c.option('--shazam-kit', 'Enable ShazamKit')
c.option('--communication-notifications', 'Enable Communication Notifications')
c.option('--group-activities', 'Enable Group Activities')
c.option('--health-kit-estimate-recalibration', 'Enable HealthKit Estimate Recalibration')
c.option('--time-sensitive-notifications', 'Enable Time Sensitive Notifications')
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
# Filter the options so that we can still build the configuration
allowed_keys = Produce::Options.available_options.collect(&:key)
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, options.__hash__.select { |key, value| allowed_keys.include?(key) })
require 'produce/service'
Produce::Service.enable(options, args)
end
end
command :disable_services do |c|
c.syntax = 'fastlane produce disable_services -a APP_IDENTIFIER SERVICE1, SERVICE2, ...'
c.description = 'Disable specific Application Services for a specific app on the Apple Developer Portal'
c.example('Disable HealthKit', 'fastlane produce disable_services -a com.example.app --healthkit')
c.option('--access-wifi', 'Disable Access Wifi')
c.option('--app-attest', 'Disable App Attest')
c.option('--app-group', 'Disable App Group')
c.option('--apple-pay', 'Disable Apple Pay')
c.option('--associated-domains', 'Disable Associated Domains')
c.option('--auto-fill-credential', 'Disable Auto Fill Credential')
c.option('--class-kit', 'Disable Class Kit')
c.option('--icloud', 'Disable iCloud')
c.option('--custom-network-protocol', 'Disable Custom Network Protocol')
c.option('--data-protection', 'Disable Data Protection')
c.option('--extended-virtual-address-space', 'Disable Extended Virtual Address Space')
c.option('--declared-age-range', 'Disable Declared Age Range capability')
c.option('--family-controls', 'Disable Family Controls')
c.option('--file-provider-testing-mode', 'Disable File Provider Testing Mode')
c.option('--fonts', 'Disable Fonts')
c.option('--game-center', 'Disable Game Center')
c.option('--health-kit', 'Disable Health Kit')
c.option('--hls-interstitial-preview', 'Disable Hls Interstitial Preview')
c.option('--home-kit', 'Disable Home Kit')
c.option('--hotspot', 'Disable Hotspot')
c.option('--in-app-purchase', 'Disable In App Purchase')
c.option('--inter-app-audio', 'Disable Inter App Audio')
c.option('--low-latency-hls', 'Disable Low Latency Hls')
c.option('--managed-associated-domains', 'Disable Managed Associated Domains')
c.option('--maps', 'Disable Maps')
c.option('--multipath', 'Disable Multipath')
c.option('--network-extension', 'Disable Network Extension')
c.option('--nfc-tag-reading', 'Disable NFC Tag Reading')
c.option('--personal-vpn', 'Disable Personal VPN')
c.option('--passbook', 'Disable Passbook (deprecated)')
c.option('--push-notification', 'Disable Push Notification')
c.option('--sign-in-with-apple', 'Disable Sign In With Apple')
c.option('--siri-kit', 'Disable Siri Kit')
c.option('--system-extension', 'Disable System Extension')
c.option('--user-management', 'Disable User Management')
c.option('--vpn-configuration', 'Disable Vpn Configuration (deprecated)')
c.option('--wallet', 'Disable Wallet')
c.option('--wireless-accessory', 'Disable Wireless Accessory')
c.option('--car-play-audio-app', 'Disable Car Play Audio App')
c.option('--car-play-messaging-app', 'Disable Car Play Messaging App')
c.option('--car-play-navigation-app', 'Disable Car Play Navigation App')
c.option('--car-play-voip-calling-app', 'Disable Car Play Voip Calling App')
c.option('--critical-alerts', 'Disable Critical Alerts')
c.option('--hotspot-helper', 'Disable Hotspot Helper')
c.option('--driver-kit', 'Disable DriverKit')
c.option('--driver-kit-endpoint-security', 'Disable DriverKit Endpoint Security')
c.option('--driver-kit-family-hid-device', 'Disable DriverKit Family HID Device')
c.option('--driver-kit-family-networking', 'Disable DriverKit Family Networking')
c.option('--driver-kit-family-serial', 'Disable DriverKit Family Serial')
c.option('--driver-kit-hid-event-service', 'Disable DriverKit HID EventService')
c.option('--driver-kit-transport-hid', 'Disable DriverKit Transport HID')
c.option('--multitasking-camera-access', 'Disable Multitasking Camera Access')
c.option('--sf-universal-link-api', 'Disable SFUniversalLink API')
c.option('--vp9-decoder', 'Disable VP9 Decoder')
c.option('--music-kit', 'Disable MusicKit')
c.option('--shazam-kit', 'Disable ShazamKit')
c.option('--communication-notifications', 'Disable Communication Notifications')
c.option('--group-activities', 'Disable Group Activities')
c.option('--health-kit-estimate-recalibration', 'Disable HealthKit Estimate Recalibration')
c.option('--time-sensitive-notifications', 'Disable Time Sensitive Notifications')
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
# Filter the options so that we can still build the configuration
allowed_keys = Produce::Options.available_options.collect(&:key)
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, options.__hash__.select { |key, value| allowed_keys.include?(key) })
require 'produce/service'
Produce::Service.disable(options, args)
end
end
command :available_services do |c|
c.syntax = 'fastlane produce available_services -a APP_IDENTIFIER'
c.description = 'Displays a list of allowed Application Services for a specific app.'
c.example('Check Available Services', 'fastlane produce available_services -a com.example.app')
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
# Filter the options so that we can still build the configuration
allowed_keys = Produce::Options.available_options.collect(&:key)
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, options.__hash__.select { |key, value| allowed_keys.include?(key) })
require 'produce/service'
require 'terminal-table'
services = Produce::Service.available_services(options, args)
rows = services.map { |capabilities| [capabilities.name, capabilities.id, capabilities.description] }
table = Terminal::Table.new(
title: "Available Services",
headings: ['Name', 'ID', 'Description'],
rows: FastlaneCore::PrintTable.transform_output(rows),
style: { all_separators: true }
)
puts(table)
end
end
command :group do |c|
c.syntax = 'fastlane produce group'
c.description = 'Ensure that a specific App Group exists'
c.example('Create group', 'fastlane produce group -g group.example.app -n "Example App Group"')
c.option('-n', '--group_name STRING', String, 'Name for the group that is created (PRODUCE_GROUP_NAME)')
c.option('-g', '--group_identifier STRING', String, 'Group identifier for the group (PRODUCE_GROUP_IDENTIFIER)')
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
allowed_keys = Produce::Options.available_options.collect(&:key)
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, options.__hash__.select { |key, value| allowed_keys.include?(key) })
require 'produce/group'
Produce::Group.new.create(options, args)
end
end
command :associate_group do |c|
c.syntax = 'fastlane produce associate_group -a APP_IDENTIFIER GROUP_IDENTIFIER1, GROUP_IDENTIFIER2, ...'
c.description = 'Associate with a group, which is created if needed or simply located otherwise'
c.example('Associate with group', 'fastlane produce associate-group -a com.example.app group.example.com')
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, options.__hash__)
require 'produce/group'
Produce::Group.new.associate(options, args)
end
end
command :cloud_container do |c|
c.syntax = 'fastlane produce cloud_container'
c.description = 'Ensure that a specific iCloud Container exists'
c.example('Create iCloud Container', 'fastlane produce cloud_container -g iCloud.com.example.app -n "Example iCloud Container"')
c.option('-n', '--container_name STRING', String, 'Name for the iCloud Container that is created (PRODUCE_CLOUD_CONTAINER_NAME)')
c.option('-g', '--container_identifier STRING', String, 'Identifier for the iCloud Container (PRODUCE_CLOUD_CONTAINER_IDENTIFIER')
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
allowed_keys = Produce::Options.available_options.collect(&:key)
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, options.__hash__.select { |key, value| allowed_keys.include?(key) })
require 'produce/cloud_container'
Produce::CloudContainer.new.create(options, args)
end
end
command :associate_cloud_container do |c|
c.syntax = 'fastlane produce associate_cloud_container -a APP_IDENTIFIER CONTAINER_IDENTIFIER1, CONTAINER_IDENTIFIER2, ...'
c.description = 'Associate with a iCloud Container, which is created if needed or simply located otherwise'
c.example('Associate with iCloud Container', 'fastlane produce associate_cloud_container -a com.example.app iCloud.com.example.com')
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, options.__hash__)
require 'produce/cloud_container'
Produce::CloudContainer.new.associate(options, args)
end
end
command :merchant do |c|
c.syntax = 'fastlane produce merchant'
c.description = 'Ensure that a specific Merchant exists'
c.example('Create merchant', 'fastlane produce merchant -o merchant.com.example.production -r "Example Merchant Production"')
c.option('-r', '--merchant_name STRING', String, 'Name for the merchant that is created (PRODUCE_MERCHANT_NAME)')
c.option('-o', '--merchant_identifier STRING', String, 'Merchant identifier for the merchant (PRODUCE_MERCHANT_IDENTIFIER)')
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
extra_options = [FastlaneCore::ConfigItem.new(key: :merchant_name, optional: true), FastlaneCore::ConfigItem.new(key: :merchant_identifier)]
all_options = Produce::Options.available_options + extra_options
allowed_keys = all_options.collect(&:key)
Produce.config = FastlaneCore::Configuration.create(all_options, options.__hash__.select { |key, value| allowed_keys.include?(key) })
require 'produce/merchant'
Produce::Merchant.new.create(options, args)
end
end
command :associate_merchant do |c|
c.syntax = 'fastlane produce associate_merchant -a APP_IDENTIFIER MERCHANT_IDENTIFIER1, MERCHANT_IDENTIFIER2, ...'
c.description = 'Associate with a merchant for use with Apple Pay. Apple Pay will be enabled for this app.'
c.example('Associate with merchant', 'fastlane produce associate_merchant -a com.example.app merchant.com.example.production')
FastlaneCore::CommanderGenerator.new.generate(Produce::Options.available_options, command: c)
c.action do |args, options|
Produce.config = FastlaneCore::Configuration.create(Produce::Options.available_options, options.__hash__)
require 'produce/merchant'
Produce::Merchant.new.associate(options, args)
end
end
default_command(:create)
run!
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/itunes_connect.rb | produce/lib/produce/itunes_connect.rb | require 'spaceship'
require 'spaceship/tunes/tunes'
require 'fastlane_core/languages'
require_relative 'module'
module Produce
class ItunesConnect
def run
@full_bundle_identifier = app_identifier
@full_bundle_identifier.gsub!('*', Produce.config[:bundle_identifier_suffix].to_s) if wildcard_bundle?
# Team selection passed though FASTLANE_ITC_TEAM_ID and FASTLANE_ITC_TEAM_NAME environment variables
# Prompts select team if multiple teams and none specified
Spaceship::ConnectAPI.login(Produce.config[:username], nil, use_portal: false, use_tunes: true)
create_new_app
end
def create_new_app
application = fetch_application
if application
UI.success("App '#{Produce.config[:app_identifier]}' already exists (#{application.id}), nothing to do on App Store Connect")
# Nothing to do here
else
emails = Produce.config[:itc_users] || []
user_ids = []
unless emails.empty?
UI.message("Verifying users exist before creating app...")
user_ids = find_user_ids(emails: emails)
end
UI.success("Creating new app '#{Produce.config[:app_name]}' on App Store Connect")
platforms = Produce.config[:platforms] || [Produce.config[:platform]]
platforms = platforms.map do |platform|
Spaceship::ConnectAPI::Platform.map(platform)
end
# Produce.config[:itc_users]
application = Spaceship::ConnectAPI::App.create(
name: Produce.config[:app_name],
version_string: Produce.config[:app_version] || "1.0",
sku: Produce.config[:sku].to_s,
primary_locale: language,
bundle_id: app_identifier,
platforms: platforms,
company_name: Produce.config[:company_name]
)
application = fetch_application
counter = 0
while application.nil?
counter += 1
UI.crash!("Couldn't find newly created app on App Store Connect - please check the website for more information") if counter == 200
# Since 2016-08-10 App Store Connect takes some time to actually list the newly created application
# We have no choice but to poll to see if the newly created app is already available
UI.message("Waiting for the newly created application to be available on App Store Connect...")
sleep(15)
application = fetch_application
end
UI.crash!("Something went wrong when creating the new app - it's not listed in the App's list") unless application
UI.message("Ensuring version number")
platforms.each do |platform|
application.ensure_version!(Produce.config[:app_version], platform: platform) if Produce.config[:app_version]
end
# Add users to app
unless user_ids.empty?
application.add_users(user_ids: user_ids)
UI.message("Successfully added #{user_ids.size} #{user_ids.count == 1 ? 'user' : 'users'} to app")
end
UI.success("Successfully created new app '#{Produce.config[:app_name]}' on App Store Connect with ID #{application.id}")
end
return application.id
end
def find_user_ids(emails: nil)
emails ||= []
users = Spaceship::ConnectAPI::User.all.select do |user|
emails.include?(user.email)
end
diff_emails = emails - users.map(&:email)
unless diff_emails.empty?
raise "Could not find users with emails of: #{diff_emails.join(',')}"
end
return users.map(&:id)
end
private
def platform
(Produce.config[:platforms] || []).first || Produce.config[:platform]
end
def fetch_application
Spaceship::ConnectAPI::App.find(@full_bundle_identifier)
end
def wildcard_bundle?
return app_identifier.end_with?("*")
end
def app_identifier
Produce.config[:app_identifier].to_s
end
# Makes sure to get the value for the language
# Instead of using the user's value `UK English` spaceship should send `en-UK`
def language
@language = Produce.config[:language]
unless FastlaneCore::Languages::ALL_LANGUAGES.include?(@language)
mapped_language = Spaceship::Tunes::LanguageConverter.from_standard_to_itc_locale(@language)
if mapped_language.to_s.empty?
message = [
"Sending language name is deprecated. Could not map '#{@language}' to a locale.",
"Please enter one of available languages: #{FastlaneCore::Languages::ALL_LANGUAGES}"
].join("\n")
UI.user_error!(message)
end
UI.deprecated("Sending language name is deprecated. '#{@language}' has been mapped to '#{mapped_language}'.")
UI.deprecated("Please enter one of available languages: #{FastlaneCore::Languages::ALL_LANGUAGES}")
@language = mapped_language
end
return @language
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/service.rb | produce/lib/produce/service.rb | require 'spaceship'
require_relative 'module'
# rubocop:disable Metrics/ClassLength
module Produce
class Service
include Spaceship::ConnectAPI::BundleIdCapability::Type
include Spaceship::ConnectAPI::BundleIdCapability::Settings
include Spaceship::ConnectAPI::BundleIdCapability::Options
def self.enable(options, args)
self.new.enable(options, args)
end
def self.disable(options, args)
self.new.disable(options, args)
end
def self.available_services(options, args)
self.new.available_services(options, args)
end
def enable(options, _args)
unless bundle_id
UI.message("[DevCenter] App '#{Produce.config[:app_identifier]}' does not exist")
return
end
UI.success("[DevCenter] App found '#{bundle_id.name}'")
UI.message("Enabling services")
enabled = update(true, options)
UI.success("Done! Enabled #{enabled} services.")
end
def disable(options, _args)
unless bundle_id
UI.message("[DevCenter] App '#{Produce.config[:app_identifier]}' does not exist")
return
end
UI.success("[DevCenter] App found '#{bundle_id.name}'")
UI.message("Disabling services")
disabled = update(false, options)
UI.success("Done! Disabled #{disabled} services.")
end
def available_services(options, _args)
unless bundle_id
UI.message("[DevCenter] App '#{Produce.config[:app_identifier]}' does not exist")
return
end
UI.success("[DevCenter] App found '#{bundle_id.name}'")
UI.message("Fetching available services")
return Spaceship::ConnectAPI::Capabilities.all
end
def valid_services_for(options)
allowed_keys = [:access_wifi, :app_attest, :app_group, :apple_pay, :associated_domains, :auto_fill_credential, :car_play_audio_app, :car_play_messaging_app,
:car_play_navigation_app, :car_play_voip_calling_app, :class_kit, :declared_age_range, :icloud, :critical_alerts, :custom_network_protocol, :data_protection,
:extended_virtual_address_space, :file_provider_testing_mode, :family_controls, :fonts, :game_center, :health_kit, :hls_interstitial_preview, :home_kit, :hotspot,
:hotspot_helper, :in_app_purchase, :inter_app_audio, :low_latency_hls, :managed_associated_domains, :maps, :multipath, :network_extension,
:nfc_tag_reading, :passbook, :personal_vpn, :push_notification, :sign_in_with_apple, :siri_kit, :system_extension, :user_management, :vpn_configuration, :wallet,
:wireless_accessory, :driver_kit, :driver_kit_endpoint_security, :driver_kit_family_hid_device, :driver_kit_family_networking, :driver_kit_family_serial,
:driver_kit_hid_event_service, :driver_kit_transport_hid, :multitasking_camera_access, :sf_universal_link_api, :vp9_decoder, :music_kit, :shazam_kit,
:communication_notifications, :group_activities, :health_kit_estimate_recalibration, :time_sensitive_notifications]
options.__hash__.select { |key, value| allowed_keys.include?(key) }
end
# @return (Hash) Settings configuration for a key-settings combination
# @example
# [{
# key: "DATA_PROTECTION_PERMISSION_LEVEL",
# options:
# [
# {
# key: "COMPLETE_PROTECTION"
# }
# ]
# }]
def build_settings_for(settings_key:, options_key:)
return [{
key: settings_key,
options: [ {
key: options_key
} ]
}]
end
# rubocop:disable Metrics/PerceivedComplexity
# rubocop:disable Require/MissingRequireStatement
def update(on, options)
updated = valid_services_for(options).count
if options.access_wifi
UI.message("\tAccess WiFi")
bundle_id.update_capability(ACCESS_WIFI_INFORMATION, enabled: on)
end
if options.app_attest
UI.message("\tApp Attest")
bundle_id.update_capability(APP_ATTEST, enabled: on)
end
if options.app_group
UI.message("\tApp Groups")
bundle_id.update_capability(APP_GROUPS, enabled: on)
end
if options.apple_pay
UI.message("\tApple Pay")
bundle_id.update_capability(APPLE_PAY, enabled: on)
end
if options.associated_domains
UI.message("\tAssociated Domains")
bundle_id.update_capability(ASSOCIATED_DOMAINS, enabled: on)
end
if options.auto_fill_credential
UI.message("\tAutoFill Credential")
bundle_id.update_capability(AUTOFILL_CREDENTIAL_PROVIDER, enabled: on)
end
if options.car_play_audio_app
UI.message("\tCarPlay Audio App")
bundle_id.update_capability(CARPLAY_PLAYABLE_CONTENT, enabled: on)
end
if options.car_play_messaging_app
UI.message("\tCarPlay Messaging App")
bundle_id.update_capability(CARPLAY_MESSAGING, enabled: on)
end
if options.car_play_navigation_app
UI.message("\tCarPlay Navigation App")
bundle_id.update_capability(CARPLAY_NAVIGATION, enabled: on)
end
if options.car_play_voip_calling_app
UI.message("\tCarPlay Voip Calling App")
bundle_id.update_capability(CARPLAY_VOIP, enabled: on)
end
if options.class_kit
UI.message("\tClassKit")
bundle_id.update_capability(CLASSKIT, enabled: on)
end
if options.critical_alerts
UI.message("\tCritical Alerts")
bundle_id.update_capability(CRITICAL_ALERTS, enabled: on)
end
if options.custom_network_protocol
UI.message("\tCustom Network Protocol")
bundle_id.update_capability(NETWORK_CUSTOM_PROTOCOL, enabled: on)
end
if options.data_protection
UI.message("\tData Protection")
settings = []
case options.data_protection
when "complete"
settings = build_settings_for(settings_key: DATA_PROTECTION_PERMISSION_LEVEL, options_key: COMPLETE_PROTECTION)
when "unlessopen"
settings = build_settings_for(settings_key: DATA_PROTECTION_PERMISSION_LEVEL, options_key: PROTECTED_UNLESS_OPEN)
when "untilfirstauth"
settings = build_settings_for(settings_key: DATA_PROTECTION_PERMISSION_LEVEL, options_key: PROTECTED_UNTIL_FIRST_USER_AUTH)
else
UI.user_error!("Unknown service '#{options.data_protection}'. Valid values: 'complete', 'unlessopen', 'untilfirstauth'") unless options.data_protection == true || options.data_protection == false
end
bundle_id.update_capability(DATA_PROTECTION, enabled: on, settings: settings)
end
if options.declared_age_range
UI.message("\tDeclared Age Range")
bundle_id.update_capability(DECLARED_AGE_RANGE, enabled: on)
end
if options.extended_virtual_address_space
UI.message("\tExtended Virtual Address Space")
bundle_id.update_capability(EXTENDED_VIRTUAL_ADDRESSING, enabled: on)
end
if options.family_controls
UI.message("\tFamily Controls")
bundle_id.update_capability(FAMILY_CONTROLS, enabled: on)
end
if options.file_provider_testing_mode
UI.message("\tFile Provider Testing Mode")
bundle_id.update_capability(FILEPROVIDER_TESTINGMODE, enabled: on)
end
if options.fonts
UI.message("\tFonts")
bundle_id.update_capability(FONT_INSTALLATION, enabled: on)
end
if options.game_center
UI.message("\tGame Center")
settings = []
case options.game_center
when "mac"
settings = build_settings_for(settings_key: GAME_CENTER_SETTING, options_key: GAME_CENTER_MAC)
when "ios"
settings = build_settings_for(settings_key: GAME_CENTER_SETTING, options_key: GAME_CENTER_IOS)
else
UI.user_error!("Unknown service '#{options.game_center}'. Valid values: 'ios', 'mac'") unless options.game_center == true || options.game_center == false
end
bundle_id.update_capability(GAME_CENTER, enabled: on, settings: settings)
end
if options.health_kit
UI.message("\tHealthKit")
bundle_id.update_capability(HEALTHKIT, enabled: on)
end
if options.hls_interstitial_preview
UI.message("\tHLS Interstitial Preview")
bundle_id.update_capability(HLS_INTERSTITIAL_PREVIEW, enabled: on)
end
if options.home_kit
UI.message("\tHomeKit")
bundle_id.update_capability(HOMEKIT, enabled: on)
end
if options.hotspot
UI.message("\tHotspot")
bundle_id.update_capability(HOT_SPOT, enabled: on)
end
if options.hotspot_helper
UI.message("\tHotspot Helper")
bundle_id.update_capability(HOTSPOT_HELPER_MANAGED, enabled: on)
end
if options.icloud
UI.message("\tiCloud")
settings = []
case options.icloud
when "xcode6_compatible"
settings = build_settings_for(settings_key: ICLOUD_VERSION, options_key: XCODE_6)
when "xcode5_compatible"
settings = build_settings_for(settings_key: ICLOUD_VERSION, options_key: XCODE_5)
else
UI.user_error!("Unknown service '#{options.icloud}'. Valid values: 'xcode6_compatible', 'xcode5_compatible', 'off'") unless options.icloud == true || options.icloud == false
end
bundle_id.update_capability(ICLOUD, enabled: on, settings: settings)
end
if options.in_app_purchase
UI.message("\tIn-App Purchase")
bundle_id.update_capability(IN_APP_PURCHASE, enabled: on)
end
if options.inter_app_audio
UI.message("\tInter-App Audio")
bundle_id.update_capability(INTER_APP_AUDIO, enabled: on)
end
if options.low_latency_hls
UI.message("\tLow Latency HLS")
bundle_id.update_capability(COREMEDIA_HLS_LOW_LATENCY, enabled: on)
end
if options.managed_associated_domains
UI.message("\tManaged Associated Domains")
bundle_id.update_capability(MDM_MANAGED_ASSOCIATED_DOMAINS, enabled: on)
end
if options.maps
UI.message("\tMaps")
bundle_id.update_capability(MAPS, enabled: on)
end
if options.multipath
UI.message("\tMultipath")
bundle_id.update_capability(MULTIPATH, enabled: on)
end
if options.network_extension
UI.message("\tNetwork Extension")
bundle_id.update_capability(NETWORK_EXTENSIONS, enabled: on)
end
if options.nfc_tag_reading
UI.message("\tNFC Tag Reading")
bundle_id.update_capability(NFC_TAG_READING, enabled: on)
end
if options.personal_vpn
UI.message("\tPersonal VPN")
bundle_id.update_capability(PERSONAL_VPN, enabled: on)
end
if options.push_notification
UI.message("\tPush Notifications")
bundle_id.update_capability(PUSH_NOTIFICATIONS, enabled: on)
end
if options.sign_in_with_apple
UI.message("\tSign In With Apple")
settings = build_settings_for(settings_key: APPLE_ID_AUTH_APP_CONSENT, options_key: PRIMARY_APP_CONSENT)
bundle_id.update_capability(APPLE_ID_AUTH, enabled: on, settings: settings)
end
if options.siri_kit
UI.message("\tSiriKit")
bundle_id.update_capability(SIRIKIT, enabled: on)
end
if options.system_extension
UI.message("\tSystem Extension")
bundle_id.update_capability(SYSTEM_EXTENSION_INSTALL, enabled: on)
end
if options.user_management
UI.message("\tUser Management")
bundle_id.update_capability(USER_MANAGEMENT, enabled: on)
end
if options.wallet
UI.message("\tWallet")
bundle_id.update_capability(WALLET, enabled: on)
end
if options.wireless_accessory
UI.message("\tWireless Accessory Configuration")
bundle_id.update_capability(WIRELESS_ACCESSORY_CONFIGURATION, enabled: on)
end
if options.driver_kit
UI.message("\tDriverKit")
bundle_id.update_capability(DRIVERKIT, enabled: on)
end
if options.driver_kit_endpoint_security
UI.message("\tDriverKit Endpoint Security")
bundle_id.update_capability(DRIVERKIT_ENDPOINT_SECURITY, enabled: on)
end
if options.driver_kit_family_hid_device
UI.message("\tDriverKit Family HID Device")
bundle_id.update_capability(DRIVERKIT_HID_DEVICE, enabled: on)
end
if options.driver_kit_family_networking
UI.message("\tDriverKit Family Networking")
bundle_id.update_capability(DRIVERKIT_NETWORKING, enabled: on)
end
if options.driver_kit_family_serial
UI.message("\tDriverKit Family Serial")
bundle_id.update_capability(DRIVERKIT_SERIAL, enabled: on)
end
if options.driver_kit_hid_event_service
UI.message("\tDriverKit HID EventService")
bundle_id.update_capability(DRIVERKIT_HID_EVENT_SERVICE, enabled: on)
end
if options.driver_kit_transport_hid
UI.message("\tDriverKit Transport HID")
bundle_id.update_capability(DRIVERKIT_HID, enabled: on)
end
if options.multitasking_camera_access
UI.message("\tMultitasking Camera Access")
bundle_id.update_capability(IPAD_CAMERA_MULTITASKING, enabled: on)
end
if options.sf_universal_link_api
UI.message("\tSFUniversalLink API")
bundle_id.update_capability(SFUNIVERSALLINK_API, enabled: on)
end
if options.vp9_decoder
UI.message("\tVP9 Decoder")
bundle_id.update_capability(VP9_DECODER, enabled: on)
end
if options.music_kit
UI.message("\tMusicKit")
bundle_id.update_capability(MUSIC_KIT, enabled: on)
end
if options.shazam_kit
UI.message("\tShazamKit")
bundle_id.update_capability(SHAZAM_KIT, enabled: on)
end
if options.communication_notifications
UI.message("\tCommunication Notifications")
bundle_id.update_capability(USERNOTIFICATIONS_COMMUNICATION, enabled: on)
end
if options.group_activities
UI.message("\tGroup Activities")
bundle_id.update_capability(GROUP_ACTIVITIES, enabled: on)
end
if options.health_kit_estimate_recalibration
UI.message("\tHealthKit Estimate Recalibration")
bundle_id.update_capability(HEALTHKIT_RECALIBRATE_ESTIMATES, enabled: on)
end
if options.time_sensitive_notifications
UI.message("\tTime Sensitive Notifications")
bundle_id.update_capability(USERNOTIFICATIONS_TIMESENSITIVE, enabled: on)
end
updated
end
def bundle_id
return @bundle_id if @bundle_id
UI.message("Starting login with user '#{Produce.config[:username]}'")
Spaceship.login(Produce.config[:username], nil)
Spaceship.select_team
UI.message("Successfully logged in")
@bundle_id ||= Spaceship::ConnectAPI::BundleId.find(Produce.config[:app_identifier].to_s)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/manager.rb | produce/lib/produce/manager.rb | require 'fastlane_core/print_table'
require_relative 'developer_center'
require_relative 'itunes_connect'
module Produce
class Manager
# Produces app at DeveloperCenter and ItunesConnect
def self.start_producing
FastlaneCore::PrintTable.print_values(config: Produce.config, hide_keys: [], title: "Summary for produce #{Fastlane::VERSION}")
Produce::DeveloperCenter.new.run unless Produce.config[:skip_devcenter]
return Produce::ItunesConnect.new.run unless Produce.config[:skip_itc]
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/module.rb | produce/lib/produce/module.rb | require 'fastlane_core/helper'
module Produce
class << self
attr_accessor :config
end
Helper = FastlaneCore::Helper # you gotta love Ruby: Helper.* should use the Helper class contained in FastlaneCore
UI = FastlaneCore::UI
ROOT = Pathname.new(File.expand_path('../../..', __FILE__))
ENV['FASTLANE_TEAM_ID'] ||= ENV["PRODUCE_TEAM_ID"]
ENV['DELIVER_USER'] ||= ENV["PRODUCE_USERNAME"]
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/cloud_container.rb | produce/lib/produce/cloud_container.rb | require 'spaceship'
require_relative 'module'
module Produce
class CloudContainer
def create(options, _args)
login
container_identifier = options.container_identifier || UI.input("iCloud Container identifier: ")
if container_exists?(container_identifier)
UI.success("[DevCenter] iCloud Container '#{options.container_name} (#{options.container_identifier})' already exists, nothing to do on the Dev Center")
# Nothing to do here
else
container_name = options.container_name || container_identifier.gsub('.', ' ')
UI.success("Creating new iCloud Container '#{container_name}' with identifier '#{container_identifier}' on the Apple Dev Center")
container = Spaceship.cloud_container.create!(identifier: container_identifier, name: container_name)
if container.name != container_name
UI.important("Your container name includes non-ASCII characters, which are not supported by the Apple Developer Portal.")
UI.important("To fix this a unique (internal) name '#{container.name}' has been created for you.")
end
UI.message("Created iCloud Container #{container.cloud_container}")
UI.user_error!("Something went wrong when creating the new iCloud Container - it's not listed in the iCloud Container list") unless container_exists?(container_identifier)
UI.success("Finished creating new iCloud Container '#{container_name}' on the Dev Center")
end
return true
end
def associate(_options, args)
login
if !app_exists?
UI.message("[DevCenter] App '#{Produce.config[:app_identifier]}' does not exist, nothing to associate with the containers")
else
app = Spaceship.app.find(app_identifier)
UI.user_error!("Something went wrong when fetching the app - it's not listed in the apps list") if app.nil?
new_containers = []
UI.message("Validating containers before association")
args.each do |container_identifier|
if !container_exists?(container_identifier)
UI.message("[DevCenter] iCloud Container '#{container_identifier}' does not exist, please create it first, skipping for now")
else
new_containers.push(Spaceship.cloud_container.find(container_identifier))
end
end
UI.message("Finalising association with #{new_containers.count} containers")
app.associate_cloud_containers(new_containers)
UI.success("Done!")
end
return true
end
def login
UI.message("Starting login with user '#{Produce.config[:username]}'")
Spaceship.login(Produce.config[:username], nil)
Spaceship.select_team
UI.message("Successfully logged in")
end
def app_identifier
Produce.config[:app_identifier].to_s
end
def container_exists?(identifier)
Spaceship.cloud_container.find(identifier) != nil
end
def app_exists?
Spaceship.app.find(app_identifier) != nil
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/produce/lib/produce/available_default_languages.rb | produce/lib/produce/available_default_languages.rb | module Produce
class AvailableDefaultLanguages
# If you update this list, you probably also have to update these files:
# - fastlane_core/lib/fastlane_core/languages.rb
# - spaceship/lib/assets/languageMapping.json
# See this pull request for example: https://github.com/fastlane/fastlane/pull/14110
def self.all_languages
[
"Arabic",
"Catalan",
"Croatian",
"Czech",
"Brazilian Portuguese",
"Danish",
"Dutch",
"English",
"English_Australian",
"English_CA",
"English_UK",
"Finnish",
"French",
"French_CA",
"German",
"Greek",
"Hebrew",
"Hindi",
"Hungarian",
"Indonesian",
"Italian",
"Japanese",
"Korean",
"Malay",
"Norwegian",
"Polish",
"Portuguese",
"Romanian",
"Russian",
"Simplified Chinese",
"Slovak",
"Spanish",
"Spanish_MX",
"Swedish",
"Ukrainian",
"Thai",
"Traditional Chinese",
"Turkish",
"Vietnamese"
]
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pilot/spec/commands_generator_spec.rb | pilot/spec/commands_generator_spec.rb | require 'pilot/commands_generator'
describe Pilot::CommandsGenerator do
let(:available_options) { Pilot::Options.available_options }
def expect_build_manager_call_with(method_sym, expected_options)
fake_build_manager = "build_manager"
expect(Pilot::BuildManager).to receive(:new).and_return(fake_build_manager)
expect(fake_build_manager).to receive(method_sym) do |actual_options|
expect(actual_options._values).to eq(expected_options._values)
end
end
{
upload: :upload,
distribute: :distribute,
builds: :list
}.each do |command, build_manager_method|
describe ":#{command} option handling" do
it "can use the username short flag from tool options" do
stub_commander_runner_args([command.to_s, '-u', 'me@it.com'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect_build_manager_call_with(build_manager_method, expected_options)
Pilot::CommandsGenerator.start
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args([command.to_s, '--app_identifier', 'your.awesome.App'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect_build_manager_call_with(build_manager_method, expected_options)
Pilot::CommandsGenerator.start
end
end
end
def expect_tester_manager_call_with(method_sym, expected_options_sets)
expected_options_sets = [expected_options_sets] unless expected_options_sets.kind_of?(Array)
fake_tester_manager = "tester_manager"
expect(Pilot::TesterManager).to receive(:new).and_return(fake_tester_manager)
expected_options_sets.each do |expected_options|
expect(fake_tester_manager).to receive(method_sym) do |actual_options|
expect(actual_options._values).to eq(expected_options._values)
end
end
end
describe ":list option handling" do
it "can use the username short flag from tool options" do
stub_const('ENV', { 'PILOT_APP_IDENTIFIER' => 'your.awesome.App' })
stub_commander_runner_args(['list', '-u', 'me@it.com'])
expected_options = FastlaneCore::Configuration.create(available_options, { username: 'me@it.com' })
expect_tester_manager_call_with(:list_testers, expected_options)
Pilot::CommandsGenerator.start
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['list', '--app_identifier', 'your.awesome.App'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect_tester_manager_call_with(:list_testers, expected_options)
Pilot::CommandsGenerator.start
end
end
{
add: :add_tester,
remove: :remove_tester,
find: :find_tester
}.each do |command, tester_manager_method|
describe ":#{command} option handling" do
it "can use the email short flag from tool options" do
stub_commander_runner_args([command.to_s, '-e', 'you@that.com'])
expected_options = FastlaneCore::Configuration.create(available_options, { email: 'you@that.com' })
expect_tester_manager_call_with(tester_manager_method, expected_options)
Pilot::CommandsGenerator.start
end
it "can use the email flag from tool options" do
stub_commander_runner_args([command.to_s, '--email', 'you@that.com'])
expected_options = FastlaneCore::Configuration.create(available_options, { email: 'you@that.com' })
expect_tester_manager_call_with(tester_manager_method, expected_options)
Pilot::CommandsGenerator.start
end
it "can provide multiple emails as args" do
stub_commander_runner_args([command.to_s, 'you@that.com', 'another@that.com'])
expected_options1 = FastlaneCore::Configuration.create(available_options, { email: 'you@that.com' })
expected_options2 = FastlaneCore::Configuration.create(available_options, { email: 'another@that.com' })
expect_tester_manager_call_with(tester_manager_method, [expected_options1, expected_options2])
Pilot::CommandsGenerator.start
end
end
end
describe ":export option handling" do
def expect_tester_exporter_export_testers_with(expected_options)
fake_tester_exporter = "tester_exporter"
expect(Pilot::TesterExporter).to receive(:new).and_return(fake_tester_exporter)
expect(fake_tester_exporter).to receive(:export_testers) do |actual_options|
expect(actual_options._values).to eq(expected_options._values)
end
end
it "can use the testers_file_path short flag from tool options" do
stub_commander_runner_args(['export', '-c', 'file/path'])
expected_options = FastlaneCore::Configuration.create(available_options, { testers_file_path: 'file/path' })
expect_tester_exporter_export_testers_with(expected_options)
Pilot::CommandsGenerator.start
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['export', '--app_identifier', 'your.awesome.App'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect_tester_exporter_export_testers_with(expected_options)
Pilot::CommandsGenerator.start
end
end
describe ":import option handling" do
def expect_tester_importer_import_testers_with(expected_options)
fake_tester_importer = "tester_importer"
expect(Pilot::TesterImporter).to receive(:new).and_return(fake_tester_importer)
expect(fake_tester_importer).to receive(:import_testers) do |actual_options|
expect(actual_options._values).to eq(expected_options._values)
end
end
it "can use the testers_file_path short flag from tool options" do
stub_commander_runner_args(['import', '-c', 'file/path'])
expected_options = FastlaneCore::Configuration.create(available_options, { testers_file_path: 'file/path' })
expect_tester_importer_import_testers_with(expected_options)
Pilot::CommandsGenerator.start
end
it "can use the app_identifier flag from tool options" do
stub_commander_runner_args(['import', '--app_identifier', 'your.awesome.App'])
expected_options = FastlaneCore::Configuration.create(available_options, { app_identifier: 'your.awesome.App' })
expect_tester_importer_import_testers_with(expected_options)
Pilot::CommandsGenerator.start
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pilot/spec/build_manager_spec.rb | pilot/spec/build_manager_spec.rb | describe "Build Manager" do
describe ".truncate_changelog" do
it "Truncates Changelog if it exceeds character size" do
changelog = File.read("./pilot/spec/fixtures/build_manager/changelog_long")
changelog = Pilot::BuildManager.truncate_changelog(changelog)
expect(changelog).to eq(File.read("./pilot/spec/fixtures/build_manager/changelog_long_truncated"))
end
it "Truncates Changelog if it exceeds byte size" do
changelog = File.binread("./pilot/spec/fixtures/build_manager/changelog_bytes_long").force_encoding("UTF-8")
changelog = Pilot::BuildManager.truncate_changelog(changelog)
expect(changelog).to eq(File.binread("./pilot/spec/fixtures/build_manager/changelog_bytes_long_truncated").force_encoding("UTF-8"))
end
it "Keeps changelog if short enough" do
changelog = "1234"
changelog = Pilot::BuildManager.truncate_changelog(changelog)
expect(changelog).to eq("1234")
end
it "Truncates based on bytes not characters" do
changelog = "ü" * 4000
expect(changelog.unpack("C*").length).to eq(8000)
changelog = Pilot::BuildManager.truncate_changelog(changelog)
# Truncation appends "...", so the result is 1998 two-byte characters plus "..." for 3999 bytes.
expect(changelog.unpack("C*").length).to eq(3999)
end
end
describe ".sanitize_changelog" do
it "removes emoji" do
changelog = "I'm 🦇B🏧an🪴!"
changelog = Pilot::BuildManager.sanitize_changelog(changelog)
expect(changelog).to eq("I'm Ban!")
end
it "removes less than symbols" do
changelog = "I'm <script>man<<!"
changelog = Pilot::BuildManager.sanitize_changelog(changelog)
expect(changelog).to eq("I'm script>man!")
end
it "removes prohibited symbols before truncating" do
changelog = File.read("./pilot/spec/fixtures/build_manager/changelog_long")
changelog = "🎉<🎉<🎉#{changelog}🎉<🎉<🎉"
changelog = Pilot::BuildManager.sanitize_changelog(changelog)
expect(changelog).to eq(File.read("./pilot/spec/fixtures/build_manager/changelog_long_truncated"))
end
end
describe ".has_changelog_or_whats_new?" do
let(:fake_build_manager) { Pilot::BuildManager.new }
let(:no_options) { {} }
let(:changelog) { { changelog: "Sup" } }
let(:whats_new_symbol) { { localized_build_info: { 'en-us' => { whats_new: 'Sup' } } } }
let(:whats_new_string) { { localized_build_info: { 'en-us' => { 'whats_new' => 'Sup' } } } }
it "returns false for no changelog or whats_new" do
has = fake_build_manager.has_changelog_or_whats_new?(no_options)
expect(has).to eq(false)
end
it "returns true for changelog" do
has = fake_build_manager.has_changelog_or_whats_new?(changelog)
expect(has).to eq(true)
end
it "returns true for whats_new with symbol" do
has = fake_build_manager.has_changelog_or_whats_new?(whats_new_symbol)
expect(has).to eq(true)
end
it "returns true for whats_new with string" do
has = fake_build_manager.has_changelog_or_whats_new?(whats_new_string)
expect(has).to eq(true)
end
end
describe ".check_for_changelog_or_whats_new!" do
let(:fake_build_manager) { Pilot::BuildManager.new }
let(:fake_changelog) { "fake changelog" }
let(:input_options) { { distribute_external: true } }
describe "what happens when changelog is not given and distribute_external is true" do
before(:each) do
allow(fake_build_manager).to receive(:has_changelog_or_whats_new?).with(input_options).and_return(false)
end
context "when UI.interactive? is possible" do
before(:each) do
allow(UI).to receive(:interactive?).and_return(true)
end
it "asks the user to enter the changelog" do
expect(UI).to receive(:input).with("No changelog provided for new build. You can provide a changelog using the `changelog` option. For now, please provide a changelog here:")
fake_build_manager.check_for_changelog_or_whats_new!(input_options)
end
it "sets the user entered changelog into input_options" do
allow(UI).to receive(:input).and_return(fake_changelog)
fake_build_manager.check_for_changelog_or_whats_new!(input_options)
expect(input_options).to eq({ distribute_external: true, changelog: fake_changelog })
end
end
context "when UI.interactive? is not possible" do
before(:each) do
allow(UI).to receive(:interactive?).and_return(false)
end
it "raises an exception with message either disable `distribute_external` or provide a changelog using the `changelog` option" do
expect(UI).to receive(:user_error!).with("No changelog provided for new build. Please either disable `distribute_external` or provide a changelog using the `changelog` option")
fake_build_manager.check_for_changelog_or_whats_new!(input_options)
end
end
end
end
describe "distribute submits the build for review" do
let(:mock_base_client) { "fake api base client" }
let(:fake_build_manager) { Pilot::BuildManager.new }
let(:app) do
Spaceship::ConnectAPI::App.new("123-123-123-123", {
name: "Mock App"
})
end
let(:pre_release_version) do
Spaceship::ConnectAPI::PreReleaseVersion.new("123-123-123-123", {
version: "1.0"
})
end
let(:app_localizations) do
[
Spaceship::ConnectAPI::BetaAppLocalization.new("234", {
feedbackEmail: 'email@email.com',
marketingUrl: 'https://url.com',
privacyPolicyUrl: 'https://url.com',
description: 'desc desc desc',
locale: 'en-us'
}),
Spaceship::ConnectAPI::BetaAppLocalization.new("432", {
feedbackEmail: 'email@email.com',
marketingUrl: 'https://url.com',
privacyPolicyUrl: 'https://url.com',
description: 'desc desc desc',
locale: 'en-gb'
})
]
end
let(:build_localizations) do
[
Spaceship::ConnectAPI::BetaBuildLocalization.new("234", {
whatsNew: 'some more words',
locale: 'en-us'
}),
Spaceship::ConnectAPI::BetaBuildLocalization.new("432", {
whatsNew: 'some words',
locale: 'en-gb'
})
]
end
let(:build_beta_detail_still_processing) do
Spaceship::ConnectAPI::BuildBetaDetail.new("321", {
internal_build_state: Spaceship::ConnectAPI::BuildBetaDetail::InternalState::PROCESSING,
external_build_state: Spaceship::ConnectAPI::BuildBetaDetail::ExternalState::PROCESSING
})
end
let(:build_beta_detail_missing_export_compliance) do
Spaceship::ConnectAPI::BuildBetaDetail.new("321", {
internal_build_state: Spaceship::ConnectAPI::BuildBetaDetail::InternalState::MISSING_EXPORT_COMPLIANCE,
external_build_state: Spaceship::ConnectAPI::BuildBetaDetail::ExternalState::MISSING_EXPORT_COMPLIANCE
})
end
let(:build_beta_detail) do
Spaceship::ConnectAPI::BuildBetaDetail.new("321", {
internal_build_state: Spaceship::ConnectAPI::BuildBetaDetail::InternalState::READY_FOR_BETA_TESTING,
external_build_state: Spaceship::ConnectAPI::BuildBetaDetail::ExternalState::READY_FOR_BETA_SUBMISSION
})
end
let(:beta_groups) do
[
Spaceship::ConnectAPI::BetaGroup.new("987", {
name: "Blue Man Group"
}),
Spaceship::ConnectAPI::BetaGroup.new("654", {
name: "Green Eggs and Ham"
})
]
end
let(:ready_to_submit_mock_build) do
Spaceship::ConnectAPI::Build.new("123", {
version: '',
uploadedDate: '',
processingState: Spaceship::ConnectAPI::Build::ProcessingState::VALID,
usesNonExemptEncryption: nil
})
end
let(:distribute_options) do
{
apple_id: 'mock_apple_id',
app_identifier: 'mock_app_id',
distribute_external: true,
groups: ["Blue Man Group"],
skip_submission: false
}
end
let(:mock_api_client_beta_app_localizations) do
[
{ "id" => "234", "attributes" => { "locale" => "en-us" } },
{ "id" => "432", "attributes" => { "locale" => "en-gb" } }
]
end
let(:mock_api_client_beta_build_localizations) do
[
{ "id" => "234", "attributes" => { "locale" => "en-us" } },
{ "id" => "432", "attributes" => { "locale" => "en-gb" } }
]
end
let(:mock_api_client_beta_groups) do
[
{ "id" => "987", "attributes" => { "name" => "Blue Man Group" } },
{ "id" => "654", "attributes" => { "name" => "Green Eggs and Ham" } }
]
end
describe "distribute success" do
let(:distribute_options_skip_waiting_non_localized_changelog) do
{
apple_id: 'mock_apple_id',
app_identifier: 'mock_app_id',
distribute_external: false,
skip_submission: false,
skip_waiting_for_build_processing: true,
notify_external_testers: true,
uses_non_exempt_encryption: false,
changelog: "log of changing"
}
end
let(:distribute_options_non_localized) do
{
apple_id: 'mock_apple_id',
app_identifier: 'mock_app_id',
distribute_external: true,
groups: ["Blue Man Group"],
skip_submission: false,
demo_account_required: true,
notify_external_testers: true,
beta_app_feedback_email: "josh+oldfeedback@rokkincat.com",
beta_app_description: "old description for all the things",
uses_non_exempt_encryption: false,
submit_beta_review: true,
changelog: "log of changing"
}
end
before(:each) do
allow(fake_build_manager).to receive(:login)
allow(mock_base_client).to receive(:team_id).and_return('')
allow(Spaceship::ConnectAPI).to receive(:post_beta_app_review_submissions) # pretend it worked.
allow(Spaceship::ConnectAPI::TestFlight).to receive(:instance).and_return(mock_base_client)
# Allow build to return app, build_beta_detail, and pre_release_version
# These are models that are expected to usually be included in the build passed into distribute
allow(ready_to_submit_mock_build).to receive(:app).and_return(app)
allow(ready_to_submit_mock_build).to receive(:pre_release_version).and_return(pre_release_version)
end
it "updates non-localized changelog and doesn't distribute" do
expect(ready_to_submit_mock_build).to receive(:build_beta_detail).and_return(build_beta_detail_still_processing).exactly(4).times
options = distribute_options_skip_waiting_non_localized_changelog
# Expect beta build localizations to be fetched
expect(Spaceship::ConnectAPI).to receive(:get_beta_build_localizations).with({
filter: { build: ready_to_submit_mock_build.id },
includes: nil,
limit: nil,
sort: nil
}).and_return(Spaceship::ConnectAPI::Response.new)
expect(ready_to_submit_mock_build).to receive(:get_beta_build_localizations).and_wrap_original do |m, *args|
m.call(*args)
build_localizations
end
# Expect beta build localizations to be patched with a UI.success after
mock_api_client_beta_build_localizations.each do |localization|
expect(Spaceship::ConnectAPI).to receive(:patch_beta_build_localizations).with({
localization_id: localization['id'],
attributes: {
whatsNew: options[:changelog]
}
})
end
expect(FastlaneCore::UI).to receive(:success).with("Successfully set the changelog for build")
# Expect build beta details to be patched
expect(Spaceship::ConnectAPI).to receive(:patch_build_beta_details).with({
build_beta_details_id: build_beta_detail.id,
attributes: { autoNotifyEnabled: options[:notify_external_testers] }
})
# Don't expect success messages
expect(FastlaneCore::UI).to_not(receive(:message).with(/Distributing new build to testers/))
expect(FastlaneCore::UI).to_not(receive(:success).with(/Successfully distributed build to/))
fake_build_manager.distribute(options, build: ready_to_submit_mock_build)
end
it "updates non-localized demo_account_required, notify_external_testers, beta_app_feedback_email, and beta_app_description and distributes" do
expect(ready_to_submit_mock_build).to receive(:build_beta_detail).and_return(build_beta_detail_missing_export_compliance).exactly(7).times
options = distribute_options_non_localized
# Expect App.find to be called from within Pilot::Manager
expect(Spaceship::ConnectAPI::App).to receive(:get).and_return(app)
# Expect a beta app review detail to be patched
expect(Spaceship::ConnectAPI).to receive(:patch_beta_app_review_detail).with({
app_id: ready_to_submit_mock_build.app_id,
attributes: { demoAccountRequired: options[:demo_account_required] }
})
# Expect beta app localizations to be fetched
expect(Spaceship::ConnectAPI).to receive(:get_beta_app_localizations).with({
filter: { app: ready_to_submit_mock_build.app.id },
includes: nil,
limit: nil,
sort: nil
}).and_return(Spaceship::ConnectAPI::Response.new)
expect(app).to receive(:get_beta_app_localizations).and_wrap_original do |m, *args|
m.call(*args)
app_localizations
end
# Expect beta app localizations to be patched with a UI.success after
mock_api_client_beta_app_localizations.each do |localization|
expect(Spaceship::ConnectAPI).to receive(:patch_beta_app_localizations).with({
localization_id: localization['id'],
attributes: {
feedbackEmail: options[:beta_app_feedback_email],
description: options[:beta_app_description]
}
})
end
expect(FastlaneCore::UI).to receive(:success).with("Successfully set the beta_app_feedback_email and/or beta_app_description")
# Expect beta build localizations to be fetched
expect(Spaceship::ConnectAPI).to receive(:get_beta_build_localizations).with({
filter: { build: ready_to_submit_mock_build.id },
includes: nil,
limit: nil,
sort: nil
}).and_return(Spaceship::ConnectAPI::Response.new)
expect(ready_to_submit_mock_build).to receive(:get_beta_build_localizations).and_wrap_original do |m, *args|
m.call(*args)
build_localizations
end
# Expect beta build localizations to be patched with a UI.success after
mock_api_client_beta_build_localizations.each do |localization|
expect(Spaceship::ConnectAPI).to receive(:patch_beta_build_localizations).with({
localization_id: localization['id'],
attributes: {
whatsNew: options[:changelog]
}
})
end
expect(FastlaneCore::UI).to receive(:success).with("Successfully set the changelog for build")
# Expect build beta details to be patched
expect(Spaceship::ConnectAPI).to receive(:patch_build_beta_details).with({
build_beta_details_id: build_beta_detail.id,
attributes: { autoNotifyEnabled: options[:notify_external_testers] }
})
# A build will go back into a processing state after a patch
# Expect wait_for_export compliance processing_to_be_complete to be called after patching
expect(Spaceship::ConnectAPI).to receive(:patch_builds).with({
build_id: ready_to_submit_mock_build.id, attributes: { usesNonExemptEncryption: false }
})
expect(Spaceship::ConnectAPI::Build).to receive(:get).and_return(ready_to_submit_mock_build).exactly(2).times
expect(FastlaneCore::UI).to receive(:message).with("Waiting for build 123 to process export compliance")
expect(ready_to_submit_mock_build).to receive(:build_beta_detail).and_return(build_beta_detail).exactly(3).times
# Expect beta groups fetched from app. This tests:
# 1. app.get_beta_groups is called
# 2. client.get_beta_groups is called inside of app.beta_groups
expect(Spaceship::ConnectAPI).to receive(:get_beta_groups).with({
filter: { app: ready_to_submit_mock_build.app.id },
includes: nil,
limit: nil,
sort: nil
}).and_return(Spaceship::ConnectAPI::Response.new)
expect(app).to receive(:get_beta_groups).and_wrap_original do |m, *args|
m.call(*args)
beta_groups
end
# Expect beta groups to be added to a builds. This tests:
# 1. build.add_beta_groups is called
# 2. client.add_beta_groups_to_build is called inside of build.add_beta_groups
expect(Spaceship::ConnectAPI).to receive(:add_beta_groups_to_build).with({
build_id: ready_to_submit_mock_build.id,
beta_group_ids: [beta_groups[0].id]
}).and_return(Spaceship::ConnectAPI::Response.new)
expect(ready_to_submit_mock_build).to receive(:add_beta_groups).with(beta_groups: [beta_groups[0]]).and_wrap_original do |m, *args|
options = args.first
m.call(**options)
end
# Expect success messages
expect(FastlaneCore::UI).to receive(:message).with(/Distributing new build to testers/)
expect(FastlaneCore::UI).to receive(:success).with(/Successfully distributed build to/)
fake_build_manager.distribute(options, build: ready_to_submit_mock_build)
end
end
end
describe "#wait_for_build_processing_to_be_complete" do
let(:fake_build_manager) { Pilot::BuildManager.new }
let(:app) do
Spaceship::ConnectAPI::App.new("123-123-123-123", {
name: "Mock App"
})
end
before(:each) do
allow(fake_build_manager).to receive(:login)
allow(fake_build_manager).to receive(:app).and_return(app)
end
it "wait given :ipa" do
options = { ipa: "some_path.ipa" }
fake_build_manager.instance_variable_set(:@config, options)
expect(fake_build_manager).to receive(:fetch_app_platform)
expect(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_version).and_return("1.2.3")
expect(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_build).and_return("123")
expect(FastlaneCore::PkgFileAnalyser).to_not(receive(:fetch_app_version))
expect(FastlaneCore::PkgFileAnalyser).to_not(receive(:fetch_app_build))
fake_build = double
expect(fake_build).to receive(:app_version).and_return("1.2.3")
expect(fake_build).to receive(:version).and_return("123")
expect(FastlaneCore::BuildWatcher).to receive(:wait_for_build_processing_to_be_complete).and_return(fake_build)
fake_build_manager.wait_for_build_processing_to_be_complete
end
it "wait given :pkg" do
options = { pkg: "some_path.pkg" }
fake_build_manager.instance_variable_set(:@config, options)
expect(fake_build_manager).to receive(:fetch_app_platform)
expect(FastlaneCore::IpaFileAnalyser).to_not(receive(:fetch_app_version))
expect(FastlaneCore::IpaFileAnalyser).to_not(receive(:fetch_app_build))
expect(FastlaneCore::PkgFileAnalyser).to receive(:fetch_app_version).and_return("1.2.3")
expect(FastlaneCore::PkgFileAnalyser).to receive(:fetch_app_build).and_return("123")
fake_build = double
expect(fake_build).to receive(:app_version).and_return("1.2.3")
expect(fake_build).to receive(:version).and_return("123")
expect(FastlaneCore::BuildWatcher).to receive(:wait_for_build_processing_to_be_complete).and_return(fake_build)
fake_build_manager.wait_for_build_processing_to_be_complete
end
it "wait given :distribute_only" do
options = { pkg: "some_path.pkg", build_number: "234", app_version: "2.3.4", distribute_only: true }
fake_build_manager.instance_variable_set(:@config, options)
expect(fake_build_manager).to receive(:fetch_app_platform)
expect(FastlaneCore::IpaFileAnalyser).to_not(receive(:fetch_app_version))
expect(FastlaneCore::IpaFileAnalyser).to_not(receive(:fetch_app_build))
expect(FastlaneCore::PkgFileAnalyser).to_not(receive(:fetch_app_version))
expect(FastlaneCore::PkgFileAnalyser).to_not(receive(:fetch_app_build))
fake_build = double
expect(fake_build).to receive(:app_version).and_return("2.3.4")
expect(fake_build).to receive(:version).and_return("234")
expect(FastlaneCore::BuildWatcher).to receive(:wait_for_build_processing_to_be_complete).and_return(fake_build)
fake_build_manager.wait_for_build_processing_to_be_complete
end
it "wait given :ipa and :pkg and platform ios" do
options = { ipa: "some_path.ipa", pkg: "some_path.pkg" }
fake_build_manager.instance_variable_set(:@config, options)
expect(fake_build_manager).to receive(:fetch_app_platform).and_return("ios")
expect(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_version).and_return("1.2.3")
expect(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_build).and_return("123")
expect(FastlaneCore::PkgFileAnalyser).to_not(receive(:fetch_app_version))
expect(FastlaneCore::PkgFileAnalyser).to_not(receive(:fetch_app_build))
fake_build = double
expect(fake_build).to receive(:app_version).and_return("1.2.3")
expect(fake_build).to receive(:version).and_return("123")
expect(FastlaneCore::BuildWatcher).to receive(:wait_for_build_processing_to_be_complete).and_return(fake_build)
fake_build_manager.wait_for_build_processing_to_be_complete
end
it "wait given :ipa and :pkg and osx platform" do
options = { ipa: "some_path.ipa", pkg: "some_path.pkg", app_platform: "osx" }
fake_build_manager.instance_variable_set(:@config, options)
expect(fake_build_manager.config[:app_platform]).to be == "osx"
expect(fake_build_manager).to receive(:fetch_app_platform).and_return("osx")
expect(FastlaneCore::IpaFileAnalyser).to_not(receive(:fetch_app_version))
expect(FastlaneCore::IpaFileAnalyser).to_not(receive(:fetch_app_build))
expect(FastlaneCore::PkgFileAnalyser).to receive(:fetch_app_version).and_return("1.2.3")
expect(FastlaneCore::PkgFileAnalyser).to receive(:fetch_app_build).and_return("123")
fake_build = double
expect(fake_build).to receive(:app_version).and_return("1.2.3")
expect(fake_build).to receive(:version).and_return("123")
expect(FastlaneCore::BuildWatcher).to receive(:wait_for_build_processing_to_be_complete).and_return(fake_build)
fake_build_manager.wait_for_build_processing_to_be_complete
end
it "wait given :app_version and :build_number" do
options = { app_version: "1.2.3", build_number: "123" }
fake_build_manager.instance_variable_set(:@config, options)
expect(fake_build_manager).to receive(:fetch_app_platform)
fake_build = double
expect(fake_build).to receive(:app_version).and_return("1.2.3")
expect(fake_build).to receive(:version).and_return("123")
expect(FastlaneCore::BuildWatcher).to receive(:wait_for_build_processing_to_be_complete).and_return(fake_build)
fake_build_manager.wait_for_build_processing_to_be_complete
end
it "wait given :ipa, :app_version and :build_number" do
options = { app_version: "4.5.6", build_number: "456", ipa: "some_path.ipa" }
fake_build_manager.instance_variable_set(:@config, options)
expect(fake_build_manager).to receive(:fetch_app_platform)
expect(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_version).and_return("1.2.3")
expect(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_build).and_return("123")
fake_build = double
expect(fake_build).to receive(:app_version).and_return("1.2.3")
expect(fake_build).to receive(:version).and_return("123")
expect(FastlaneCore::BuildWatcher).to receive(:wait_for_build_processing_to_be_complete).and_return(fake_build)
fake_build_manager.wait_for_build_processing_to_be_complete
end
end
describe "#update_beta_app_meta" do
let(:fake_build_manager) { Pilot::BuildManager.new }
let(:fake_build) { double("fake build") }
it "does not attempt to set demo account required" do
options = {}
expect(fake_build_manager).not_to receive(:update_review_detail)
expect(fake_build_manager).not_to receive(:update_build_beta_details)
fake_build_manager.update_beta_app_meta(options, fake_build)
end
it "does not attempt to set demo account required" do
options = { notify_external_testers: true }
expect(fake_build_manager).not_to receive(:update_review_detail)
expect(fake_build_manager).to receive(:update_build_beta_details)
fake_build_manager.update_beta_app_meta(options, fake_build)
end
it "sets demo account required to false" do
options = { demo_account_required: false }
expect(fake_build_manager).to receive(:update_review_detail)
expect(fake_build_manager).not_to receive(:update_build_beta_details)
fake_build_manager.update_beta_app_meta(options, fake_build)
expect(options[:beta_app_review_info][:demo_account_required]).to be(false)
end
it "sets demo account required to true" do
options = { demo_account_required: true }
expect(fake_build_manager).to receive(:update_review_detail)
expect(fake_build_manager).not_to receive(:update_build_beta_details)
fake_build_manager.update_beta_app_meta(options, fake_build)
expect(options[:beta_app_review_info][:demo_account_required]).to be(true)
end
end
describe "#upload" do
describe "shows the correct notices" do
let(:fake_build_manager) { Pilot::BuildManager.new }
let(:fake_app_id) { 123 }
let(:fake_dir) { "fake dir" }
let(:fake_app_platform) { "ios" }
let(:fake_app_identifier) { "org.fastlane.very-capable-app" }
let(:fake_short_version) { "1.0" }
let(:fake_bundle_version) { "1" }
let(:upload_options) do
{
apple_id: fake_app_id,
skip_waiting_for_build_processing: true,
changelog: "changelog contents",
ipa: File.expand_path("./fastlane_core/spec/fixtures/ipas/very-capable-app.ipa")
}
end
before(:each) do
allow(fake_build_manager).to receive(:login)
allow(fake_build_manager).to receive(:fetch_app_platform).and_return(fake_app_platform)
allow(Dir).to receive(:mktmpdir).and_return(fake_dir)
fake_ipauploadpackagebuilder = double
allow(fake_ipauploadpackagebuilder).to receive(:generate).with(app_id: fake_app_id, ipa_path: upload_options[:ipa], package_path: fake_dir, platform: fake_app_platform, app_identifier: fake_app_identifier, short_version: fake_short_version, bundle_version: fake_bundle_version).and_return(true)
allow(FastlaneCore::IpaUploadPackageBuilder).to receive(:new).and_return(fake_ipauploadpackagebuilder)
fake_itunestransporter = double
allow(fake_itunestransporter).to receive(:upload).and_return(true)
allow(FastlaneCore::ItunesTransporter).to receive(:new).and_return(fake_itunestransporter)
fake_build = double
expect(fake_build_manager).to receive(:wait_for_build_processing_to_be_complete).and_return(fake_build)
expect(fake_build_manager).to receive(:distribute).with(upload_options, build: fake_build)
end
it "does not advertise `skip_waiting_for_build_processing` if the option is set" do
expect(FastlaneCore::UI).to_not(receive(:message).with("If you want to skip waiting for the processing to be finished, use the `skip_waiting_for_build_processing` option"))
expect(FastlaneCore::UI).to_not(receive(:message).with("Note that if `skip_waiting_for_build_processing` is used but a `changelog` is supplied, this process will wait for the build to appear on App Store Connect, update the changelog and then skip the remaining of the processing steps."))
fake_build_manager.upload(upload_options)
end
it "shows notice when using `skip_waiting_for_build_processing` and changelog together" do
expect(FastlaneCore::UI).to(receive(:important).with("`skip_waiting_for_build_processing` used and `changelog` supplied - will wait until build appears on App Store Connect, update the changelog and then skip the rest of the remaining of the processing steps."))
fake_build_manager.upload(upload_options)
end
end
describe "uses Manager.login (which does spaceship login) for ipa" do
let(:fake_build_manager) { Pilot::BuildManager.new }
let(:fake_app_id) { 123 }
let(:fake_dir) { "fake dir" }
let(:fake_app_platform) { "ios" }
let(:fake_app_identifier) { "org.fastlane.very-capable-app" }
let(:fake_short_version) { "1.0" }
let(:fake_bundle_version) { "1" }
let(:upload_options) do
{
apple_id: fake_app_id,
skip_waiting_for_build_processing: true,
ipa: File.expand_path("./fastlane_core/spec/fixtures/ipas/very-capable-app.ipa")
}
end
before(:each) do
allow(fake_build_manager).to receive(:fetch_app_platform).and_return(fake_app_platform)
allow(Dir).to receive(:mktmpdir).and_return(fake_dir)
fake_ipauploadpackagebuilder = double
allow(fake_ipauploadpackagebuilder).to receive(:generate).with(app_id: fake_app_id, ipa_path: upload_options[:ipa], package_path: fake_dir, platform: fake_app_platform, app_identifier: fake_app_identifier, short_version: fake_short_version, bundle_version: fake_bundle_version).and_return(true)
allow(FastlaneCore::IpaUploadPackageBuilder).to receive(:new).and_return(fake_ipauploadpackagebuilder)
fake_itunestransporter = double
allow(fake_itunestransporter).to receive(:upload).and_return(true)
allow(FastlaneCore::ItunesTransporter).to receive(:new).and_return(fake_itunestransporter)
expect(UI).to receive(:success).with("Ready to upload new build to TestFlight (App: #{fake_app_id})...")
expect(UI).to receive(:success).with("Successfully uploaded the new binary to App Store Connect")
end
it "NOT when skip_waiting_for_build_processing and apple_id are set" do
# should not execute Manager.login (which does spaceship login)
expect(fake_build_manager).not_to(receive(:login))
fake_build_manager.upload(upload_options)
end
it "when skip_waiting_for_build_processing and apple_id are not set" do
# remove options that make login unnecessary
upload_options.delete(:apple_id)
upload_options.delete(:skip_waiting_for_build_processing)
# allow Manager.login method this time
expect(fake_build_manager).to receive(:login).at_least(:once)
# check for changelog or whats new!
expect(fake_build_manager).to receive(:check_for_changelog_or_whats_new!).with(upload_options)
# other stuff required to let `upload` work:
expect(fake_build_manager).to receive(:fetch_app_id).and_return(fake_app_id).exactly(2).times
expect(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_version).and_return(fake_short_version).exactly(2).times
expect(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_build).and_return(fake_bundle_version).exactly(2).times
fake_app = double
expect(fake_app).to receive(:id).and_return(fake_app_id)
expect(fake_build_manager).to receive(:app).and_return(fake_app)
fake_build = double
expect(fake_build).to receive(:app_version).and_return(fake_short_version)
expect(fake_build).to receive(:version).and_return(fake_bundle_version)
expect(UI).to receive(:message).with("If you want to skip waiting for the processing to be finished, use the `skip_waiting_for_build_processing` option")
expect(UI).to receive(:message).with("Note that if `skip_waiting_for_build_processing` is used but a `changelog` is supplied, this process will wait for the build to appear on App Store Connect, update the changelog and then skip the remaining of the processing steps.")
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | true |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pilot/spec/tester_manager_spec.rb | pilot/spec/tester_manager_spec.rb | require 'colored'
describe Pilot::TesterManager do
describe "Manages adding/removing/displaying testers" do
let(:tester_manager) { Pilot::TesterManager.new }
let(:custom_tester_group) do
Spaceship::ConnectAPI::BetaGroup.new("1", {
name: "Test Group"
})
end
let(:app_context_testers) do
[
Spaceship::ConnectAPI::BetaTester.new("1", {
firstName: 'First',
lastName: 'Last',
email: 'my@email.addr',
betaGroups: [custom_tester_group]
}),
Spaceship::ConnectAPI::BetaTester.new("2", {
firstName: 'Fabricio',
lastName: 'Devtoolio',
email: 'fabric-devtools@gmail.com',
betaGroups: [custom_tester_group]
})
]
end
let(:current_user) do
Spaceship::Tunes::Member.new({ "firstname" => "Josh",
"lastname" => "Liebowitz",
"email_address" => "taquitos+nospam@gmail.com" })
end
let(:fake_tester) do
Spaceship::ConnectAPI::BetaTester.new("1", {
firstName: 'fake',
lastName: 'tester',
email: 'fabric-devtools@gmail.com+fake@gmail.com'
})
end
let(:default_add_tester_options) do
FastlaneCore::Configuration.create(Pilot::Options.available_options, {
apple_id: '123456789',
email: fake_tester.email,
first_name: fake_tester.first_name,
last_name: fake_tester.last_name
})
end
let(:remove_tester_options) do
FastlaneCore::Configuration.create(Pilot::Options.available_options, {
apple_id: '123456789',
email: fake_tester.email,
first_name: fake_tester.first_name,
last_name: fake_tester.last_name
})
end
let(:default_add_tester_options_with_group) do
FastlaneCore::Configuration.create(Pilot::Options.available_options, {
apple_id: '123456789',
email: fake_tester.email,
first_name: fake_tester.first_name,
last_name: fake_tester.last_name,
groups: ["Test Group"]
})
end
let(:fake_app) { "fake_app_object" }
let(:fake_app_name) { "My Fake App" }
let(:fake_client) { "fake client" }
before(:each) do
allow(fake_app).to receive(:apple_id).and_return("123456789")
allow(fake_app).to receive(:name).and_return(fake_app_name)
allow(Spaceship::ConnectAPI::App).to receive(:get).and_return(fake_app)
allow(Spaceship::ConnectAPI::App).to receive(:find).and_return(fake_app)
allow(Spaceship::Tunes).to receive(:client).and_return(fake_client)
allow(tester_manager).to receive(:login) # prevent attempting to log in with iTC
allow(fake_client).to receive(:user).and_return(current_user)
allow(fake_client).to receive(:user_email).and_return("taquitos@fastlane.tools")
allow(fake_client).to receive(:team_id).and_return("1234")
end
describe "when invoked from the context of an app" do
it "prints a table without columns showing device and version info" do
allow(fake_app).to receive(:get_beta_testers).and_return(app_context_testers)
headings = ["First", "Last", "Email", "Groups"]
rows = app_context_testers.map do |tester|
[tester.first_name, tester.last_name, tester.email, tester.beta_groups.map(&:name).join(";")]
end
expect(Terminal::Table).to receive(:new).with(title: "All Testers (2)".green,
headings: headings,
rows: rows)
tester_manager.list_testers(app_identifier: 'com.whatever')
end
end
describe "when asked to invite a new tester to a specific existing custom group" do
it "creates a new tester and adds it to the default group" do
allow(tester_manager).to receive(:find_app_tester).and_return(fake_tester)
allow(fake_app).to receive(:get_beta_groups).and_return([custom_tester_group])
expect(custom_tester_group).to receive(:post_bulk_beta_tester_assignments)
groups = [custom_tester_group]
group_names = groups.map(&:name).join(';')
expect(FastlaneCore::UI).to receive(:success).with("Successfully added tester #{fake_tester.email} to app #{fake_app_name} in group(s) #{group_names}")
tester_manager.add_tester(default_add_tester_options_with_group)
end
end
describe "when external tester is removed" do
it "removes the tester without error" do
allow(tester_manager).to receive(:find_app_tester).and_return(fake_tester)
allow(fake_app).to receive(:get_beta_groups).and_return([custom_tester_group])
expect(fake_tester).to receive(:delete_from_apps)
expect(FastlaneCore::UI).to receive(:success).with("Successfully removed tester fabric-devtools@gmail.com+fake@gmail.com from app: #{fake_app_name}")
tester_manager.remove_tester(remove_tester_options)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pilot/spec/manager_spec.rb | pilot/spec/manager_spec.rb | describe Pilot do
describe Pilot::Manager do
let(:fake_manager) { Pilot::Manager.new }
let(:fake_api_key_json_path) do
"./spaceship/spec/connect_api/fixtures/asc_key.json"
end
let(:fake_api_key) do
JSON.parse(File.read(fake_api_key_json_path), { symbolize_names: true })
end
let(:fake_app_id) { "fake app_id" }
let(:fake_app) { "fake app" }
let(:fake_app_identifier) { "fake app_identifier" }
let(:fake_ipa) { "fake ipa" }
let(:fake_pkg) { "fake pkg" }
describe "what happens on 'start'" do
context "when 'config' variable is already set" do
before(:each) do
fake_manager.instance_variable_set(:@config, { api_key: fake_api_key })
end
it "doesn't override the 'config' variable value" do
options = {}
fake_manager.start(options)
expected_options = { api_key: fake_api_key }
expect(fake_manager.instance_variable_get(:@config)).to eq(expected_options)
end
it "doesn't call login" do
expect(fake_manager).not_to receive(:login)
options = {}
fake_manager.start(options)
end
end
context "when using the default 'should_login' value" do
before(:each) do
expect(fake_manager).to receive(:login)
end
it "sets the 'config' variable value and calls login" do
options = {}
fake_manager.start(options)
expect(fake_manager.instance_variable_get(:@config)).to eq(options)
end
end
context "when passing 'should_login' value as TRUE" do
before(:each) do
expect(fake_manager).to receive(:login)
end
it "sets the 'config' variable value and calls login" do
options = {}
fake_manager.start(options, should_login: true)
expect(fake_manager.instance_variable_get(:@config)).to eq(options)
end
end
context "when passing 'should_login' value as FALSE" do
context "when input options has no 'api_key' or 'api_key_path' param" do
before(:each) do
expect(fake_manager).not_to receive(:login)
end
it "sets the 'config' variable value and doesn't call login" do
options = {}
fake_manager.start(options, should_login: false)
expect(fake_manager.instance_variable_get(:@config)).to eq(options)
end
end
context "when input options has 'api_key' param" do
before(:each) do
expect(fake_manager).to receive(:login)
end
it "sets the 'config' variable value and calls login for appstore connect api token" do
options = { api_key: "fake_api_key" }
fake_manager.start(options, should_login: false)
expect(fake_manager.instance_variable_get(:@config)).to eq(options)
end
end
context "when input options has 'api_key_path' param" do
before(:each) do
expect(fake_manager).to receive(:login)
end
it "sets the 'config' variable value and calls login for appstore connect api token" do
options = { api_key_path: "fake api_key_path" }
fake_manager.start(options, should_login: false)
expect(fake_manager.instance_variable_get(:@config)).to eq(options)
end
end
end
end
describe "what happens on 'login'" do
context "when using app store connect api token" do
before(:each) do
allow(Spaceship::ConnectAPI)
.to receive(:token)
.and_return(Spaceship::ConnectAPI::Token.from(filepath: fake_api_key_json_path))
end
it "uses the existing API token if found" do
expect(Spaceship::ConnectAPI::Token).to receive(:from).with(hash: nil, filepath: nil).and_return(false)
expect(UI).to receive(:message).with("Using existing authorization token for App Store Connect API")
fake_manager.instance_variable_set(:@config, {})
fake_manager.login
end
it "creates and sets new API token using config api_key and api_key_path" do
expect(Spaceship::ConnectAPI::Token).to receive(:from).with(hash: "api_key", filepath: "api_key_path").and_return(true)
expect(UI).to receive(:message).with("Creating authorization token for App Store Connect API")
expect(Spaceship::ConnectAPI).to receive(:token=)
options = {}
options[:api_key] = "api_key"
options[:api_key_path] = "api_key_path"
fake_manager.instance_variable_set(:@config, options)
fake_manager.login
end
end
shared_examples "performing the spaceship login using username and password by pilot" do
before(:each) do
expect(fake_manager.config).to receive(:fetch).with(:username, force_ask: true)
expect(UI).to receive(:message).with("Login to App Store Connect (username)")
expect(Spaceship::ConnectAPI).to receive(:login)
expect(UI).to receive(:message).with("Login successful")
end
it "performs the login using username and password" do
fake_manager.login
end
end
context "when using web session" do
context "when username input param is given" do
before(:each) do
fake_manager.instance_variable_set(:@config, { username: "username" })
end
it_behaves_like "performing the spaceship login using username and password by pilot"
end
context "when username input param is not given but found apple_id in AppFile" do
before(:each) do
fake_manager.instance_variable_set(:@config, {})
allow(CredentialsManager::AppfileConfig)
.to receive(:try_fetch_value)
.with(:apple_id)
.and_return("username")
end
it_behaves_like "performing the spaceship login using username and password by pilot"
end
end
end
describe "what happens on fetching the 'app'" do
context "when 'app_id' variable is already set" do
before(:each) do
allow(Spaceship::ConnectAPI::App)
.to receive(:get)
.with({ app_id: fake_app_id })
.and_return(fake_app)
fake_manager.instance_variable_set(:@app_id, fake_app_id)
end
it "uses the existing 'app_id' value" do
app_result = fake_manager.app
expect(fake_manager.instance_variable_get(:@app_id)).to eq(fake_app_id)
expect(app_result).to eq(fake_app)
end
end
context "when 'app_id' variable is not set" do
before(:each) do
allow(fake_manager)
.to receive(:fetch_app_id)
.and_return(fake_app_id)
allow(Spaceship::ConnectAPI::App)
.to receive(:get)
.with({ app_id: fake_app_id })
.and_return(fake_app)
expect(fake_manager).to receive(:fetch_app_id)
end
it "tries to find the app ID automatically" do
app_result = fake_manager.app
expect(app_result).to eq(fake_app)
end
end
context "when 'app' variable is not set" do
context "when Spaceship returns a valid 'app' object" do
before(:each) do
allow(fake_manager)
.to receive(:fetch_app_id)
.and_return(fake_app_id)
allow(Spaceship::ConnectAPI::App)
.to receive(:get)
.with({ app_id: fake_app_id })
.and_return(fake_app)
expect(fake_manager).to receive(:fetch_app_id)
end
it "returns the Spaceship app object" do
app_result = fake_manager.app
expect(app_result).to eq(fake_app)
end
end
context "when Spaceship failed to return a valid 'app' object" do
before(:each) do
fake_manager.instance_variable_set(:@config, { apple_id: fake_app_id })
allow(fake_manager)
.to receive(:fetch_app_id)
.and_return(fake_app_id)
allow(Spaceship::ConnectAPI::App)
.to receive(:get)
.with({ app_id: fake_app_id })
.and_return(nil)
expect(fake_manager).to receive(:fetch_app_id)
end
it "raises the 'Could not find app' exception" do
expect(UI).to receive(:user_error!).with("Could not find app with #{fake_app_id}")
fake_manager.app
end
end
end
end
describe "what happens on fetching the 'app_id'" do
context "when 'app_id' variable is already set" do
before(:each) do
fake_manager.instance_variable_set(:@app_id, fake_app_id)
end
it "uses the existing 'app_id' value" do
fetch_app_id_result = fake_manager.fetch_app_id
expect(fake_manager.instance_variable_get(:@app_id)).to eq(fake_app_id)
expect(fetch_app_id_result).to eq(fake_app_id)
end
end
context "when 'app_id' variable is not set but config has apple_id" do
before(:each) do
fake_manager.instance_variable_set(:@config, { apple_id: fake_app_id })
end
it "uses the config apple_id for 'app_id' value" do
fetch_app_id_result = fake_manager.fetch_app_id
expect(fake_manager.instance_variable_get(:@app_id)).to eq(fake_app_id)
expect(fetch_app_id_result).to eq(fake_app_id)
end
end
context "when 'app_id' variable is not set, config does not has apple_id and failed to find app_identifier" do
before(:each) do
fake_manager.instance_variable_set(:@config, { apple_id: nil })
allow(fake_manager)
.to receive(:fetch_app_identifier)
.and_return(nil)
end
it "asks user to enter the app ID manually" do
expect(UI)
.to receive(:input)
.with("Could not automatically find the app ID, please enter it here (e.g. 956814360): ")
.and_return(fake_app_id)
fetch_app_id_result = fake_manager.fetch_app_id
expect(fetch_app_id_result).to eq(fake_app_id)
end
end
context "when 'app_id' variable is not set, config does not has apple_id but found the app_identifier" do
let(:fake_username) { "fake username" }
before(:each) do
fake_manager.instance_variable_set(:@config, { apple_id: nil })
allow(fake_manager)
.to receive(:fetch_app_identifier)
.and_return(fake_app_identifier)
end
context "when Spaceship failed to find the 'app' object using the app_identifier" do
before(:each) do
RSpec::Mocks.configuration.allow_message_expectations_on_nil = true
fake_manager.instance_variable_set(:@config, { username: fake_username })
allow(Spaceship::ConnectAPI::App)
.to receive(:find)
.with(fake_app_identifier)
.and_return(nil)
end
after(:each) do
RSpec::Mocks.configuration.allow_message_expectations_on_nil = false
end
it "raises the 'Could not find app' exception" do
allow(nil).to receive(:id).and_return(fake_app_id)
expect(UI).to receive(:user_error!).with("Couldn't find app '#{fake_app_identifier}' on the account of '#{fake_username}' on App Store Connect")
fake_manager.fetch_app_id
end
end
context "when Spaceship found the 'app' object using the app_identifier" do
before(:each) do
allow(Spaceship::ConnectAPI::App)
.to receive(:find)
.with(fake_app_identifier)
.and_return(OpenStruct.new(id: fake_app_id))
end
it "uses the Spaceship app id for 'app_id' value" do
fetch_app_id_result = fake_manager.fetch_app_id
expect(fake_manager.instance_variable_get(:@app_id)).to eq(fake_app_id)
expect(fetch_app_id_result).to eq(fake_app_id)
end
end
end
end
describe "what happens on fetching the 'app_identifier'" do
before(:each) do
expect(UI).to receive(:verbose).with("App identifier (#{fake_app_identifier})")
end
context "when config has 'app_identifier' variable" do
before(:each) do
fake_manager.instance_variable_set(:@config, { app_identifier: fake_app_identifier })
end
it "uses the config 'app_identifier' value" do
fetch_app_identifier_result = fake_manager.fetch_app_identifier
expect(fetch_app_identifier_result).to eq(fake_app_identifier)
end
end
context "when config does not has 'app_identifier' but has 'ipa' path variable" do
before(:each) do
fake_manager.instance_variable_set(:@config, { ipa: fake_ipa })
allow(FastlaneCore::IpaFileAnalyser)
.to receive(:fetch_app_identifier)
.with(fake_ipa)
.and_return(fake_app_identifier)
end
it "uses the FastlaneCore::IpaFileAnalyser with 'ipa' path to find the 'app_identifier' value" do
fetch_app_identifier_result = fake_manager.fetch_app_identifier
expect(fetch_app_identifier_result).to eq(fake_app_identifier)
end
end
context "when config does not has 'app_identifier' but has 'pkg' path variable" do
before(:each) do
fake_manager.instance_variable_set(:@config, { pkg: fake_pkg })
allow(FastlaneCore::PkgFileAnalyser)
.to receive(:fetch_app_identifier)
.with(fake_pkg)
.and_return(fake_app_identifier)
end
it "uses the FastlaneCore::PkgFileAnalyser with 'pkg' path to find the 'app_identifier' value" do
fetch_app_identifier_result = fake_manager.fetch_app_identifier
expect(fetch_app_identifier_result).to eq(fake_app_identifier)
end
end
context "when FastlaneCore::IpaFileAnalyser failed to fetch the 'app_identifier' variable" do
before(:each) do
fake_manager.instance_variable_set(:@config, { ipa: fake_ipa })
allow(FastlaneCore::IpaFileAnalyser)
.to receive(:fetch_app_identifier)
.with(fake_ipa)
.and_return(nil)
end
it "asks user to enter the app's bundle identifier manually" do
expect(UI).to receive(:input).with("Please enter the app's bundle identifier: ").and_return(fake_app_identifier)
fetch_app_identifier_result = fake_manager.fetch_app_identifier
expect(fetch_app_identifier_result).to eq(fake_app_identifier)
end
end
end
describe "what happens on fetching the 'app_platform'" do
context "when config has 'app_platform' variable" do
context "ios" do
let(:fake_app_platform) { "ios" }
before(:each) do
expect(UI).to receive(:verbose).with("App Platform (#{fake_app_platform})")
fake_manager.instance_variable_set(:@config, { app_platform: fake_app_platform })
end
it "uses the config 'app_platform' value" do
fetch_app_platform_result = fake_manager.fetch_app_platform
expect(fetch_app_platform_result).to eq(fake_app_platform)
end
end
context "osx" do
let(:fake_app_platform) { "osx" }
before(:each) do
expect(UI).to receive(:verbose).with("App Platform (#{fake_app_platform})")
fake_manager.instance_variable_set(:@config, { app_platform: fake_app_platform })
end
it "uses the config 'app_platform' value" do
fetch_app_platform_result = fake_manager.fetch_app_platform
expect(fetch_app_platform_result).to eq(fake_app_platform)
end
end
end
context "when config does not have 'app_platform'" do
context "but has 'ipa' path variable" do
let(:fake_app_platform) { "ios" }
before(:each) do
expect(UI).to receive(:verbose).with("App Platform (#{fake_app_platform})")
fake_manager.instance_variable_set(:@config, { ipa: fake_ipa })
expect(FastlaneCore::IpaFileAnalyser)
.to receive(:fetch_app_platform)
.with(fake_ipa)
.and_return(fake_app_platform)
end
it "uses the FastlaneCore::IpaFileAnalyser with 'ipa' path to find the 'app_platform' value" do
fetch_app_platform_result = fake_manager.fetch_app_platform
expect(fetch_app_platform_result).to eq(fake_app_platform)
end
end
context "but has 'pkg' path variable" do
let(:fake_app_platform) { "osx" }
before(:each) do
expect(UI).to receive(:verbose).with("App Platform (#{fake_app_platform})")
fake_manager.instance_variable_set(:@config, { pkg: fake_pkg })
expect(FastlaneCore::PkgFileAnalyser)
.to receive(:fetch_app_platform)
.with(fake_pkg)
.and_return(fake_app_platform)
end
it "uses the FastlaneCore::PkgFileAnalyser with 'pkg' path to find the 'app_platform' value" do
fetch_app_platform_result = fake_manager.fetch_app_platform
expect(fetch_app_platform_result).to eq(fake_app_platform)
end
end
end
context "when FastlaneCore::IpaFileAnalyser failed to fetch the 'app_platform' variable" do
context "ios" do
let(:fake_app_platform) { "ios" }
before(:each) do
expect(UI).to receive(:verbose).with("App Platform (#{fake_app_platform})")
fake_manager.instance_variable_set(:@config, { ipa: fake_ipa })
allow(FastlaneCore::IpaFileAnalyser)
.to receive(:fetch_app_platform)
.with(fake_ipa)
.and_return(nil)
end
it "asks user to enter the app's platform manually" do
expect(UI).to receive(:input).with("Please enter the app's platform (appletvos, ios, osx, xros): ").and_return(fake_app_platform)
fetch_app_platform_result = fake_manager.fetch_app_platform
expect(fetch_app_platform_result).to eq(fake_app_platform)
end
end
context "osx" do
let(:fake_app_platform) { "osx" }
before(:each) do
expect(UI).to receive(:verbose).with("App Platform (#{fake_app_platform})")
fake_manager.instance_variable_set(:@config, { pkg: fake_pkg })
allow(FastlaneCore::PkgFileAnalyser)
.to receive(:fetch_app_platform)
.with(fake_pkg)
.and_return(nil)
end
it "asks user to enter the app's platform manually" do
expect(UI).to receive(:input).with("Please enter the app's platform (appletvos, ios, osx, xros): ").and_return(fake_app_platform)
fetch_app_platform_result = fake_manager.fetch_app_platform
expect(fetch_app_platform_result).to eq(fake_app_platform)
end
end
end
context "when FastlaneCore::IpaFileAnalyser failed to fetch the 'app_platform' variable and its not required to enter manually" do
context "ios" do
let(:fake_app_platform) { "ios" }
before(:each) do
expect(UI).not_to receive(:verbose).with("App Platform (#{fake_app_platform})")
fake_manager.instance_variable_set(:@config, { ipa: fake_ipa })
allow(FastlaneCore::IpaFileAnalyser)
.to receive(:fetch_app_platform)
.with(fake_ipa)
.and_return(nil)
end
it "does not ask user to enter the app's platform manually" do
expect(UI).not_to receive(:input).with("Please enter the app's platform (appletvos, ios, osx, xros): ")
fetch_app_platform_result = fake_manager.fetch_app_platform(required: false)
expect(fetch_app_platform_result).to eq(nil)
end
end
end
context "when user entered an invalid 'app_platform' manually" do
let(:invalid_app_platform) { "invalid platform" }
before(:each) do
expect(UI).to receive(:verbose).with("App Platform (#{invalid_app_platform})")
fake_manager.instance_variable_set(:@config, { ipa: fake_ipa })
allow(FastlaneCore::IpaFileAnalyser)
.to receive(:fetch_app_platform)
.with(fake_ipa)
.and_return(nil)
allow(UI)
.to receive(:input)
.with("Please enter the app's platform (appletvos, ios, osx, xros): ")
.and_return(invalid_app_platform)
end
it "raises the 'invalid platform' exception" do
expect(UI).to receive(:user_error!).with("App Platform must be ios, appletvos, osx, or xros")
fake_manager.fetch_app_platform
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pilot/spec/tester_importer_spec.rb | pilot/spec/tester_importer_spec.rb | require 'csv'
describe Pilot::TesterImporter do
describe ".import_testers" do
let(:fake_tester_importer) { Pilot::TesterImporter.new }
context "when testers CSV file path is not given" do
let(:fake_tester_manager) { double("tester manager") }
let(:empty_input_options) { {} }
before(:each) do
fake_tester_importer.instance_variable_set(:@config, empty_input_options)
allow(CSV).to receive(:foreach).and_return([])
allow(Pilot::TesterManager).to receive(:new).and_return(fake_tester_manager)
allow(fake_tester_importer).to receive(:start).with(empty_input_options)
end
it "raises an fatal exception with message" do
expect(UI).to receive(:user_error!).with("Import file path is required")
fake_tester_importer.import_testers(empty_input_options)
end
end
context "when testers CSV file path is given" do
let(:fake_tester_manager) { double("tester manager") }
let(:fake_testers_file_path) { Tempfile.new("fake testers_file_path").path }
let(:fake_input_options) do
{
testers_file_path: fake_testers_file_path
}
end
before(:each) do
fake_tester_importer.instance_variable_set(:@config, fake_input_options)
allow(Pilot::TesterManager).to receive(:new).and_return(fake_tester_manager)
allow(fake_tester_importer).to receive(:start).with(fake_input_options)
end
context "when No email found in CSV row" do
let(:fake_row) { ["FirstName", "LastName", "group-1;group-2"] }
before(:each) do
allow(CSV).to receive(:foreach).with(fake_testers_file_path, "r").and_yield(fake_row)
end
it "prints an non-fatal error message and continue" do
expect(UI).to receive(:error).with("No email found in row: #{fake_row}")
expect(UI).to receive(:success).with("Successfully imported 0 testers from #{fake_testers_file_path}")
fake_tester_importer.import_testers(fake_input_options)
end
end
context "when invalid email found in CSV row" do
let(:fake_row) { ["FirstName", "LastName", "invalid-email-address", "group-1;group-2"] }
before(:each) do
allow(CSV).to receive(:foreach).with(fake_testers_file_path, "r").and_yield(fake_row)
end
it "prints an non-fatal error message and continue" do
expect(UI).to receive(:error).with("No email found in row: #{fake_row}")
expect(UI).to receive(:success).with("Successfully imported 0 testers from #{fake_testers_file_path}")
fake_tester_importer.import_testers(fake_input_options)
end
end
context "when valid tester details found in CSV row" do
let(:fake_email) { "valid@email.address" }
let(:fake_row) { ["FirstName", "LastName", fake_email, "group-1;group-2"] }
before(:each) do
allow(CSV).to receive(:foreach).with(fake_testers_file_path, "r").and_yield(fake_row)
end
context "when tester manager succeeded to add a new tester" do
before(:each) do
expect(fake_tester_manager).to receive(:add_tester).with({
first_name: "FirstName",
last_name: "LastName",
email: fake_email,
groups: ["group-1", "group-2"],
testers_file_path: fake_testers_file_path
})
end
it "prints a success message for the added tester" do
expect(UI).to receive(:success).with("Successfully imported 1 testers from #{fake_testers_file_path}")
fake_tester_importer.import_testers(fake_input_options)
end
end
context "when tester manager failed to add a new tester" do
let(:fake_exception) { "fake exception" }
before(:each) do
expect(fake_tester_manager).to receive(:add_tester).with({
first_name: "FirstName",
last_name: "LastName",
email: fake_email,
groups: ["group-1", "group-2"],
testers_file_path: fake_testers_file_path
}).and_raise(fake_exception)
end
it "prints an non-fatal error message" do
expect(UI).to receive(:error).with("Error adding tester #{fake_email}: #{fake_exception}")
expect(UI).to receive(:success).with("Successfully imported 0 testers from #{fake_testers_file_path}")
fake_tester_importer.import_testers(fake_input_options)
end
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pilot/spec/spec_helper.rb | pilot/spec/spec_helper.rb | def before_each_pilot
ENV["DELIVER_USER"] = "DELIVERUSER"
ENV["DELIVER_PASSWORD"] = "DELIVERPASS"
ENV["DELIVER_HTML_EXPORT_PATH"] = "/tmp" # to not pollute the working directory
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pilot/spec/test_exporter_spec.rb | pilot/spec/test_exporter_spec.rb | require 'csv'
describe Pilot::TesterExporter do
describe ".export_testers" do
let(:fake_tester_exporter) { Pilot::TesterExporter.new }
let(:fake_tester_manager) { double("tester manager") }
let(:fake_testers_file_path) { Tempfile.new("fake testers_file_path").path }
let(:fake_apple_id) { "fake apple_id" }
let(:fake_app_identifier) { "fake app_identifier" }
let(:fake_input_options) do
{
testers_file_path: fake_testers_file_path,
apple_id: fake_apple_id,
app_identifier: fake_app_identifier
}
end
before(:each) do
fake_tester_exporter.instance_variable_set(:@config, fake_input_options)
allow(Pilot::TesterManager).to receive(:new).and_return(fake_tester_manager)
allow(fake_tester_exporter).to receive(:start).with(fake_input_options)
end
context "when able to find app using apple_id and app_identifier" do
let(:fake_app) { "fake app" }
before(:each) do
allow(fake_app).to receive(:get_beta_testers).with(includes: "apps,betaTesterMetrics,betaGroups").and_return([])
allow(fake_tester_exporter).to receive(:find_app).with(apple_id: fake_apple_id, app_identifier: fake_app_identifier).and_return(fake_app)
end
it "exports beta testers inside the correct file path" do
expect(CSV).to receive(:open).with(fake_testers_file_path, "w")
fake_tester_exporter.export_testers(fake_input_options)
end
it "shows a success message after export" do
expect(UI).to receive(:success).with("Successfully exported CSV to #{fake_testers_file_path}")
fake_tester_exporter.export_testers(fake_input_options)
end
end
context "when failed to find app using apple_id and app_identifier" do
let(:fake_app) { "fake app" }
before(:each) do
allow(fake_tester_exporter).to receive(:find_app).with(apple_id: fake_apple_id, app_identifier: fake_app_identifier).and_return(nil)
allow(Spaceship::ConnectAPI::BetaTester).to receive(:all).with(includes: "apps,betaTesterMetrics,betaGroups").and_return([])
end
it "exports beta testers inside the correct file path" do
expect(CSV).to receive(:open).with(fake_testers_file_path, "w")
fake_tester_exporter.export_testers(fake_input_options)
end
it "shows a success message after export" do
expect(UI).to receive(:success).with("Successfully exported CSV to #{fake_testers_file_path}")
fake_tester_exporter.export_testers(fake_input_options)
end
end
end
describe ".find_app" do
let(:fake_tester_exporter) { Pilot::TesterExporter.new }
let(:fake_app) { "fake app" }
context "when app_identifier is given" do
let(:fake_app_identifier) { "fake app_identifier" }
context "when able to find app using app_identifier" do
before(:each) do
allow(Spaceship::ConnectAPI::App).to receive(:find).with(fake_app_identifier).and_return(fake_app)
end
it "returns the app correctly" do
received_app = fake_tester_exporter.find_app(app_identifier: fake_app_identifier)
expect(received_app).to eq(fake_app)
end
end
context "when failed to find app using app_identifier" do
before(:each) do
allow(Spaceship::ConnectAPI::App).to receive(:find).with(fake_app_identifier).and_return(nil)
end
it "raises an fatal exception with message" do
expect(UI).to receive(:user_error!).with("Could not find an app by #{fake_app_identifier}")
fake_tester_exporter.find_app(app_identifier: fake_app_identifier)
end
end
end
context "when app_identifier is not given but apple_id is given" do
let(:fake_apple_id) { "fake apple_id" }
context "when able to find app using apple_id" do
before(:each) do
allow(Spaceship::ConnectAPI::App).to receive(:get).with(app_id: fake_apple_id).and_return(fake_app)
end
it "returns the app correctly" do
received_app = fake_tester_exporter.find_app(apple_id: fake_apple_id)
expect(received_app).to eq(fake_app)
end
end
context "when failed to find app using apple_id" do
before(:each) do
allow(Spaceship::ConnectAPI::App).to receive(:get).with(app_id: fake_apple_id).and_return(nil)
end
it "raises an fatal exception with message" do
expect(UI).to receive(:user_error!).with("Could not find an app by #{fake_apple_id}")
fake_tester_exporter.find_app(apple_id: fake_apple_id)
end
end
end
context "when app_identifier and apple_id both are not given" do
it "raises an fatal exception with message" do
expect(UI).to receive(:user_error!).with("You must include an `app_identifier` to `list_testers`")
fake_tester_exporter.find_app
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/pilot/spec/options_spec.rb | pilot/spec/options_spec.rb | describe Pilot::Options do
before(:each) do
ENV.delete('FASTLANE_TEAM_ID')
end
after(:each) do
ENV.delete('FASTLANE_TEAM_ID')
end
it "accepts a developer portal team ID" do
FastlaneCore::Configuration.create(Pilot::Options.available_options, { dev_portal_team_id: 'ABCD1234' })
expect(ENV['FASTLANE_TEAM_ID']).to eq('ABCD1234')
end
context "beta_app_review_info" do
it "accepts valid values" do
options = {
beta_app_review_info: {
contact_email: "email@email.com",
contact_first_name: "Connect",
contact_last_name: "API",
contact_phone: "5558675309}",
demo_account_name: "demo@email.com",
demo_account_password: "connectapi",
notes: "this is review note for the reviewer <3 thank you for reviewing"
}
}
expect do
FastlaneCore::Configuration.create(Pilot::Options.available_options, options)
end.not_to(raise_error)
end
it "throws errors for invalid keys" do
options = {
beta_app_review_info: {
contact_email: "email@email.com",
contact_first_name: "Connect",
contact_last_name: "API",
contact_phone: "5558675309}",
demo_account_name: "demo@email.com",
cheese: "pizza",
demo_account_password: "connectapi",
notes: "this is review note for the reviewer <3 thank you for reviewing"
}
}
expect do
FastlaneCore::Configuration.create(Pilot::Options.available_options, options)
end.to raise_error(FastlaneCore::Interface::FastlaneError, "Invalid key 'cheese'")
end
end
context "localized_app_info" do
it "accepts valid values" do
options = {
localized_app_info: {
'default' => {
feedback_email: "default@email.com",
marketing_url: "https://example.com/marketing-default",
privacy_policy_url: "https://example.com/privacy-default",
tv_os_privacy_policy_url: "https://example.com/privacy-default",
description: "Default description"
},
'en-GB' => {
feedback_email: "en-gb@email.com",
marketing_url: "https://example.com/marketing-en-gb",
privacy_policy_url: "https://example.com/privacy-en-gb",
tv_os_privacy_policy_url: "https://example.com/privacy-en-gb",
description: "en-gb description"
}
}
}
expect do
FastlaneCore::Configuration.create(Pilot::Options.available_options, options)
end.not_to(raise_error)
end
it "throws errors for invalid keys" do
options = {
localized_app_info: {
'default' => {
feedback_email: "default@email.com",
marketing_url: "https://example.com/marketing-default",
privacy_policy_url: "https://example.com/privacy-default",
tv_os_privacy_policy_url: "https://example.com/privacy-default",
description: "Default description"
},
'en-GB' => {
feedback_email: "en-gb@email.com",
marketing_url: "https://example.com/marketing-en-gb",
pepperoni: "pizza",
privacy_policy_url: "https://example.com/privacy-en-gb",
tv_os_privacy_policy_url: "https://example.com/privacy-en-gb",
description: "en-gb description"
}
}
}
expect do
FastlaneCore::Configuration.create(Pilot::Options.available_options, options)
end.to raise_error(FastlaneCore::Interface::FastlaneError, "Invalid key 'pepperoni'")
end
end
context "localized_build_info" do
it "accepts valid values" do
options = {
localized_build_info: {
'default' => {
whats_new: "Default changelog"
},
'en-GB' => {
whats_new: "en-gb changelog"
}
}
}
expect do
FastlaneCore::Configuration.create(Pilot::Options.available_options, options)
end.not_to(raise_error)
end
it "throws errors for invalid keys" do
options = {
localized_build_info: {
'default' => {
whats_new: "Default changelog"
},
'en-GB' => {
whats_new: "en-gb changelog",
buffalo_chicken: "pizza"
}
}
}
expect do
FastlaneCore::Configuration.create(Pilot::Options.available_options, options)
end.to raise_error(FastlaneCore::Interface::FastlaneError, "Invalid key 'buffalo_chicken'")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.