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/fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb | fastlane_core/lib/fastlane_core/ui/fastlane_runner.rb | unless Object.const_defined?("Faraday")
# We create these empty error classes if we didn't require Faraday
# so that we can use it in the rescue block below even if we didn't
# require Faraday or didn't use it
module Faraday
class Error < StandardError; end
class ClientError < Error; end
class SSLError < ClientError; end
class ConnectionFailed < ClientError; end
end
end
unless Object.const_defined?("OpenSSL")
module OpenSSL
module SSL
class SSLError < StandardError; end
end
end
end
require 'commander'
require_relative '../env'
require_relative '../globals'
require_relative '../analytics/action_completion_context'
require_relative '../analytics/action_launch_context'
require_relative 'errors'
module Commander
# This class override the run method with our custom stack trace handling
# In particular we want to distinguish between user_error! and crash! (one with, one without stack trace)
class Runner
# Code taken from https://github.com/commander-rb/commander/blob/master/lib/commander/runner.rb#L50
attr_accessor :collector
# Temporary workaround for issues mentioned in https://github.com/fastlane/fastlane/pull/18760
# Code taken from https://github.com/commander-rb/commander/blob/40d06bfbc54906d0de7c72ac73f4e9188c9ca294/lib/commander/runner.rb#L372-L385
#
# Problem:
# `optparse` is guessing that command option `-e` is referring to global option `--env` (because it starts with an e).
# This is raising OptionParser::MissingArgument error because `--env` takes a string argument.
# A command of `-e --verbose` works because `--verbose` is seen as the argument.
# A command of `--verbose -e` doesn't work because no argument after `-e` so MissingArgument is raised again.
# This broke somewhere between Ruby 2.5 and Ruby 2.6
#
# Solution:
# Proper solution is to set `parser.require_exact = true` but this only available on `optparse` version 0.1.1
# which is not used by Commander.
# `require_exact` will prevent OptionParser from assuming `-e` is the same as `--env STRING`
# Even if it was on RubyGems, it would require Commander to allow this option to be set on OptionParser
#
# This work around was made on 2021-08-13
#
# When fixed:
# This method implementation overrides one provided by Commander::Runner already. Just delete this method
# so the existing one can be used
def parse_global_options
parser = options.inject(OptionParser.new) do |options, option|
options.on(*option[:args], &global_option_proc(option[:switches], &option[:proc]))
end
# This is the actual solution but is only in version 0.1.1 of optparse and its not in Commander
# This is the only change from Commanders implementation of parse_global_options
parser.require_exact = true
options = @args.dup
begin
parser.parse!(options)
rescue OptionParser::InvalidOption => e
# Remove the offending args and retry.
options = options.reject { |o| e.args.include?(o) }
retry
end
end
def run!
require_program(:version, :description)
trap('INT') { abort(program(:int_message)) } if program(:int_message)
trap('INT') { program(:int_block).call } if program(:int_block)
global_option('-h', '--help', 'Display help documentation') do
args = @args - %w(-h --help)
command(:help).run(*args)
return
end
global_option('-v', '--version', 'Display version information') do
say(version)
return
end
parse_global_options
remove_global_options(options, @args)
xcode_outdated = false
begin
unless FastlaneCore::Helper.xcode_at_least?(Fastlane::MINIMUM_XCODE_RELEASE)
xcode_outdated = true
end
rescue
# We don't care about exceptions here
# We'll land here if the user doesn't have Xcode at all for example
# which is fine for someone who uses fastlane just for Android project
# What we *do* care about is when someone links an old version of Xcode
end
begin
if xcode_outdated
# We have to raise that error within this `begin` block to show a nice user error without a stack trace
FastlaneCore::UI.user_error!("fastlane requires a minimum version of Xcode #{Fastlane::MINIMUM_XCODE_RELEASE}, please upgrade and make sure to use `sudo xcode-select -s /Applications/Xcode.app`")
end
is_swift = FastlaneCore::FastlaneFolder.swift?
fastlane_client_language = is_swift ? :swift : :ruby
action_launch_context = FastlaneCore::ActionLaunchContext.context_for_action_name(@program[:name], fastlane_client_language: fastlane_client_language, args: ARGV)
FastlaneCore.session.action_launched(launch_context: action_launch_context)
# Trainer has been added to fastlane as of 2.201.0
# We need to make sure that the trainer fastlane plugin is no longer installed
# to avoid any clashes
if Gem::Specification.any? { |s| (s.name == 'fastlane-plugin-trainer') && Gem::Requirement.default =~ (s.version) }
FastlaneCore::UI.user_error!("Migration Needed: As of 2.201.0, trainer is included in fastlane. Please remove the trainer plugin from your Gemfile or Pluginfile (or with 'gem uninstall fastlane-plugin-trainer') - More information: https://docs.fastlane.tools/best-practices/xcodebuild-formatters/")
end
return_value = run_active_command
action_completed(@program[:name], status: FastlaneCore::ActionCompletionStatus::SUCCESS)
return return_value
rescue Commander::Runner::InvalidCommandError => e
# calling `abort` makes it likely that tests stop without failing, so
# we'll disable that during tests.
if FastlaneCore::Helper.test?
raise e
else
abort("#{e}. Use --help for more information")
end
rescue Interrupt => e
# We catch it so that the stack trace is hidden by default when using ctrl + c
if FastlaneCore::Globals.verbose?
raise e
else
action_completed(@program[:name], status: FastlaneCore::ActionCompletionStatus::INTERRUPTED, exception: e)
abort("\nCancelled... use --verbose to show the stack trace")
end
rescue \
OptionParser::InvalidOption,
OptionParser::InvalidArgument,
OptionParser::MissingArgument => e
# calling `abort` makes it likely that tests stop without failing, so
# we'll disable that during tests.
if FastlaneCore::Helper.test?
raise e
else
if self.active_command.name == "help" && @default_command == :help # need to access directly via @
# This is a special case, for example for pilot
# when the user runs `fastlane pilot -u user@google.com`
# This would be confusing, as the user probably wanted to use `pilot list`
# or some other command. Because `-u` isn't available for the `pilot --help`
# command it would show this very confusing error message otherwise
abort("Please ensure to use one of the available commands (#{self.commands.keys.join(', ')})".red)
else
# This would print something like
#
# invalid option: -u
#
abort(e.to_s)
end
end
rescue FastlaneCore::Interface::FastlaneCommonException => e # these are exceptions that we don't count as crashes
display_user_error!(e, e.to_s)
rescue FastlaneCore::Interface::FastlaneError => e # user_error!
rescue_fastlane_error(e)
rescue Errno::ENOENT => e
rescue_file_error(e)
rescue Faraday::SSLError, OpenSSL::SSL::SSLError => e # SSL issues are very common
handle_ssl_error!(e)
rescue Faraday::ConnectionFailed => e
rescue_connection_failed_error(e)
rescue => e # high chance this is actually FastlaneCore::Interface::FastlaneCrash, but can be anything else
rescue_unknown_error(e)
ensure
FastlaneCore.session.finalize_session
end
end
def action_completed(action_name, status: nil, exception: nil)
# https://github.com/fastlane/fastlane/issues/11913
# if exception.nil? || exception.fastlane_should_report_metrics?
# action_completion_context = FastlaneCore::ActionCompletionContext.context_for_action_name(action_name, args: ARGV, status: status)
# FastlaneCore.session.action_completed(completion_context: action_completion_context)
# end
end
def rescue_file_error(e)
# We're also printing the new-lines, as otherwise the message is not very visible in-between the error and the stack trace
puts("")
FastlaneCore::UI.important("Error accessing file, this might be due to fastlane's directory handling")
FastlaneCore::UI.important("Check out https://docs.fastlane.tools/advanced/#directory-behavior for more details")
puts("")
raise e
end
def rescue_connection_failed_error(e)
if e.message.include?('Connection reset by peer - SSL_connect')
handle_tls_error!(e)
else
handle_unknown_error!(e)
end
end
def rescue_unknown_error(e)
action_completed(@program[:name], status: FastlaneCore::ActionCompletionStatus::FAILED, exception: e)
handle_unknown_error!(e)
end
def rescue_fastlane_error(e)
action_completed(@program[:name], status: FastlaneCore::ActionCompletionStatus::USER_ERROR, exception: e)
show_github_issues(e.message) if e.show_github_issues
display_user_error!(e, e.message)
end
def handle_tls_error!(e)
# Apple has upgraded its App Store Connect servers to require TLS 1.2, but
# system Ruby 2.0 does not support it. We want to suggest that users upgrade
# their Ruby version
suggest_ruby_reinstall(e)
display_user_error!(e, e.to_s)
end
def handle_ssl_error!(e)
# SSL errors are very common when the Ruby or OpenSSL installation is somehow broken
# We want to show a nice error message to the user here
# We have over 20 GitHub issues just for this one error:
# https://github.com/fastlane/fastlane/search?q=errno%3D0+state%3DSSLv3+read+server&type=Issues
suggest_ruby_reinstall(e)
display_user_error!(e, e.to_s)
end
def suggest_ruby_reinstall(e)
ui = FastlaneCore::UI
ui.error("-----------------------------------------------------------------------")
ui.error(e.to_s)
ui.error("")
ui.error("SSL errors can be caused by various components on your local machine.")
ui.error("")
ui.error("The best solution is to use the self-contained fastlane version.")
ui.error("Which ships with a bundled OpenSSL,ruby and all gems - so you don't depend on system libraries")
ui.error(" - Use Homebrew")
ui.error(" - update brew with `brew update`")
ui.error(" - install fastlane using:")
ui.error(" - `brew install fastlane`")
ui.error(" - Use One-Click-Installer:")
ui.error(" - download fastlane at https://download.fastlane.tools")
ui.error(" - extract the archive and double click the `install`")
ui.error("-----------------------------------------------------------")
ui.error("for more details on ways to install fastlane please refer the documentation:")
ui.error("-----------------------------------------------------------")
ui.error(" 🚀 https://docs.fastlane.tools 🚀 ")
ui.error("-----------------------------------------------------------")
ui.error("")
ui.error("You can also install a new version of Ruby")
ui.error("")
ui.error("- Make sure OpenSSL is installed with Homebrew: `brew update && brew upgrade openssl`")
ui.error("- If you use system Ruby:")
ui.error(" - Run `brew update && brew install ruby`")
ui.error("- If you use rbenv with ruby-build:")
ui.error(" - Run `brew update && brew upgrade ruby-build && rbenv install 2.3.1`")
ui.error(" - Run `rbenv global 2.3.1` to make it the new global default Ruby version")
ui.error("- If you use rvm:")
ui.error(" - First run `rvm osx-ssl-certs update all`")
ui.error(" - Then run `rvm reinstall ruby-2.3.1 --with-openssl-dir=/usr/local`")
ui.error("")
ui.error("If that doesn't fix your issue, please google for the following error message:")
ui.error(" '#{e}'")
ui.error("-----------------------------------------------------------------------")
end
def handle_unknown_error!(e)
# Some spaceship exception classes implement #preferred_error_info in order to share error info
# that we'd rather display instead of crashing with a stack trace. However, fastlane_core and
# spaceship cannot know about each other's classes! To make this information passing work, we
# use a bit of Ruby duck-typing to check whether the unknown exception type implements the right
# method. If so, we'll present any returned error info in the manner of a user_error!
error_info = e.respond_to?(:preferred_error_info) ? e.preferred_error_info : nil
should_show_github_issues = e.respond_to?(:show_github_issues) ? e.show_github_issues : true
if error_info
error_info = error_info.join("\n\t") if error_info.kind_of?(Array)
show_github_issues(error_info) if should_show_github_issues
display_user_error!(e, error_info)
else
# Pass the error instead of a message so that the inspector can do extra work to simplify the query
show_github_issues(e) if should_show_github_issues
# From https://stackoverflow.com/a/4789702/445598
# We do this to make the actual error message red and therefore more visible
reraise_formatted!(e, e.message)
end
end
def display_user_error!(e, message)
if FastlaneCore::Globals.verbose?
# with stack trace
reraise_formatted!(e, message)
else
# without stack trace
action_completed(@program[:name], status: FastlaneCore::ActionCompletionStatus::USER_ERROR, exception: e)
abort("\n[!] #{message}".red)
end
end
def reraise_formatted!(e, message)
backtrace = FastlaneCore::Env.truthy?("FASTLANE_HIDE_BACKTRACE") ? [] : e.backtrace
raise e, "[!] #{message}".red, backtrace
end
def show_github_issues(message_or_error)
return if FastlaneCore::Env.truthy?("FASTLANE_HIDE_GITHUB_ISSUES")
return if FastlaneCore::Helper.test?
require 'gh_inspector'
require 'fastlane_core/ui/github_issue_inspector_reporter'
inspector = GhInspector::Inspector.new("fastlane", "fastlane", verbose: FastlaneCore::Globals.verbose?)
delegate = Fastlane::InspectorReporter.new
if message_or_error.kind_of?(String)
inspector.search_query(message_or_error, delegate)
else
inspector.search_exception(message_or_error, delegate)
end
rescue => ex
FastlaneCore::UI.error("Error finding relevant GitHub issues: #{ex}") if FastlaneCore::Globals.verbose?
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane_core/lib/fastlane_core/ui/github_issue_inspector_reporter.rb | fastlane_core/lib/fastlane_core/ui/github_issue_inspector_reporter.rb | require_relative '../helper'
require_relative '../globals'
module Fastlane
# Adds all the necessary emojis (obv)
#
class InspectorReporter
NUMBER_OF_ISSUES_INLINE = 3
# Called just as the investigation has begun.
def inspector_started_query(query, inspector)
puts("")
puts("Looking for related GitHub issues on #{inspector.repo_owner}/#{inspector.repo_name}...")
puts("Search query: #{query}") if FastlaneCore::Globals.verbose?
puts("")
end
# Called once the inspector has received a report with more than one issue.
def inspector_successfully_received_report(report, inspector)
report.issues[0..(NUMBER_OF_ISSUES_INLINE - 1)].each { |issue| print_issue_full(issue) }
if report.issues.count > NUMBER_OF_ISSUES_INLINE
report.url.sub!('\'', '%27')
puts("and #{report.total_results - NUMBER_OF_ISSUES_INLINE} more at: #{report.url}")
puts("")
end
print_open_link_hint
end
# Called once the report has been received, but when there are no issues found.
def inspector_received_empty_report(report, inspector)
puts("Found no similar issues. To create a new issue, please visit:")
puts("https://github.com/#{inspector.repo_owner}/#{inspector.repo_name}/issues/new")
puts("Run `fastlane env` to append the fastlane environment to your issue")
end
# Called when there have been networking issues in creating the report.
def inspector_could_not_create_report(error, query, inspector)
puts("Could not access the GitHub API, you may have better luck via the website.")
puts("https://github.com/#{inspector.repo_owner}/#{inspector.repo_name}/search?q=#{query}&type=Issues&utf8=✓")
puts("Error: #{error.name}")
end
private
def print_issue_full(issue)
resolved = issue.state == 'closed'
status = (resolved ? issue.state.green : issue.state.red)
puts("➡️ #{issue.title.yellow}")
puts(" #{issue.html_url} [#{status}] #{issue.comments} 💬")
puts(" #{Time.parse(issue.updated_at).to_pretty}")
puts("")
end
def print_open_link_hint(newline = false)
puts("") if newline
puts("🔗 You can ⌘ + double-click on links to open them directly in your browser.") if FastlaneCore::Helper.mac?
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane_core/lib/fastlane_core/ui/errors/fastlane_exception.rb | fastlane_core/lib/fastlane_core/ui/errors/fastlane_exception.rb | module FastlaneCore
class Interface
class FastlaneException < StandardError
def prefix
'[FASTLANE_EXCEPTION]'
end
def caused_by_calling_ui_method?(method_name: nil)
return false if backtrace.nil? || backtrace[0].nil? || method_name.nil?
first_frame = backtrace[0]
if first_frame.include?(method_name) && first_frame.include?('interface.rb')
true
else
false
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane_core/lib/fastlane_core/ui/errors/fastlane_error.rb | fastlane_core/lib/fastlane_core/ui/errors/fastlane_error.rb | require_relative 'fastlane_exception'
module FastlaneCore
class Interface
class FastlaneError < FastlaneException
attr_reader :show_github_issues
attr_reader :error_info
def initialize(show_github_issues: false, error_info: nil)
@show_github_issues = show_github_issues
@error_info = error_info
end
def prefix
'[USER_ERROR]'
end
end
end
end
class Exception
def fastlane_should_report_metrics?
return false
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane_core/lib/fastlane_core/ui/errors/fastlane_common_error.rb | fastlane_core/lib/fastlane_core/ui/errors/fastlane_common_error.rb | require_relative 'fastlane_exception'
module FastlaneCore
class Interface
# Super class for exception types that we do not want to record
# explicitly as crashes or user errors
class FastlaneCommonException < FastlaneException; end
# Raised when there is a build failure in xcodebuild
class FastlaneBuildFailure < FastlaneCommonException; end
# Raised when a test fails when being run by tools such as scan or snapshot
class FastlaneTestFailure < FastlaneCommonException; end
# Raise this type of exception when a failure caused by a third party
# dependency (i.e. xcodebuild, gradle, slather) happens.
class FastlaneDependencyCausedException < FastlaneCommonException; end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane_core/lib/fastlane_core/ui/errors/fastlane_shell_error.rb | fastlane_core/lib/fastlane_core/ui/errors/fastlane_shell_error.rb | require_relative 'fastlane_exception'
module FastlaneCore
class Interface
class FastlaneShellError < FastlaneException
def prefix
'[SHELL_ERROR]'
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane_core/lib/fastlane_core/ui/errors/fastlane_crash.rb | fastlane_core/lib/fastlane_core/ui/errors/fastlane_crash.rb | require_relative 'fastlane_exception'
module FastlaneCore
class Interface
class FastlaneCrash < FastlaneException
def prefix
'[FASTLANE_CRASH]'
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane_core/lib/fastlane_core/ui/implementations/shell.rb | fastlane_core/lib/fastlane_core/ui/implementations/shell.rb | require_relative '../../helper'
require_relative '../../globals'
require_relative '../../env'
require_relative '../interface'
module FastlaneCore
# Shell is the terminal output of things
# For documentation for each of the methods open `interface.rb`
class Shell < Interface
require 'tty-screen'
def log
return @log if @log
$stdout.sync = true
if Helper.test? && !ENV.key?('DEBUG')
$stdout.puts("Logging disabled while running tests. Force them by setting the DEBUG environment variable")
@log ||= Logger.new(nil) # don't show any logs when running tests
else
@log ||= Logger.new($stdout)
end
@log.formatter = proc do |severity, datetime, progname, msg|
"#{format_string(datetime, severity)}#{msg}\n"
end
@log
end
def format_string(datetime = Time.now, severity = "")
timezone_string = !FastlaneCore::Env.truthy?('FASTLANE_SHOW_TIMEZONE') ? '' : ' %z'
if FastlaneCore::Globals.verbose?
return "#{severity} [#{datetime.strftime('%Y-%m-%d %H:%M:%S.%2N' + timezone_string)}]: "
elsif FastlaneCore::Env.truthy?("FASTLANE_HIDE_TIMESTAMP")
return ""
else
return "[#{datetime.strftime('%H:%M:%S' + timezone_string)}]: "
end
end
#####################################################
# @!group Messaging: show text to the user
#####################################################
def error(message)
log.error(message.to_s.red)
end
def important(message)
log.warn(message.to_s.yellow)
end
def success(message)
log.info(message.to_s.green)
end
def message(message)
log.info(message.to_s)
end
def deprecated(message)
log.error(message.to_s.deprecated)
end
def command(message)
log.info("$ #{message}".cyan)
end
def command_output(message)
actual = (encode_as_utf_8_if_possible(message).split("\r").last || "") # as clearing the line will remove the `>` and the time stamp
actual.split("\n").each do |msg|
if FastlaneCore::Env.truthy?("FASTLANE_DISABLE_OUTPUT_FORMAT")
log.info(msg)
else
prefix = msg.include?("▸") ? "" : "▸ "
log.info(prefix + "" + msg.magenta)
end
end
end
def verbose(message)
log.debug(message.to_s) if FastlaneCore::Globals.verbose?
end
def header(message)
format = format_string
# clamp to zero to prevent negative argument error below
available_width = [0, TTY::Screen.width - format.length].max
if message.length + 8 < available_width
message = "--- #{message} ---"
i = message.length
else
i = available_width
end
success("-" * i)
success(message)
success("-" * i)
end
def content_error(content, error_line)
error_line = error_line.to_i
return unless error_line > 0
contents = content.split(/\r?\n/).map(&:chomp)
start_line = error_line - 2 < 1 ? 1 : error_line - 2
end_line = error_line + 2 < contents.length ? error_line + 2 : contents.length
error('```')
Range.new(start_line, end_line).each do |line|
str = line == error_line ? " => " : " "
str << line.to_s.rjust(Math.log10(end_line) + 1)
str << ":\t#{contents[line - 1]}"
error(str)
end
error('```')
end
#####################################################
# @!group Errors: Inputs
#####################################################
def interactive?
interactive = true
interactive = false if $stdout.isatty == false
interactive = false if Helper.ci?
return interactive
end
def input(message)
verify_interactive!(message)
ask("#{format_string}#{message.to_s.yellow}").to_s.strip
end
def confirm(message)
verify_interactive!(message)
agree("#{format_string}#{message.to_s.yellow} (y/n)", true)
end
def select(message, options)
verify_interactive!(message)
important(message)
choose(*options)
end
def password(message)
verify_interactive!(message)
ask("#{format_string}#{message.to_s.yellow}") do |q|
q.whitespace = :chomp
q.echo = "*"
end
end
private
def encode_as_utf_8_if_possible(message)
return message if message.valid_encoding?
# genstrings outputs UTF-16, so we should try to use this encoding if it turns out to be valid
test_message = message.dup
return message.encode(Encoding::UTF_8, Encoding::UTF_16) if test_message.force_encoding(Encoding::UTF_16).valid_encoding?
# replace any invalid with empty string
message.encode(Encoding::UTF_8, invalid: :replace)
end
def verify_interactive!(message)
return if interactive?
important(message)
crash!("Could not retrieve response as fastlane runs in non-interactive mode")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane_core/lib/fastlane_core/update_checker/update_checker.rb | fastlane_core/lib/fastlane_core/update_checker/update_checker.rb | require 'excon'
require 'digest'
require_relative 'changelog'
require_relative '../analytics/app_identifier_guesser'
require_relative '../helper'
require_relative '../ui/ui'
module FastlaneCore
# Verifies, the user runs the latest version of this gem
class UpdateChecker
def self.start_looking_for_update(gem_name)
return if Helper.test?
return if FastlaneCore::Env.truthy?("FASTLANE_SKIP_UPDATE_CHECK")
@start_time = Time.now
Thread.new do
begin
server_results[gem_name] = fetch_latest(gem_name)
rescue
# we don't want to show a stack trace if something goes wrong
end
end
end
def self.server_results
@results ||= {}
end
class << self
attr_reader :start_time
end
def self.update_available?(gem_name, current_version)
latest = server_results[gem_name]
return (latest and Gem::Version.new(latest) > Gem::Version.new(current_version))
end
def self.show_update_status(gem_name, current_version)
if update_available?(gem_name, current_version)
show_update_message(gem_name, current_version)
end
end
# Show a message to the user to update to a new version of fastlane (or a sub-gem)
# Use this method, as this will detect the current Ruby environment and show an
# appropriate message to the user
def self.show_update_message(gem_name, current_version)
available = server_results[gem_name]
puts("")
puts('#######################################################################')
if available
puts("# #{gem_name} #{available} is available. You are on #{current_version}.")
else
puts("# An update for #{gem_name} is available. You are on #{current_version}.")
end
puts("# You should use the latest version.")
puts("# Please update using `#{self.update_command(gem_name: gem_name)}`.")
puts("# To see what's new, open https://github.com/fastlane/#{gem_name}/releases.") if FastlaneCore::Env.truthy?("FASTLANE_HIDE_CHANGELOG")
if !Helper.bundler? && !Helper.contained_fastlane? && Random.rand(5) == 1
# We want to show this message from time to time, if the user doesn't use bundler, nor bundled fastlane
puts('#######################################################################')
puts("# Run `gem cleanup` from time to time to speed up fastlane")
end
puts('#######################################################################')
Changelog.show_changes(gem_name, current_version, update_gem_command: UpdateChecker.update_command(gem_name: gem_name)) unless FastlaneCore::Env.truthy?("FASTLANE_HIDE_CHANGELOG")
ensure_rubygems_source
end
# The command that the user should use to update their mac
def self.update_command(gem_name: "fastlane")
if Helper.bundler?
"bundle update #{gem_name.downcase}"
elsif Helper.contained_fastlane? || Helper.homebrew?
"fastlane update_fastlane"
elsif Helper.mac_app?
"the Fabric app. Launch the app and navigate to the fastlane tab to get the most recent version."
else
"gem install #{gem_name.downcase}"
end
end
# Check if RubyGems is set as a gem source
# on some machines that might not be the case
# and then users can't find the update when
# running the specified command
def self.ensure_rubygems_source
return if Helper.contained_fastlane?
return if `gem sources`.include?("https://rubygems.org")
puts("")
UI.error("RubyGems is not listed as your Gem source")
UI.error("You can run `gem sources` to see all your sources")
UI.error("Please run the following command to fix this:")
UI.command("gem sources --add https://rubygems.org")
end
def self.fetch_latest(gem_name)
JSON.parse(Excon.get(generate_fetch_url(gem_name)).body)["version"]
end
def self.generate_fetch_url(gem_name)
"https://rubygems.org/api/v1/gems/#{gem_name}.json"
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane_core/lib/fastlane_core/update_checker/changelog.rb | fastlane_core/lib/fastlane_core/update_checker/changelog.rb | require 'excon'
module FastlaneCore
class Changelog
class << self
def show_changes(gem_name, current_version, update_gem_command: "bundle update")
did_show_changelog = false
self.releases(gem_name).each_with_index do |release, index|
next unless Gem::Version.new(release['tag_name']) > Gem::Version.new(current_version)
puts("")
puts(release['name'].green)
puts(release['body'])
did_show_changelog = true
next unless index == 2
puts("")
puts("To see all new releases, open https://github.com/fastlane/#{gem_name}/releases".green)
break
end
puts("")
puts("Please update using `#{update_gem_command}`".green) if did_show_changelog
rescue
# Something went wrong, we don't care so much about this
end
def releases(gem_name)
url = "https://api.github.com/repos/fastlane/#{gem_name}/releases"
# We have to follow redirects, since some repos were moved away into a separate org
server_response = Excon.get(url,
middlewares: Excon.defaults[:middlewares] + [Excon::Middleware::RedirectFollower])
JSON.parse(server_response.body)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/commands_generator_spec.rb | gym/spec/commands_generator_spec.rb | require 'gym/commands_generator'
describe Gym::CommandsGenerator do
def expect_manager_work_with(expected_options)
fake_manager = "manager"
expect(Gym::Manager).to receive(:new).and_return(fake_manager)
expect(fake_manager).to receive(:work) do |actual_options|
expect(expected_options._values).to eq(actual_options._values)
end
end
describe ":build option handling" do
it "can use the scheme short flag from tool options" do
# leaving out the command name defaults to 'build'
stub_commander_runner_args(['-s', 'MyScheme'])
expected_options = FastlaneCore::Configuration.create(Gym::Options.available_options, { scheme: 'MyScheme' })
expect_manager_work_with(expected_options)
Gym::CommandsGenerator.start
end
it "can use the clean flag from tool options" do
# leaving out the command name defaults to 'build'
stub_commander_runner_args(['--clean', 'true'])
expected_options = FastlaneCore::Configuration.create(Gym::Options.available_options, { clean: true })
expect_manager_work_with(expected_options)
Gym::CommandsGenerator.start
end
end
# :init is not tested here because it does not use any tool options.
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/error_handler_spec.rb | gym/spec/error_handler_spec.rb | describe Gym do
before(:all) do
options = { project: "./gym/examples/multipleSchemes/Example.xcodeproj" }
@config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
@project = FastlaneCore::Project.new(@config)
@output = %(
2015-12-15 13:00:57.177 xcodebuild[81544:4350404] [MT] IDEDistribution: -[IDEDistributionLogging _createLoggingBundleAtPath:]: Created bundle at path '/var/folders/88/l77k840955j0x55fkb3m6cdr0000gn/T/EventLink_2015-12-15_13-00-57.177.xcdistributionlogs'.
2015-12-15 13:00:57.318 xcodebuild[81544:4350404] [MT] IDEDistribution: Failed to generate distribution items with error: Error Domain=DVTMachOErrorDomain Code=0 "Found an unexpected Mach-O header code: 0x72613c21" UserInfo={NSLocalizedDescription=Found an unexpected Mach-O header code: 0x72613c21, NSLocalizedRecoverySuggestion=}
2015-12-15 13:00:57.318 xcodebuild[81544:4350404] [MT] IDEDistribution: Step failed: <IDEDistributionSigningAssetsStep: 0x7f9d94cb55a0>: Error Domain=DVTMachOErrorDomain Code=0 "Found an unexpected Mach-O header code: 0x72613c21" UserInfo={NSLocalizedDescription=Found an unexpected Mach-O header code: 0x72613c21, NSLocalizedRecoverySuggestion=}
%)
end
describe Gym::ErrorHandler, requires_xcodebuild: true do
before(:each) { Gym.config = @config }
def mock_gym_path(content)
log_path = "log_path"
expect(File).to receive(:exist?).with(log_path).and_return(true)
allow(Gym::BuildCommandGenerator).to receive(:xcodebuild_log_path).and_return(log_path)
expect(File).to receive(:read).with(log_path).and_return(content)
end
it "raises build error with error_info" do
mock_gym_path(@output)
expect(UI).to receive(:build_failure!).with("Error building the application - see the log above", error_info: @output)
Gym::ErrorHandler.handle_build_error(@output)
end
it "raises package error with error_info" do
mock_gym_path(@output)
expect(UI).to receive(:build_failure!).with("Error packaging up the application", error_info: @output)
Gym::ErrorHandler.handle_package_error(@output)
end
it "prints the last few lines of the raw output, as `xcpretty` doesn't render all error messages correctly" do
code_signing_output = @output + %(
SetMode u+w,go-w,a+rX /Users/fkrause/Library/Developer/Xcode/DerivedData/Themoji-aanbocksacwzrydzjzjvnfrcqibb/Build/Intermediates.noindex/ArchiveIntermediates/Themoji/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Pods_Themoji.framework
cd /Users/fkrause/Developer/hacking/themoji/Pods
/bin/chmod -RH u+w,go-w,a+rX /Users/fkrause/Library/Developer/Xcode/DerivedData/Themoji-aanbocksacwzrydzjzjvnfrcqibb/Build/Intermediates.noindex/ArchiveIntermediates/Themoji/IntermediateBuildFilesPath/UninstalledProducts/iphoneos/Pods_Themoji.framework
=== BUILD TARGET Themoji OF PROJECT Themoji WITH CONFIGURATION Release ===
Check dependencies
No profile for team 'N8X438SEU2' matching 'match AppStore me.themoji.app.beta' found: Xcode couldn't find any provisioning profiles matching 'N8X438SEU2/match AppStore me.themoji.app.beta'. Install the profile (by dragging and dropping it onto Xcode's dock item) or select a different one in the General tab of the target editor.
Code signing is required for product type 'Application' in SDK 'iOS 11.0'
)
mock_gym_path(code_signing_output)
expect(UI).to receive(:build_failure!).with("Error building the application - see the log above", error_info: code_signing_output)
expect(UI).to receive(:command_output).with("No profile for team 'N8X438SEU2' matching 'match AppStore me.themoji.app.beta' found: Xcode couldn't find any provisioning profiles matching 'N8X438SEU2/match AppStore me.themoji.app.beta'. " \
"Install the profile (by dragging and dropping it onto Xcode's dock item) or select a different one in the General tab of the target editor.")
expect(UI).to receive(:command_output).with("Code signing is required for product type 'Application' in SDK 'iOS 11.0'")
expect(UI).to receive(:command_output).at_least(:once) # as this is called multiple times before
Gym::ErrorHandler.handle_build_error(code_signing_output)
end
it "prints mismatch between the export_method and the selected profiles only once" do
mock_gym_path(@output)
expect(UI).to receive(:build_failure!).with("Error building the application - see the log above", error_info: @output)
Gym.config[:export_method] = 'app-store'
Gym.config[:export_options][:provisioningProfiles] = {
'com.sample.app' => 'In House Ad Hoc'
}
expect(UI).to receive(:error).with(/There seems to be a mismatch between/).once
allow(UI).to receive(:error)
Gym::ErrorHandler.handle_build_error(@output)
end
it "does not print mismatch if the export_method and the selected profiles matched" do
mock_gym_path(@output)
expect(UI).to receive(:build_failure!).with("Error building the application - see the log above", error_info: @output)
Gym.config[:export_method] = 'enterprise'
Gym.config[:export_options][:provisioningProfiles] = {
'com.sample.app' => 'In House Ad Hoc' # `enterprise` take precedence over `ad-hoc`
}
expect(UI).to receive(:error).with(/There seems to be a mismatch between/).never
allow(UI).to receive(:error)
Gym::ErrorHandler.handle_build_error(@output)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/code_signing_mapping_spec.rb | gym/spec/code_signing_mapping_spec.rb | describe Gym::CodeSigningMapping, requires_xcodebuild: true do
describe "#app_identifier_contains?" do
it "returns false if it doesn't contain it" do
csm = Gym::CodeSigningMapping.new(project: nil)
return_value = csm.app_identifier_contains?("dsfsdsdf", "somethingelse")
expect(return_value).to eq(false)
end
it "returns true if it doesn't contain it" do
csm = Gym::CodeSigningMapping.new(project: nil)
return_value = csm.app_identifier_contains?("FuLL-StRing Yo", "fullstringyo")
expect(return_value).to eq(true)
end
it "Strips out all the usual characters that are not needed" do
csm = Gym::CodeSigningMapping.new(project: nil)
return_value = csm.app_identifier_contains?("Ad-HocValue", "ad-hoc")
expect(return_value).to eq(true)
end
it "Replace the inhouse keyword for enterprise profiles" do
csm = Gym::CodeSigningMapping.new(project: nil)
return_value = csm.app_identifier_contains?("match InHouse bundle", "enterprise")
expect(return_value).to eq(true)
end
end
describe "#detect_project_profile_mapping" do
it "returns the mapping of the selected provisioning profiles", requires_xcode: true do
workspace_path = "gym/spec/fixtures/projects/cocoapods/Example.xcworkspace"
options = { workspace: workspace_path, scheme: "Example" }
project = FastlaneCore::Project.new(options)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
csm = Gym::CodeSigningMapping.new(project: project)
expect(csm.detect_project_profile_mapping).to eq({ "family.wwdc.app" => "match AppStore family.wwdc.app", "family.wwdc.app.watchkitapp" => "match AppStore family.wwdc.app.watchkitapp", "family.wwdc.app.watchkitapp.watchkitextension" => "match AppStore family.wwdc.app.watchkitappextension" })
end
it "detects the build configuration from selected scheme", requires_xcode: true do
workspace_path = "gym/spec/fixtures/projects/cocoapods/Example.xcworkspace"
options = { workspace: workspace_path, scheme: "Example (Debug)" }
project = FastlaneCore::Project.new(options)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
csm = Gym::CodeSigningMapping.new(project: project)
expect(csm.detect_project_profile_mapping).to eq({ "family.wwdc.app" => "match Development family.wwdc.app", "family.wwdc.app.watchkitapp" => "match Development family.wwdc.app.watchkitapp", "family.wwdc.app.watchkitapp.watchkitextension" => "match Development family.wwdc.app.watchkitappextension" })
end
it "detects the build configuration from selected scheme of a project based on inheritance for resolve xcconfigs", requires_xcode: true do
workspace_path = "gym/spec/fixtures/projects/projectBasedOnInheritance/ExampleWithInheritedXcconfig.xcworkspace"
options = { workspace: workspace_path, scheme: "Target A" }
project = FastlaneCore::Project.new(options)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
csm = Gym::CodeSigningMapping.new(project: project)
expect(csm.detect_project_profile_mapping).to eq({ "com.targeta.release" => "release-targeta", "com.targetb.release" => "release-targetb" })
end
end
describe "#detect_project_profile_mapping_for_tv_os" do
it "returns the mapping of the selected provisioning profiles for tv_os", requires_xcode: true do
workspace_path = "gym/spec/fixtures/projects/cocoapods/Example.xcworkspace"
options = { workspace: workspace_path, scheme: "ExampletvOS", destination: "generic/platform=tvOS" }
project = FastlaneCore::Project.new(options)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
csm = Gym::CodeSigningMapping.new(project: project)
expect(csm.detect_project_profile_mapping).to eq({ "family.wwdc.app" => "match AppStore family.wwdc.app.tvos" })
end
end
describe "#merge_profile_mapping" do
let(:csm) { Gym::CodeSigningMapping.new }
it "only mapping from Xcode Project is available" do
result = csm.merge_profile_mapping(primary_mapping: {},
secondary_mapping: { "identifier.1" => "value.1" },
export_method: "app-store")
expect(result).to eq({ "identifier.1": "value.1" })
end
it "only mapping from match (user) is available" do
result = csm.merge_profile_mapping(primary_mapping: { "identifier.1" => "value.1" },
secondary_mapping: {},
export_method: "app-store")
expect(result).to eq({ "identifier.1": "value.1" })
end
it "keeps both profiles if they don't conflict" do
result = csm.merge_profile_mapping(primary_mapping: { "identifier.1" => "value.1" },
secondary_mapping: { "identifier.2" => "value.2" },
export_method: "app-store")
expect(result).to eq({ "identifier.1": "value.1", "identifier.2": "value.2" })
end
it "doesn't crash if nil is provided" do
result = csm.merge_profile_mapping(primary_mapping: nil,
secondary_mapping: {},
export_method: "app-store")
expect(result).to eq({})
end
it "accesses the Xcode profile mapping, if nothing else is given" do
expect(csm).to receive(:detect_project_profile_mapping).and_return({ "identifier.1" => "value.1" })
result = csm.merge_profile_mapping(primary_mapping: {}, export_method: "app-store")
expect(result).to eq({ "identifier.1": "value.1" })
end
context "Both primary and secondary are available" do
context "Both match the export method" do
it "should prefer the primary mapping" do
result = csm.merge_profile_mapping(primary_mapping: { "identifier.1" => "Ap-pStoreValue2" },
secondary_mapping: { "identifier.1" => "Ap-pStoreValue1" },
export_method: "app-store")
expect(result).to eq({ "identifier.1": "Ap-pStoreValue2" })
end
end
context "The primary is the only one that matches the export type" do
it "should prefer the primary mapping" do
result = csm.merge_profile_mapping(primary_mapping: { "identifier.1" => "Ap-p StoreValue1" },
secondary_mapping: { "identifier.1" => "Ad-HocValue" },
export_method: "app-store")
expect(result).to eq({ "identifier.1": "Ap-p StoreValue1" })
end
end
context "The secondary is the only one that matches the export type" do
it "should prefer the secondary mapping" do
result = csm.merge_profile_mapping(primary_mapping: { "identifier.1" => "Ap-p StoreValue1" },
secondary_mapping: { "identifier.1" => "Ad-HocValue" },
export_method: "ad-hoc")
expect(result).to eq({ "identifier.1": "Ad-HocValue" })
end
end
context "Neither of them match the export type" do
it "should choose the secondary_mapping" do
result = csm.merge_profile_mapping(primary_mapping: { "identifier.1" => "AppStore" },
secondary_mapping: { "identifier.1" => "Adhoc" },
export_method: "development")
expect(result).to eq({ "identifier.1": "Adhoc" })
end
end
context "Both have the same value" do
let(:result) do
csm.merge_profile_mapping(primary_mapping: { primary_key => "AppStore" },
secondary_mapping: { secondary_key => "AppStore" },
export_method: "development")
end
context "when primary's key is symbol and secondary's key is also symbol" do
let(:primary_key) { :"identifier.1" }
let(:secondary_key) { :"identifier.1" }
it "is merged correctly" do
expect(result).to eq({ "identifier.1": "AppStore" })
end
end
context "when primary's key is symbol and secondary's key is string" do
let(:primary_key) { :"identifier.1" }
let(:secondary_key) { "identifier.1" }
it "is merged correctly" do
expect(result).to eq({ "identifier.1": "AppStore" })
end
end
context "when primary's key is string and secondary's key is also string" do
let(:primary_key) { "identifier.1" }
let(:secondary_key) { "identifier.1" }
it "is merged correctly" do
expect(result).to eq({ "identifier.1": "AppStore" })
end
end
context "when primary's key is string and secondary's key is also symbol" do
let(:primary_key) { "identifier.1" }
let(:secondary_key) { :"identifier.1" }
it "is merged correctly" do
expect(result).to eq({ "identifier.1": "AppStore" })
end
end
end
end
end
describe "#test_target?" do
let(:csm) { Gym::CodeSigningMapping.new(project: nil) }
context "when build_setting include TEST_TARGET_NAME" do
it "is test target" do
build_settings = { "TEST_TARGET_NAME" => "Sample" }
expect(csm.test_target?(build_settings)).to be(true)
end
end
context "when build_setting include TEST_HOST" do
it "is test target" do
build_settings = { "TEST_HOST" => "Sample" }
expect(csm.test_target?(build_settings)).to be(true)
end
end
context "when build_setting include neither TEST_HOST nor TEST_TARGET_NAME" do
it "is not test target" do
build_settings = {}
expect(csm.test_target?(build_settings)).to be(false)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/build_command_generator_spec.rb | gym/spec/build_command_generator_spec.rb | describe Gym do
before(:all) do
options = { project: "./gym/examples/standard/Example.xcodeproj" }
config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
@project = FastlaneCore::Project.new(config)
end
before(:each) do
@project.options.delete(:use_system_scm)
allow(Gym).to receive(:project).and_return(@project)
end
describe Gym::BuildCommandGenerator do
before(:each) do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false)
# Gym::Options.available_options caches options after first load and we don't want that for tests
allow(Gym::Options).to receive(:available_options).and_return(Gym::Options.plain_options)
end
it "raises an exception when project path wasn't found" do
tmp_path = Dir.mktmpdir
path = "#{tmp_path}/notExistent"
expect do
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, { project: path })
end.to raise_error("Project file not found at path '#{path}'")
end
it "supports additional parameters", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
xcargs = { DEBUG: "1", BUNDLE_NAME: "Example App" }
options = { project: "./gym/examples/standard/Example.xcodeproj", sdk: "9.0", toolchain: "com.apple.dt.toolchain.Swift_2_3", xcargs: xcargs, scheme: 'Example' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-sdk '9.0'",
"-toolchain 'com.apple.dt.toolchain.Swift_2_3'",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"DEBUG=1 BUNDLE_NAME=Example\\ App",
:archive,
"| tee #{log_path.shellescape}",
"| xcpretty"
])
end
it "disables xcpretty formatting", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
xcargs = { DEBUG: "1", BUNDLE_NAME: "Example App" }
options = { project: "./gym/examples/standard/Example.xcodeproj", sdk: "9.0", xcargs: xcargs, scheme: 'Example', disable_xcpretty: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-sdk '9.0'",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"DEBUG=1 BUNDLE_NAME=Example\\ App",
:archive,
"| tee #{log_path.shellescape}"
])
end
it "enables unicode", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
xcargs = { DEBUG: "1", BUNDLE_NAME: "Example App" }
options = { project: "./gym/examples/standard/Example.xcodeproj", sdk: "9.0", xcargs: xcargs, scheme: 'Example', xcpretty_utf: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-sdk '9.0'",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"DEBUG=1 BUNDLE_NAME=Example\\ App",
:archive,
"| tee #{log_path.shellescape}",
"| xcpretty",
"--utf"
])
end
it "#xcodebuild_command option is used if provided", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
options = { xcodebuild_command: "arch -arm64 xcodebuild", project: "./gym/examples/standard/Example.xcodeproj", scheme: 'Example' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"arch -arm64 xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
:archive,
"| tee #{log_path.shellescape}",
"| xcpretty"
])
end
it "uses system scm", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", use_system_scm: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to include("-scmProvider system").once
end
it "uses system scm via project options", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj" }
@project.options[:use_system_scm] = true
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to include("-scmProvider system").once
end
it "uses system scm options exactly once", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", use_system_scm: true }
@project.options[:use_system_scm] = true
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to include("-scmProvider system").once
end
it "defaults to Xcode scm when option is not provided", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to_not(include("-scmProvider system"))
end
it "adds -showBuildTimingSummary flag when option is set", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", build_timing_summary: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to include("-showBuildTimingSummary")
end
it "the -showBuildTimingSummary is not added by default", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to_not(include("-showBuildTimingSummary"))
end
it "uses the correct build command when `skip_archive` is used", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
options = { project: "./gym/examples/standard/Example.xcodeproj", scheme: 'Example', skip_archive: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-destination 'generic/platform=iOS'",
:build,
"| tee #{log_path.shellescape}",
"| xcpretty"
])
end
describe "Standard Example" do
before do
options = { project: "./gym/examples/standard/Example.xcodeproj", scheme: 'Example' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
end
it "uses the correct build command with the example project with no additional parameters", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
:archive,
"| tee #{log_path.shellescape}",
"| xcpretty"
])
end
it "#project_path_array", requires_xcodebuild: true do
result = Gym::BuildCommandGenerator.project_path_array
expect(result).to eq(["-scheme Example", "-project ./gym/examples/standard/Example.xcodeproj"])
end
it "default #build_path", requires_xcodebuild: true do
result = Gym::BuildCommandGenerator.build_path
regex = %r{Library/Developer/Xcode/Archives/\d\d\d\d\-\d\d\-\d\d}
expect(result).to match(regex)
end
it "user provided #build_path", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", build_path: "/tmp/my/build_path", scheme: 'Example' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.build_path
expect(result).to eq("/tmp/my/build_path")
end
it "#archive_path", requires_xcodebuild: true do
result = Gym::BuildCommandGenerator.archive_path
regex = %r{Library/Developer/Xcode/Archives/\d\d\d\d\-\d\d\-\d\d/ExampleProductName \d\d\d\d\-\d\d\-\d\d \d\d\.\d\d\.\d\d.xcarchive}
expect(result).to match(regex)
end
it "#buildlog_path is used when provided", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", buildlog_path: "/tmp/my/path", scheme: 'Example' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.xcodebuild_log_path
expect(result).to include("/tmp/my/path")
end
it "#buildlog_path is not used when not provided", requires_xcodebuild: true do
result = Gym::BuildCommandGenerator.xcodebuild_log_path
expect(result.to_s).to include(File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym"))
end
end
describe "Derived Data Example" do
before(:each) do
options = { project: "./gym/examples/standard/Example.xcodeproj", derived_data_path: "/tmp/my/derived_data", scheme: 'Example' }
config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
@project = FastlaneCore::Project.new(config)
allow(Gym).to receive(:project).and_return(@project)
end
it "uses the correct build command with the example project", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-derivedDataPath /tmp/my/derived_data",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
:archive,
"| tee #{log_path.shellescape}",
"| xcpretty"
])
end
end
describe "Result Bundle Example" do
it "uses the correct build command with the example project", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
options = { project: "./gym/examples/standard/Example.xcodeproj", result_bundle: true, scheme: 'Example' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"-resultBundlePath './ExampleProductName.xcresult'",
:archive,
"| tee #{log_path.shellescape}",
"| xcpretty"
])
end
end
describe "Result Bundle Path Example" do
it "uses the correct build command with the example project", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
options = { project: "./gym/examples/standard/Example.xcodeproj", scheme: 'Example', result_bundle: true,
result_bundle_path: "result_bundle" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"-resultBundlePath 'result_bundle'",
:archive,
"| tee #{log_path.shellescape}",
"| xcpretty"
])
end
it "does not use result_bundle_path if result_bundle is false", requires_xcodebuild: true do
log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
options = { project: "./gym/examples/standard/Example.xcodeproj", scheme: 'Example', result_bundle: false,
result_bundle_path: "result_bundle" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
:archive,
"| tee #{log_path.shellescape}",
"| xcpretty"
])
end
end
describe "Analyze Build Time Example" do
before do
@log_path = File.expand_path("#{FastlaneCore::Helper.buildlog_path}/gym/ExampleProductName-Example.log")
end
it "uses the correct build command with the example project when option is enabled", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", analyze_build_time: true, scheme: 'Example' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"OTHER_SWIFT_FLAGS=\"\\$(value) -Xfrontend -debug-time-function-bodies\"",
:archive,
"| tee #{@log_path.shellescape}",
"| xcpretty"
])
result = Gym::BuildCommandGenerator.post_build
expect(result).to eq([
"grep -E '^[0-9.]+ms' #{@log_path.shellescape} | grep -vE '^0\.[0-9]' | sort -nr > culprits.txt"
])
end
it "uses the correct build command with the example project when option is disabled", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", analyze_build_time: false, scheme: 'Example' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::BuildCommandGenerator.generate
expect(result).to eq([
"set -o pipefail &&",
"xcodebuild",
"-scheme Example",
"-project ./gym/examples/standard/Example.xcodeproj",
"-destination 'generic/platform=iOS'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
:archive,
"| tee #{@log_path.shellescape}",
"| xcpretty"
])
result = Gym::BuildCommandGenerator.post_build
expect(result).to be_empty
end
end
end
context "with any formatter" do
describe "#pipe" do
it "uses no pipe with disable_xcpretty", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false)
allow(Gym::Options).to receive(:available_options).and_return(Gym::Options.plain_options)
options = { project: "./gym/examples/standard/Example.xcodeproj", disable_xcpretty: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
pipe = Gym::BuildCommandGenerator.pipe
expect(pipe.join(" ")).not_to include("| xcpretty")
expect(pipe.join(" ")).not_to include("| xcbeautify")
end
it "uses no pipe with xcodebuild_formatter of empty string", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false)
allow(Gym::Options).to receive(:available_options).and_return(Gym::Options.plain_options)
options = { project: "./gym/examples/standard/Example.xcodeproj", xcodebuild_formatter: '' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
pipe = Gym::BuildCommandGenerator.pipe
expect(pipe.join(" ")).not_to include("| xcpretty")
expect(pipe.join(" ")).not_to include("| xcbeautify")
end
describe "with xcodebuild_formatter" do
describe "with no xcpretty options" do
it "default when xcbeautify not installed", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false)
allow(Gym::Options).to receive(:available_options).and_return(Gym::Options.plain_options)
options = { project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
pipe = Gym::BuildCommandGenerator.pipe
expect(pipe.join(" ")).to include("| xcpretty")
end
it "default when xcbeautify installed", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(true)
allow(Gym::Options).to receive(:available_options).and_return(Gym::Options.plain_options)
options = { project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
pipe = Gym::BuildCommandGenerator.pipe
expect(pipe.join(" ")).to include("| xcbeautify")
end
it "xcpretty override when xcbeautify installed", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(true)
allow(Gym::Options).to receive(:available_options).and_return(Gym::Options.plain_options)
options = { project: "./gym/examples/standard/Example.xcodeproj", xcodebuild_formatter: 'xcpretty' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
pipe = Gym::BuildCommandGenerator.pipe
expect(pipe.join(" ")).to include("| xcpretty")
end
it "customer formatter", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false)
allow(Gym::Options).to receive(:available_options).and_return(Gym::Options.plain_options)
options = { project: "./gym/examples/standard/Example.xcodeproj", xcodebuild_formatter: '/path/to/xcbeautify' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
pipe = Gym::BuildCommandGenerator.pipe
expect(pipe.join(" ")).to include("| /path/to/xcbeautify")
end
end
it "with xcpretty options when xcbeautify installed", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(true)
allow(Gym::Options).to receive(:available_options).and_return(Gym::Options.plain_options)
options = { project: "./gym/examples/standard/Example.xcodeproj", xcpretty_test_format: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
pipe = Gym::BuildCommandGenerator.pipe
expect(pipe.join(" ")).to include("| xcpretty")
end
end
end
describe "#legacy_xcpretty_options" do
it "with xcpretty_test_format", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", xcpretty_test_format: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
options = Gym::BuildCommandGenerator.legacy_xcpretty_options
expect(options).to eq(['xcpretty_test_format'])
end
it "with xcpretty_formatter", requires_xcodebuild: true do
allow(File).to receive(:exist?).and_call_original
expect(File).to receive(:exist?).with("thing.rb").and_return(true)
options = { project: "./gym/examples/standard/Example.xcodeproj", xcpretty_formatter: "thing.rb" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
options = Gym::BuildCommandGenerator.legacy_xcpretty_options
expect(options).to eq(['xcpretty_formatter'])
end
it "with xcpretty_report_junit", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", xcpretty_report_junit: "thing.junit" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
options = Gym::BuildCommandGenerator.legacy_xcpretty_options
expect(options).to eq(['xcpretty_report_junit'])
end
it "with xcpretty_report_html", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", xcpretty_report_html: "thing.html" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
options = Gym::BuildCommandGenerator.legacy_xcpretty_options
expect(options).to eq(['xcpretty_report_html'])
end
it "with xcpretty_report_json", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", xcpretty_report_json: "thing.json" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
options = Gym::BuildCommandGenerator.legacy_xcpretty_options
expect(options).to eq(['xcpretty_report_json'])
end
it "with xcpretty_utf", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", xcpretty_utf: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
options = Gym::BuildCommandGenerator.legacy_xcpretty_options
expect(options).to eq(['xcpretty_utf'])
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/gymfile_spec.rb | gym/spec/gymfile_spec.rb | describe Gym do
before(:all) do
options = { project: "./gym/examples/multipleSchemes/Example.xcodeproj" }
@config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
@project = FastlaneCore::Project.new(@config)
end
describe "Project with multiple Schemes and Gymfile", requires_xcodebuild: true do
before(:each) { Gym.config = @config }
it "#schemes returns all available schemes" do
expect(@project.schemes).to contain_exactly("Example", "ExampleTests")
end
it "executing `gym` will not ask for the scheme" do
expect(Gym.config[:scheme]).to eq("Example")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/package_command_generator_xcode7_spec.rb | gym/spec/package_command_generator_xcode7_spec.rb | describe Gym do
before(:all) do
options = { project: "./gym/examples/standard/Example.xcodeproj" }
config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
@project = FastlaneCore::Project.new(config)
end
before(:each) do
allow(Gym).to receive(:project).and_return(@project)
end
describe Gym::PackageCommandGeneratorXcode7, requires_xcodebuild: true do
it "passes xcargs through to xcode build wrapper " do
options = {
project: "./gym/examples/standard/Example.xcodeproj",
xcargs: "-allowProvisioningUpdates"
}
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
expect(result).to eq([
"/usr/bin/xcrun #{Gym::PackageCommandGeneratorXcode7.wrap_xcodebuild.shellescape} -exportArchive",
"-exportOptionsPlist '#{Gym::PackageCommandGeneratorXcode7.config_path}'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"-exportPath '#{Gym::PackageCommandGeneratorXcode7.temporary_output_path}'",
"-allowProvisioningUpdates",
""
])
end
it "works with the example project with no additional parameters" do
options = { project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
expect(result).to eq([
"/usr/bin/xcrun #{Gym::PackageCommandGeneratorXcode7.wrap_xcodebuild.shellescape} -exportArchive",
"-exportOptionsPlist '#{Gym::PackageCommandGeneratorXcode7.config_path}'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"-exportPath '#{Gym::PackageCommandGeneratorXcode7.temporary_output_path}'",
""
])
end
it "works with the example project and additional parameters" do
xcargs = { DEBUG: "1", BUNDLE_NAME: "Example App" }
options = { project: "./gym/examples/standard/Example.xcodeproj", export_xcargs: xcargs }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
expect(result).to eq([
"/usr/bin/xcrun #{Gym::PackageCommandGeneratorXcode7.wrap_xcodebuild.shellescape} -exportArchive",
"-exportOptionsPlist '#{Gym::PackageCommandGeneratorXcode7.config_path}'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"-exportPath '#{Gym::PackageCommandGeneratorXcode7.temporary_output_path}'",
"DEBUG=1 BUNDLE_NAME=Example\\ App",
""
])
end
it "works with spaces in path name" do
options = { project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
allow(Gym::PackageCommandGeneratorXcode7).to receive(:wrap_xcodebuild).and_return("/tmp/path with spaces")
result = Gym::PackageCommandGeneratorXcode7.generate
expect(result).to eq([
"/usr/bin/xcrun /tmp/path\\ with\\ spaces -exportArchive",
"-exportOptionsPlist '#{Gym::PackageCommandGeneratorXcode7.config_path}'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"-exportPath '#{Gym::PackageCommandGeneratorXcode7.temporary_output_path}'",
""
])
end
it "supports passing a toolchain to use" do
options = {
project: "./gym/examples/standard/Example.xcodeproj",
toolchain: "com.apple.dt.toolchain.Swift_2_3"
}
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
expect(result).to eq([
"/usr/bin/xcrun #{Gym::PackageCommandGeneratorXcode7.wrap_xcodebuild.shellescape} -exportArchive",
"-exportOptionsPlist '#{Gym::PackageCommandGeneratorXcode7.config_path}'",
"-archivePath #{Gym::BuildCommandGenerator.archive_path.shellescape}",
"-exportPath '#{Gym::PackageCommandGeneratorXcode7.temporary_output_path}'",
"-toolchain '#{options[:toolchain]}'",
""
])
end
it "generates a valid plist file we need" do
options = { project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
config_path = Gym::PackageCommandGeneratorXcode7.config_path
expect(Plist.parse_xml(config_path)).to eq({
'method' => "app-store"
})
end
it "reads user export plist" do
options = { project: "./gym/examples/standard/Example.xcodeproj", export_options: "./gym/examples/standard/ExampleExport.plist" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
config_path = Gym::PackageCommandGeneratorXcode7.config_path
expect(Plist.parse_xml(config_path)).to eq({
'embedOnDemandResourcesAssetPacksInBundle' => true,
'manifest' => {
'appURL' => 'https://www.example.com/Example.ipa',
'displayImageURL' => 'https://www.example.com/display.png',
'fullSizeImageURL' => 'https://www.example.com/fullSize.png'
},
'method' => 'ad-hoc'
})
expect(Gym.config[:export_method]).to eq("ad-hoc")
expect(Gym.config[:include_symbols]).to be_nil
expect(Gym.config[:include_bitcode]).to be_nil
expect(Gym.config[:export_team_id]).to be_nil
end
it "defaults to the correct export type if :export_options parameter is provided" do
options = {
project: "./gym/examples/standard/Example.xcodeproj",
export_options: {
include_symbols: true
}
}
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
config_path = Gym::PackageCommandGeneratorXcode7.config_path
content = Plist.parse_xml(config_path)
expect(content["include_symbols"]).to eq(true)
expect(content["method"]).to eq('app-store')
end
it "reads user export plist and override some parameters" do
options = {
project: "./gym/examples/standard/Example.xcodeproj",
export_options: "./gym/examples/standard/ExampleExport.plist",
export_method: "app-store",
include_symbols: false,
include_bitcode: true,
export_team_id: "1234567890"
}
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
config_path = Gym::PackageCommandGeneratorXcode7.config_path
expect(Plist.parse_xml(config_path)).to eq({
'embedOnDemandResourcesAssetPacksInBundle' => true,
'manifest' => {
'appURL' => 'https://www.example.com/Example.ipa',
'displayImageURL' => 'https://www.example.com/display.png',
'fullSizeImageURL' => 'https://www.example.com/fullSize.png'
},
'method' => 'app-store',
'uploadSymbols' => false,
'uploadBitcode' => true,
'teamID' => '1234567890'
})
end
it "reads export options from hash" do
options = {
project: "./gym/examples/standard/Example.xcodeproj",
export_options: {
embedOnDemandResourcesAssetPacksInBundle: false,
manifest: {
appURL: "https://example.com/My App.ipa",
displayImageURL: "https://www.example.com/display image.png",
fullSizeImageURL: "https://www.example.com/fullSize image.png"
},
method: "enterprise",
uploadSymbols: false,
uploadBitcode: true,
teamID: "1234567890"
},
export_method: "app-store",
include_symbols: true,
include_bitcode: false,
export_team_id: "ASDFGHJK"
}
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
config_path = Gym::PackageCommandGeneratorXcode7.config_path
expect(Plist.parse_xml(config_path)).to eq({
'embedOnDemandResourcesAssetPacksInBundle' => false,
'manifest' => {
'appURL' => 'https://example.com/My%20App.ipa',
'displayImageURL' => 'https://www.example.com/display%20image.png',
'fullSizeImageURL' => 'https://www.example.com/fullSize%20image.png'
},
'method' => 'app-store',
'uploadSymbols' => true,
'uploadBitcode' => false,
'teamID' => 'ASDFGHJK'
})
end
it "doesn't store bitcode/symbols information for non app-store builds" do
options = { project: "./gym/examples/standard/Example.xcodeproj", export_method: 'ad-hoc' }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
config_path = Gym::PackageCommandGeneratorXcode7.config_path
expect(Plist.parse_xml(config_path)).to eq({
'method' => "ad-hoc"
})
end
it "uses a temporary folder to store the resulting ipa file" do
options = { project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
result = Gym::PackageCommandGeneratorXcode7.generate
expect(Gym::PackageCommandGeneratorXcode7.temporary_output_path).to match(%r{#{Dir.tmpdir}/gym_output.+})
expect(Gym::PackageCommandGeneratorXcode7.manifest_path).to match(%r{#{Dir.tmpdir}/gym_output.+/manifest.plist})
expect(Gym::PackageCommandGeneratorXcode7.app_thinning_path).to match(%r{#{Dir.tmpdir}/gym_output.+/app-thinning.plist})
expect(Gym::PackageCommandGeneratorXcode7.app_thinning_size_report_path).to match(%r{#{Dir.tmpdir}/gym_output.+/App Thinning Size Report.txt})
expect(Gym::PackageCommandGeneratorXcode7.apps_path).to match(%r{#{Dir.tmpdir}/gym_output.+/Apps})
expect(Gym::PackageCommandGeneratorXcode7.appstore_info_path).to match(%r{#{Dir.tmpdir}/gym_output.+/AppStoreInfo.plist})
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/detect_values_spec.rb | gym/spec/detect_values_spec.rb | describe Gym do
describe Gym::DetectValues do
describe 'Xcode config handling', :stuff, requires_xcodebuild: true do
now = Time.now
day = now.strftime("%F")
before do
# These tests can take some time to run
# Mocking Time.now to ensure test pass when running between two days
expect(Time).to receive(:now).and_return(now).once
end
it "fetches the custom build path from the Xcode config" do
expect(Gym::DetectValues).to receive(:has_xcode_preferences_plist?).and_return(true)
expect(Gym::DetectValues).to receive(:xcode_preferences_dictionary).and_return({ "IDECustomDistributionArchivesLocation" => "/test/path" })
options = { project: "./gym/examples/multipleSchemes/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
path = Gym.config[:build_path]
expect(path).to eq("/test/path/#{day}")
end
it "fetches the default build path from the Xcode config when preference files exists but not archive location defined" do
expect(Gym::DetectValues).to receive(:has_xcode_preferences_plist?).and_return(true)
expect(Gym::DetectValues).to receive(:xcode_preferences_dictionary).and_return({})
options = { project: "./gym/examples/multipleSchemes/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
archive_path = File.expand_path("~/Library/Developer/Xcode/Archives/#{day}")
path = Gym.config[:build_path]
expect(path).to eq(archive_path)
end
it "fetches the default build path from the Xcode config when missing Xcode preferences plist" do
expect(Gym::DetectValues).to receive(:has_xcode_preferences_plist?).and_return(false)
options = { project: "./gym/examples/multipleSchemes/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
archive_path = File.expand_path("~/Library/Developer/Xcode/Archives/#{day}")
path = Gym.config[:build_path]
expect(path).to eq(archive_path)
end
end
describe '#detect_third_party_installer', :stuff, requires_xcodebuild: true do
let(:team_name) { "Some Team Name" }
let(:team_id) { "123456789" }
let(:installer_cert_123456789) do
output = <<-eos
keychain: "/Users/josh/Library/Keychains/login.keychain-db"
version: 512
class: 0x80001000
attributes:
"alis"<blob>="3rd Party Mac Developer Installer: Some Team Name (123456789)"
"cenc"<uint32>=0x00000003
"ctyp"<uint32>=0x00000001
"hpky"<blob>=0xC89D8821E5D9AF1B511D5D0391D0F2193D4BA034 "\310\235\210!\345\331\257\033Q\035]\003\221\320\362\031=K\2404"
"issu"<blob>=0x308196310B300906035504061302555331133011060355040A0C0A4170706C6520496E632E312C302A060355040B0C234170706C6520576F726C647769646520446576656C6F7065722052656C6174696F6E733144304206035504030C3B4170706C6520576F726C647769646520446576656C6F7065722052656C6174696F6E732043657274696669636174696F6E20417574686F72
697479 "0\201\2261\0130\011\006\003U\004\006\023\002US1\0230\021\006\003U\004\012\014\012Apple Inc.1,0*\006\003U\004\013\014#Apple Worldwide Developer Relations1D0B\006\003U\004\003\014;Apple Worldwide Developer Relations Certification Authority"
"labl"<blob>="3rd Party Mac Developer Installer: Some Team Name (123456789)"
"skid"<blob>=0xC89D8821E5D9AF1B511D5D0391D0F2193D4BA034 "\310\235\210!\345\331\257\033Q\035]\003\221\320\362\031=K\2404"
"snbr"<blob>=0x28FEC528B49F0DA9 "(\376\305(\264\237\015\251"
"subj"<blob>=0x308198311A3018060A0992268993F22C6401010C0A3937324B5333365032553143304106035504030C3A337264205061727479204D616320446576656C6F70657220496E7374616C6C65723A204A6F736820486F6C747A20283937324B5333365032552931133011060355040B0C0A3937324B53333650325531133011060355040A0C0A4A6F736820486F6C747A310B300906035504
0613025553 "0\201\2301\0320\030\006\012\011\222&\211\223\362,d\001\001\014\012972KS36P2U1C0A\006\003U\004\003\014:3rd Party Mac Developer Installer: Some Team Name (123456789)1\0230\021\006\003U\004\013\014\012123456789\0230\021\006\003U\004\012\014\012Some Team Name1\0130\011\006\003U\004\006\023\002US"
eos
output.force_encoding("BINARY")
end
let(:installer_cert_111222333) do
output = <<-eos
keychain: "/Users/josh/Library/Keychains/login.keychain-db"
version: 512
class: 0x80001000
attributes:
"alis"<blob>="3rd Party Mac Developer Installer: Not A Team Name (111222333)"
"cenc"<uint32>=0x00000003
"ctyp"<uint32>=0x00000001
"hpky"<blob>=0xC89D8821E5D9AF1B511D5D0391D0F2193D4BA034 "\310\235\210!\345\331\257\033Q\035]\003\221\320\362\031=K\2404"
"issu"<blob>=0x308196310B300906035504061302555331133011060355040A0C0A4170706C6520496E632E312C302A060355040B0C234170706C6520576F726C647769646520446576656C6F7065722052656C6174696F6E733144304206035504030C3B4170706C6520576F726C647769646520446576656C6F7065722052656C6174696F6E732043657274696669636174696F6E20417574686F72
697479 "0\201\2261\0130\011\006\003U\004\006\023\002US1\0230\021\006\003U\004\012\014\012Apple Inc.1,0*\006\003U\004\013\014#Apple Worldwide Developer Relations1D0B\006\003U\004\003\014;Apple Worldwide Developer Relations Certification Authority"
"labl"<blob>="3rd Party Mac Developer Installer: Not A Team Name (111222333)"
"skid"<blob>=0xC89D8821E5D9AF1B511D5D0391D0F2193D4BA034 "\310\235\210!\345\331\257\033Q\035]\003\221\320\362\031=K\2404"
"snbr"<blob>=0x28FEC528B49F0DA9 "(\376\305(\264\237\015\251"
"subj"<blob>=0x308198311A3018060A0992268993F22C6401010C0A3937324B5333365032553143304106035504030C3A337264205061727479204D616320446576656C6F70657220496E7374616C6C65723A204A6F736820486F6C747A20283937324B5333365032552931133011060355040B0C0A3937324B53333650325531133011060355040A0C0A4A6F736820486F6C747A310B300906035504
0613025553 "0\201\2301\0320\030\006\012\011\222&\211\223\362,d\001\001\014\012972KS36P2U1C0A\006\003U\004\003\014:3rd Party Mac Developer Installer: Not A Team Name (111222333)1\0230\021\006\003U\004\013\014\012111222333\0230\021\006\003U\004\012\014\012Not A Team Name1\0130\011\006\003U\004\006\023\002US"
eos
output.force_encoding("BINARY")
end
let(:output_2_matching_1_nonmatching) do
[
installer_cert_111222333,
installer_cert_123456789,
installer_cert_123456789
].join("\n")
end
let(:output_1_nonmatching) do
[
installer_cert_111222333
].join("\n")
end
let(:output_none) do
""
end
it "no team id found" do
allow_any_instance_of(FastlaneCore::Project).to receive(:build_settings).with(anything).and_call_original
allow_any_instance_of(FastlaneCore::Project).to receive(:build_settings).with(key: "DEVELOPMENT_TEAM").and_return(nil)
expect(FastlaneCore::Helper).to_not(receive(:backticks).with("security find-certificate -a -c \"3rd Party Mac Developer Installer: \"", print: false))
options = { project: "./gym/examples/multipleSchemes/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
installer_cert_name = Gym.config[:installer_cert_name]
expect(installer_cert_name).to eq(nil)
end
describe "using export_team_id" do
let(:options) { { project: "./gym/examples/multipleSchemes/Example.xcodeproj", export_team_id: team_id, export_method: "app-store" } }
it "finds installer cert from list with 2 matching and 1 non-matching" do
expect(FastlaneCore::Helper).to receive(:backticks).with("security find-certificate -a -c \"3rd Party Mac Developer Installer: \"", print: false).and_return(output_2_matching_1_nonmatching)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
installer_cert_name = Gym.config[:installer_cert_name]
expect(installer_cert_name).to eq("3rd Party Mac Developer Installer: #{team_name} (#{team_id})")
end
it "does not find installer cert from list with 1 non-matching" do
expect(FastlaneCore::Helper).to receive(:backticks).with("security find-certificate -a -c \"3rd Party Mac Developer Installer: \"", print: false).and_return(output_1_nonmatching)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
installer_cert_name = Gym.config[:installer_cert_name]
expect(installer_cert_name).to eq(nil)
end
it "does not installer cert from empty list" do
expect(FastlaneCore::Helper).to receive(:backticks).with("security find-certificate -a -c \"3rd Party Mac Developer Installer: \"", print: false).and_return(output_none)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
installer_cert_name = Gym.config[:installer_cert_name]
expect(installer_cert_name).to eq(nil)
end
end
describe "using DEVELOPMENT_TEAM builds setting" do
let(:options) { { project: "./gym/examples/multipleSchemes/Example.xcodeproj", export_method: "app-store" } }
before do
allow_any_instance_of(FastlaneCore::Project).to receive(:build_settings).with(anything).and_call_original
allow_any_instance_of(FastlaneCore::Project).to receive(:build_settings).with(key: "DEVELOPMENT_TEAM").and_return(team_id)
end
it "finds installer cert from list with 2 matching and 1 non-matching" do
expect(FastlaneCore::Helper).to receive(:backticks).with("security find-certificate -a -c \"3rd Party Mac Developer Installer: \"", print: false).and_return(output_2_matching_1_nonmatching)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
installer_cert_name = Gym.config[:installer_cert_name]
expect(installer_cert_name).to eq("3rd Party Mac Developer Installer: #{team_name} (#{team_id})")
end
it "does not find installer cert from list with 1 non-matching" do
expect(FastlaneCore::Helper).to receive(:backticks).with("security find-certificate -a -c \"3rd Party Mac Developer Installer: \"", print: false).and_return(output_1_nonmatching)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
installer_cert_name = Gym.config[:installer_cert_name]
expect(installer_cert_name).to eq(nil)
end
it "does not installer cert from empty list" do
expect(FastlaneCore::Helper).to receive(:backticks).with("security find-certificate -a -c \"3rd Party Mac Developer Installer: \"", print: false).and_return(output_none)
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
installer_cert_name = Gym.config[:installer_cert_name]
expect(installer_cert_name).to eq(nil)
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/platform_detection_spec.rb | gym/spec/platform_detection_spec.rb | describe Gym do
it "detects when a multiplatform project is building for iOS", requires_xcodebuild: true do
options = { project: "./gym/examples/multiplatform/Example.xcodeproj", sdk: "iphoneos" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
expect(Gym.project.multiplatform?).to eq(true)
expect(Gym.project.ios?).to eq(true)
expect(Gym.project.mac?).to eq(true)
expect(Gym.building_for_mac?).to eq(false)
expect(Gym.building_for_ios?).to eq(true)
expect(Gym.building_for_ipa?).to eq(true)
expect(Gym.building_for_pkg?).to eq(false)
expect(Gym.building_multiplatform_for_ios?).to eq(true)
end
it "detects when a multiplatform project is building for macOS", requires_xcodebuild: true do
options = { project: "./gym/examples/multiplatform/Example.xcodeproj", sdk: "macosx" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
expect(Gym.project.multiplatform?).to eq(true)
expect(Gym.project.ios?).to eq(true)
expect(Gym.project.mac?).to eq(true)
expect(Gym.building_for_ios?).to eq(false)
expect(Gym.building_for_mac?).to eq(true)
expect(Gym.building_for_ipa?).to eq(false)
expect(Gym.building_for_pkg?).to eq(true)
expect(Gym.building_multiplatform_for_mac?).to eq(true)
end
it "detects the correct platform for a visionOS project", requires_xcodebuild: true, if: FastlaneCore::Helper.mac? && FastlaneCore::Helper.xcode_at_least?('15.0') do
options = { project: "./gym/examples/visionos/VisionExample.xcodeproj", sdk: "xros", skip_package_dependencies_resolution: true }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
expect(Gym.project.multiplatform?).to eq(false)
expect(Gym.project.visionos?).to eq(true)
expect(Gym.project.ios?).to eq(false)
expect(Gym.building_for_ios?).to eq(true)
expect(Gym.building_for_mac?).to eq(false)
expect(Gym.building_for_ipa?).to eq(true)
expect(Gym.building_for_pkg?).to eq(false)
expect(Gym.building_multiplatform_for_mac?).to eq(false)
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/spec_helper.rb | gym/spec/spec_helper.rb | ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false | |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/options_spec.rb | gym/spec/options_spec.rb | describe Gym do
describe Gym::Options do
it "raises an exception when project path wasn't found" do
expect do
options = { project: "./gym/examples/standard/Example.xcodeproj", workspace: "./gym/examples/cocoapods/Example.xcworkspace" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
end.to raise_error("You can only pass either a 'project' or a 'workspace', not both")
end
it "removes the `ipa` from the output name if given", requires_xcodebuild: true do
options = { output_name: "Example.ipa", project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
expect(Gym.config[:output_name]).to eq("Example")
end
it "automatically chooses an existing scheme if the defined one is not available", requires_xcodebuild: true do
options = { project: "./gym/examples/standard/Example.xcodeproj", scheme: "NotHere" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
expect(Gym.config[:scheme]).to eq("Example")
end
it "replaces SEPARATOR (i.e. /) character with underscore(_) in output name", requires_xcodebuild: true do
options = { output_name: "feature" + File::SEPARATOR + "Example.ipa", project: "./gym/examples/standard/Example.xcodeproj" }
Gym.config = FastlaneCore::Configuration.create(Gym::Options.available_options, options)
expect(Gym.config[:output_name]).to eq("feature_Example")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/spec/xcodebuild_fixes/generic_archive_fix_spec.rb | gym/spec/xcodebuild_fixes/generic_archive_fix_spec.rb | describe Gym do
describe Gym::XcodebuildFixes do
let(:watch_app) { 'gym/spec/fixtures/xcodebuild_fixes/ios_watch_app.app' }
let(:ios_app) { 'gym/spec/fixtures/xcodebuild_fixes/ios_app.app' }
it "can detect watch application", requires_plistbuddy: true do
expect(Gym::XcodebuildFixes.is_watchkit_app?(watch_app)).to eq(true)
end
it "doesn't detect iOS application" do
expect(Gym::XcodebuildFixes.is_watchkit_app?(ios_app)).to eq(false)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym.rb | gym/lib/gym.rb | require_relative 'gym/manager'
require_relative 'gym/generators/build_command_generator'
require_relative 'gym/generators/package_command_generator'
require_relative 'gym/runner'
require_relative 'gym/error_handler'
require_relative 'gym/options'
require_relative 'gym/detect_values'
require_relative 'gym/xcode'
require_relative 'gym/code_signing_mapping'
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/code_signing_mapping.rb | gym/lib/gym/code_signing_mapping.rb | require 'xcodeproj'
require_relative 'module'
module Gym
class CodeSigningMapping
attr_accessor :project
def initialize(project: nil)
self.project = project
end
# @param primary_mapping [Hash] The preferred mapping (e.g. whatever the user provided)
# @param secondary_mapping [Hash] (optional) The secondary mapping (e.g. whatever is detected from the Xcode project)
# @param export_method [String] The method that should be preferred in case there is a conflict
def merge_profile_mapping(primary_mapping: nil, secondary_mapping: nil, export_method: nil)
final_mapping = (primary_mapping || {}).dup # for verbose output at the end of the method
secondary_mapping ||= self.detect_project_profile_mapping # default to Xcode project
final_mapping = final_mapping.transform_keys(&:to_sym)
secondary_mapping = secondary_mapping.transform_keys(&:to_sym)
# Now it's time to merge the (potentially) existing mapping
# (e.g. coming from `provisioningProfiles` of the `export_options` or from previous match calls)
# with the secondary hash we just created (or was provided as parameter).
# Both might include information about what profile to use
# This is important as it might not be clear for the user that they have to call match for each app target
# before adding this code, we'd only either use whatever we get from match, or what's defined in the Xcode project
# With the code below, we'll make sure to take the best of it:
#
# 1) A provisioning profile is defined in the `primary_mapping`
# 2) A provisioning profile is defined in the `secondary_mapping`
# 3) On a conflict (app identifier assigned both in xcode and match)
# 3.1) we'll choose whatever matches what's defined as the `export_method`
# 3.2) If both include the right `export_method`, we'll prefer the one from `primary_mapping`
# 3.3) If none has the right export_method, we'll use whatever is defined in the Xcode project
#
# To get a better sense of this, check out code_signing_spec.rb for some test cases
secondary_mapping.each do |bundle_identifier, provisioning_profile|
if final_mapping[bundle_identifier].nil?
final_mapping[bundle_identifier] = provisioning_profile
else
if self.app_identifier_contains?(final_mapping[bundle_identifier], export_method) # 3.1 + 3.2 nothing to do in this case
elsif self.app_identifier_contains?(provisioning_profile, export_method)
# Also 3.1 (3.1 is "implemented" twice, as it could be either the primary, or the secondary being the one that matches)
final_mapping[bundle_identifier] = provisioning_profile
else
# 3.3
final_mapping[bundle_identifier] = provisioning_profile
end
end
end
UI.verbose("Merging provisioning profile mappings")
UI.verbose("-------------------------------------")
UI.verbose("Primary provisioning profile mapping:")
UI.verbose(primary_mapping)
UI.verbose("Secondary provisioning profile mapping:")
UI.verbose(secondary_mapping)
UI.verbose("Resulting in the following mapping:")
UI.verbose(final_mapping)
return final_mapping
end
# Helper method to remove "-" and " " and downcase app identifier
# and compare if an app identifier includes a certain string
# We do some `gsub`bing, because we can't really know the profile type, so we'll just look at the name and see if it includes
# the export method (which it usually does, but with different notations)
def app_identifier_contains?(str, contains)
return str.to_s.gsub("-", "").gsub(" ", "").gsub("InHouse", "enterprise").downcase.include?(contains.to_s.gsub("-", "").gsub(" ", "").downcase)
end
def test_target?(build_settings)
return (!build_settings["TEST_TARGET_NAME"].nil? || !build_settings["TEST_HOST"].nil?)
end
def same_platform?(sdkroot)
destination = Gym.config[:destination].dup
destination.slice!("generic/platform=")
destination_sdkroot = []
case destination
when "macosx"
destination_sdkroot = ["macosx"]
when "iOS"
destination_sdkroot = ["iphoneos", "watchos"]
when "tvOS"
destination_sdkroot = ["appletvos"]
end
# Catalyst projects will always have an "iphoneos" sdkroot
# Need to force a same platform when trying to build as macos
if Gym.building_mac_catalyst_for_mac?
return true
end
return destination_sdkroot.include?(sdkroot)
end
def detect_configuration_for_archive
extract_from_scheme = lambda do
if self.project.workspace?
available_schemes = self.project.workspace.schemes.reject { |k, v| v.include?("Pods/Pods.xcodeproj") }
project_path = available_schemes[Gym.config[:scheme]]
else
project_path = self.project.path
end
if project_path
scheme_path = File.join(project_path, "xcshareddata", "xcschemes", "#{Gym.config[:scheme]}.xcscheme")
Xcodeproj::XCScheme.new(scheme_path).archive_action.build_configuration if File.exist?(scheme_path)
end
end
configuration = Gym.config[:configuration]
configuration ||= extract_from_scheme.call if Gym.config[:scheme]
configuration ||= self.project.default_build_settings(key: "CONFIGURATION")
return configuration
end
def detect_project_profile_mapping
provisioning_profile_mapping = {}
specified_configuration = detect_configuration_for_archive
self.project.project_paths.each do |project_path|
UI.verbose("Parsing project file '#{project_path}' to find selected provisioning profiles")
UI.verbose("Finding provision profiles for '#{specified_configuration}'") if specified_configuration
begin
# Storing bundle identifiers with duplicate profiles
# for informing user later on
bundle_identifiers_with_duplicates = []
project = Xcodeproj::Project.open(project_path)
project.targets.each do |target|
target.build_configuration_list.build_configurations.each do |build_configuration|
current = build_configuration.build_settings
next if test_target?(current)
sdkroot = build_configuration.resolve_build_setting("SDKROOT", target)
next unless same_platform?(sdkroot)
next unless specified_configuration == build_configuration.name
# Catalyst apps will have some build settings that will have a configuration
# that is specific for macos so going to do our best to capture those
#
# There are other platform filters besides "[sdk=macosx*]" that we could use but
# this is the default that Xcode will use so this will also be our default
sdk_specifier = Gym.building_mac_catalyst_for_mac? ? "[sdk=macosx*]" : ""
# Look for sdk specific bundle identifier (if set) and fallback to general configuration if none
bundle_identifier = build_configuration.resolve_build_setting("PRODUCT_BUNDLE_IDENTIFIER#{sdk_specifier}", target)
bundle_identifier ||= build_configuration.resolve_build_setting("PRODUCT_BUNDLE_IDENTIFIER", target)
next unless bundle_identifier
# Xcode prefixes "maccatalyst." if building a Catalyst app for mac and
# if DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER is set to YES
if Gym.building_mac_catalyst_for_mac? && build_configuration.resolve_build_setting("DERIVE_MACCATALYST_PRODUCT_BUNDLE_IDENTIFIER", target) == "YES"
bundle_identifier = "maccatalyst.#{bundle_identifier}"
end
# Look for sdk specific provisioning profile specifier (if set) and fallback to general configuration if none
provisioning_profile_specifier = build_configuration.resolve_build_setting("PROVISIONING_PROFILE_SPECIFIER#{sdk_specifier}", target)
provisioning_profile_specifier ||= build_configuration.resolve_build_setting("PROVISIONING_PROFILE_SPECIFIER", target)
# Look for sdk specific provisioning profile uuid (if set) and fallback to general configuration if none
provisioning_profile_uuid = build_configuration.resolve_build_setting("PROVISIONING_PROFILE#{sdk_specifier}", target)
provisioning_profile_uuid ||= build_configuration.resolve_build_setting("PROVISIONING_PROFILE", target)
has_profile_specifier = provisioning_profile_specifier.to_s.length > 0
has_profile_uuid = provisioning_profile_uuid.to_s.length > 0
# Stores bundle identifiers that have already been mapped to inform user
if provisioning_profile_mapping[bundle_identifier] && (has_profile_specifier || has_profile_uuid)
bundle_identifiers_with_duplicates << bundle_identifier
end
# Creates the mapping for a bundle identifier and profile specifier/uuid
if has_profile_specifier
provisioning_profile_mapping[bundle_identifier] = provisioning_profile_specifier
elsif has_profile_uuid
provisioning_profile_mapping[bundle_identifier] = provisioning_profile_uuid
end
end
# Alerting user to explicitly specify a mapping if cannot be determined
next if bundle_identifiers_with_duplicates.empty?
UI.error("Couldn't automatically detect the provisioning profile mapping")
UI.error("There were multiple profiles for bundle identifier(s): #{bundle_identifiers_with_duplicates.uniq.join(', ')}")
UI.error("You need to provide an explicit mapping of what provisioning")
UI.error("profile to use for each bundle identifier of your app")
end
rescue => ex
# We catch errors here, as we might run into an exception on one included project
# But maybe the next project actually contains the information we need
if Helper.xcode_at_least?("9.0")
UI.error("Couldn't automatically detect the provisioning profile mapping")
UI.error("Since Xcode 9 you need to provide an explicit mapping of what")
UI.error("provisioning profile to use for each target of your app")
UI.error(ex)
UI.verbose(ex.backtrace.join("\n"))
end
end
end
return provisioning_profile_mapping
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/gym/lib/gym/options.rb | gym/lib/gym/options.rb | require 'fastlane_core/configuration/config_item'
require 'fastlane/helper/xcodebuild_formatter_helper'
require 'credentials_manager/appfile_config'
require_relative 'module'
module Gym
# rubocop:disable Metrics/ClassLength
class Options
def self.available_options
return @options if @options
@options = plain_options
end
def self.plain_options
[
FastlaneCore::ConfigItem.new(key: :workspace,
short_option: "-w",
env_name: "GYM_WORKSPACE",
optional: true,
description: "Path to the workspace file",
verify_block: proc do |value|
v = File.expand_path(value.to_s)
UI.user_error!("Workspace file not found at path '#{v}'") unless File.exist?(v)
UI.user_error!("Workspace file invalid") unless File.directory?(v)
UI.user_error!("Workspace file is not a workspace, must end with .xcworkspace") unless v.include?(".xcworkspace")
end,
conflicting_options: [:project],
conflict_block: proc do |value|
UI.user_error!("You can only pass either a 'workspace' or a '#{value.key}', not both")
end),
FastlaneCore::ConfigItem.new(key: :project,
short_option: "-p",
optional: true,
env_name: "GYM_PROJECT",
description: "Path to the project file",
verify_block: proc do |value|
v = File.expand_path(value.to_s)
UI.user_error!("Project file not found at path '#{v}'") unless File.exist?(v)
UI.user_error!("Project file invalid") unless File.directory?(v)
UI.user_error!("Project file is not a project file, must end with .xcodeproj") unless v.include?(".xcodeproj")
end,
conflicting_options: [:workspace],
conflict_block: proc do |value|
UI.user_error!("You can only pass either a 'project' or a '#{value.key}', not both")
end),
FastlaneCore::ConfigItem.new(key: :scheme,
short_option: "-s",
optional: true,
env_name: "GYM_SCHEME",
description: "The project's scheme. Make sure it's marked as `Shared`"),
FastlaneCore::ConfigItem.new(key: :clean,
short_option: "-c",
env_name: "GYM_CLEAN",
description: "Should the project be cleaned before building it?",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :output_directory,
short_option: "-o",
env_name: "GYM_OUTPUT_DIRECTORY",
description: "The directory in which the ipa file should be stored in",
default_value: "."),
FastlaneCore::ConfigItem.new(key: :output_name,
short_option: "-n",
env_name: "GYM_OUTPUT_NAME",
description: "The name of the resulting ipa file",
optional: true),
FastlaneCore::ConfigItem.new(key: :configuration,
short_option: "-q",
env_name: "GYM_CONFIGURATION",
description: "The configuration to use when building the app. Defaults to 'Release'",
default_value_dynamic: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :silent,
short_option: "-a",
env_name: "GYM_SILENT",
description: "Hide all information that's not necessary while building",
default_value: false,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :codesigning_identity,
short_option: "-i",
env_name: "GYM_CODE_SIGNING_IDENTITY",
description: "The name of the code signing identity to use. It has to match the name exactly. e.g. 'iPhone Distribution: SunApps GmbH'",
optional: true),
FastlaneCore::ConfigItem.new(key: :skip_package_ipa,
env_name: "GYM_SKIP_PACKAGE_IPA",
description: "Should we skip packaging the ipa?",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :skip_package_pkg,
env_name: "GYM_SKIP_PACKAGE_PKG",
description: "Should we skip packaging the pkg?",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :include_symbols,
short_option: "-m",
env_name: "GYM_INCLUDE_SYMBOLS",
description: "Should the ipa file include symbols?",
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :include_bitcode,
short_option: "-z",
env_name: "GYM_INCLUDE_BITCODE",
description: "Should the ipa file include bitcode?",
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :export_method,
short_option: "-j",
env_name: "GYM_EXPORT_METHOD",
description: "Method used to export the archive. Valid values are: app-store, validation, ad-hoc, package, enterprise, development, developer-id and mac-application",
type: String,
optional: true,
verify_block: proc do |value|
av = %w(app-store validation ad-hoc package enterprise development developer-id mac-application)
UI.user_error!("Unsupported export_method '#{value}', must be: #{av}") unless av.include?(value)
end),
FastlaneCore::ConfigItem.new(key: :export_options,
env_name: "GYM_EXPORT_OPTIONS",
description: "Path to an export options plist or a hash with export options. Use 'xcodebuild -help' to print the full set of available options",
optional: true,
type: Hash,
skip_type_validation: true,
conflict_block: proc do |value|
UI.user_error!("'#{value.key}' must be false to use 'export_options'")
end),
FastlaneCore::ConfigItem.new(key: :export_xcargs,
env_name: "GYM_EXPORT_XCARGS",
description: "Pass additional arguments to xcodebuild for the package phase. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS=\"-ObjC -lstdc++\"",
optional: true,
conflict_block: proc do |value|
UI.user_error!("'#{value.key}' must be false to use 'export_xcargs'")
end,
type: :shell_string),
FastlaneCore::ConfigItem.new(key: :skip_build_archive,
env_name: "GYM_SKIP_BUILD_ARCHIVE",
description: "Export ipa from previously built xcarchive. Uses archive_path as source",
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :skip_archive,
env_name: "GYM_SKIP_ARCHIVE",
description: "After building, don't archive, effectively not including -archivePath param",
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :skip_codesigning,
env_name: "GYM_SKIP_CODESIGNING",
description: "Build without codesigning",
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :catalyst_platform,
env_name: "GYM_CATALYST_PLATFORM",
description: "Platform to build when using a Catalyst enabled app. Valid values are: ios, macos",
type: String,
optional: true,
verify_block: proc do |value|
av = %w(ios macos)
UI.user_error!("Unsupported catalyst_platform '#{value}', must be: #{av}") unless av.include?(value)
end),
FastlaneCore::ConfigItem.new(key: :installer_cert_name,
env_name: "GYM_INSTALLER_CERT_NAME",
description: "Full name of 3rd Party Mac Developer Installer or Developer ID Installer certificate. Example: `3rd Party Mac Developer Installer: Your Company (ABC1234XWYZ)`",
type: String,
optional: true),
# Very optional
FastlaneCore::ConfigItem.new(key: :build_path,
env_name: "GYM_BUILD_PATH",
description: "The directory in which the archive should be stored in",
optional: true),
FastlaneCore::ConfigItem.new(key: :archive_path,
short_option: "-b",
env_name: "GYM_ARCHIVE_PATH",
description: "The path to the created archive",
optional: true),
FastlaneCore::ConfigItem.new(key: :derived_data_path,
short_option: "-f",
env_name: "GYM_DERIVED_DATA_PATH",
description: "The directory where built products and other derived data will go",
optional: true),
FastlaneCore::ConfigItem.new(key: :result_bundle,
short_option: "-u",
env_name: "GYM_RESULT_BUNDLE",
type: Boolean,
description: "Should an Xcode result bundle be generated in the output directory",
default_value: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :result_bundle_path,
env_name: "GYM_RESULT_BUNDLE_PATH",
description: "Path to the result bundle directory to create. Ignored if `result_bundle` if false",
optional: true),
FastlaneCore::ConfigItem.new(key: :buildlog_path,
short_option: "-l",
env_name: "GYM_BUILDLOG_PATH",
description: "The directory where to store the build log",
default_value: "#{FastlaneCore::Helper.buildlog_path}/gym",
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :sdk,
short_option: "-k",
env_name: "GYM_SDK",
description: "The SDK that should be used for building the application",
optional: true),
FastlaneCore::ConfigItem.new(key: :toolchain,
env_name: "GYM_TOOLCHAIN",
description: "The toolchain that should be used for building the application (e.g. com.apple.dt.toolchain.Swift_2_3, org.swift.30p620160816a)",
optional: true,
type: String),
FastlaneCore::ConfigItem.new(key: :destination,
short_option: "-d",
env_name: "GYM_DESTINATION",
description: "Use a custom destination for building the app",
optional: true),
FastlaneCore::ConfigItem.new(key: :export_team_id,
short_option: "-g",
env_name: "GYM_EXPORT_TEAM_ID",
description: "Optional: Sometimes you need to specify a team id when exporting the ipa file",
optional: true),
FastlaneCore::ConfigItem.new(key: :xcargs,
short_option: "-x",
env_name: "GYM_XCARGS",
description: "Pass additional arguments to xcodebuild for the build phase. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS=\"-ObjC -lstdc++\"",
optional: true,
type: :shell_string),
FastlaneCore::ConfigItem.new(key: :xcconfig,
short_option: "-y",
env_name: "GYM_XCCONFIG",
description: "Use an extra XCCONFIG file to build your app",
optional: true,
verify_block: proc do |value|
UI.user_error!("File not found at path '#{File.expand_path(value)}'") unless File.exist?(value)
end),
FastlaneCore::ConfigItem.new(key: :suppress_xcode_output,
short_option: "-r",
env_name: "SUPPRESS_OUTPUT",
description: "Suppress the output of xcodebuild to stdout. Output is still saved in buildlog_path",
optional: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :xcodebuild_formatter,
env_names: ["GYM_XCODEBUILD_FORMATTER", "FASTLANE_XCODEBUILD_FORMATTER"],
description: "xcodebuild formatter to use (ex: 'xcbeautify', 'xcbeautify --quieter', 'xcpretty', 'xcpretty -test'). Use empty string (ex: '') to disable any formatter (More information: https://docs.fastlane.tools/best-practices/xcodebuild-formatters/)",
type: String,
default_value: Fastlane::Helper::XcodebuildFormatterHelper.xcbeautify_installed? ? 'xcbeautify' : 'xcpretty',
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :build_timing_summary,
env_name: "GYM_BUILD_TIMING_SUMMARY",
description: "Create a build timing summary",
type: Boolean,
default_value: false,
optional: true),
# xcpretty
FastlaneCore::ConfigItem.new(key: :disable_xcpretty,
env_name: "DISABLE_XCPRETTY",
deprecated: "Use `xcodebuild_formatter: ''` instead",
description: "Disable xcpretty formatting of build output",
optional: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :xcpretty_test_format,
env_name: "XCPRETTY_TEST_FORMAT",
description: "Use the test (RSpec style) format for build output",
optional: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :xcpretty_formatter,
env_name: "XCPRETTY_FORMATTER",
description: "A custom xcpretty formatter to use",
optional: true,
verify_block: proc do |value|
UI.user_error!("Formatter file not found at path '#{File.expand_path(value)}'") unless File.exist?(value)
end),
FastlaneCore::ConfigItem.new(key: :xcpretty_report_junit,
env_name: "XCPRETTY_REPORT_JUNIT",
description: "Have xcpretty create a JUnit-style XML report at the provided path",
optional: true),
FastlaneCore::ConfigItem.new(key: :xcpretty_report_html,
env_name: "XCPRETTY_REPORT_HTML",
description: "Have xcpretty create a simple HTML report at the provided path",
optional: true),
FastlaneCore::ConfigItem.new(key: :xcpretty_report_json,
env_name: "XCPRETTY_REPORT_JSON",
description: "Have xcpretty create a JSON compilation database at the provided path",
optional: true),
FastlaneCore::ConfigItem.new(key: :xcpretty_utf,
env_name: "XCPRETTY_UTF",
description: "Have xcpretty use unicode encoding when reporting builds",
optional: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :analyze_build_time,
env_name: "GYM_ANALYZE_BUILD_TIME",
description: "Analyze the project build time and store the output in 'culprits.txt' file",
optional: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :skip_profile_detection,
env_name: "GYM_SKIP_PROFILE_DETECTION",
description: "Do not try to build a profile mapping from the xcodeproj. Match or a manually provided mapping should be used",
optional: true,
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :xcodebuild_command,
env_name: "GYM_XCODE_BUILD_COMMAND",
description: "Allows for override of the default `xcodebuild` command",
type: String,
optional: true,
default_value: "xcodebuild"),
FastlaneCore::ConfigItem.new(key: :cloned_source_packages_path,
env_name: "GYM_CLONED_SOURCE_PACKAGES_PATH",
description: "Sets a custom path for Swift Package Manager dependencies",
type: String,
optional: true),
FastlaneCore::ConfigItem.new(key: :package_cache_path,
env_name: "GYM_PACKAGE_CACHE_PATH",
description: "Sets a custom package cache path for Swift Package Manager dependencies",
type: String,
optional: true),
FastlaneCore::ConfigItem.new(key: :skip_package_dependencies_resolution,
env_name: "GYM_SKIP_PACKAGE_DEPENDENCIES_RESOLUTION",
description: "Skips resolution of Swift Package Manager dependencies",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :disable_package_automatic_updates,
env_name: "GYM_DISABLE_PACKAGE_AUTOMATIC_UPDATES",
description: "Prevents packages from automatically being resolved to versions other than those recorded in the `Package.resolved` file",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :use_system_scm,
env_name: "GYM_USE_SYSTEM_SCM",
description: "Lets xcodebuild use system's scm configuration",
optional: true,
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :package_authorization_provider,
env_name: "GYM_PACKAGE_AUTHORIZATION_PROVIDER",
description: "Lets xcodebuild use a specified package authorization provider (keychain|netrc)",
optional: true,
type: String,
verify_block: proc do |value|
av = %w(netrc keychain)
UI.user_error!("Unsupported authorization provider '#{value}', must be: #{av}") unless av.include?(value)
end),
FastlaneCore::ConfigItem.new(key: :generate_appstore_info,
env_name: "GYM_GENERATE_APPSTORE_INFO",
description: "Generate AppStoreInfo.plist using swinfo for app-store exports",
type: Boolean,
optional: true,
default_value: false)
]
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/gym/lib/gym/detect_values.rb | gym/lib/gym/detect_values.rb | require 'fastlane_core/core_ext/cfpropertylist'
require 'fastlane_core/project'
require_relative 'module'
require_relative 'code_signing_mapping'
module Gym
# This class detects all kinds of default values
class DetectValues
# This is needed as these are more complex default values
# Returns the finished config object
def self.set_additional_default_values
config = Gym.config
# First, try loading the Gymfile from the current directory
config.load_configuration_file(Gym.gymfile_name)
# Detect the project
FastlaneCore::Project.detect_projects(config)
Gym.project = FastlaneCore::Project.new(config)
# Go into the project's folder, as there might be a Gymfile there
project_path = File.expand_path("..", Gym.project.path)
unless File.expand_path(".") == project_path
Dir.chdir(project_path) do
config.load_configuration_file(Gym.gymfile_name)
end
end
ensure_export_options_is_hash
detect_scheme
detect_platform # we can only do that *after* we have the scheme
detect_selected_provisioning_profiles # we can only do that *after* we have the platform
detect_configuration
detect_toolchain
detect_third_party_installer
config[:output_name] ||= Gym.project.app_name
config[:build_path] ||= archive_path_from_local_xcode_preferences
# Make sure the output name is valid and remove a trailing `.ipa` extension
# as it will be added by gym for free
config[:output_name].gsub!(".ipa", "")
config[:output_name].gsub!(File::SEPARATOR, "_")
return config
end
def self.archive_path_from_local_xcode_preferences
day = Time.now.strftime("%F") # e.g. 2015-08-07
archive_path = File.expand_path("~/Library/Developer/Xcode/Archives/#{day}/")
return archive_path unless has_xcode_preferences_plist?
custom_archive_path = xcode_preferences_dictionary['IDECustomDistributionArchivesLocation']
return archive_path if custom_archive_path.to_s.length == 0
return File.join(custom_archive_path, day)
end
# Helper Methods
# this file only exists when you edit the Xcode preferences to set custom values
def self.has_xcode_preferences_plist?
File.exist?(xcode_preference_plist_path)
end
def self.xcode_preference_plist_path
File.expand_path("~/Library/Preferences/com.apple.dt.Xcode.plist")
end
def self.xcode_preferences_dictionary(path = xcode_preference_plist_path)
CFPropertyList.native_types(CFPropertyList::List.new(file: path).value)
end
# Since Xcode 9 you need to provide the explicit mapping of what provisioning profile to use for
# each target of your app
def self.detect_selected_provisioning_profiles
Gym.config[:export_options] ||= {}
hash_to_use = (Gym.config[:export_options][:provisioningProfiles] || {}).dup || {} # dup so we can show the original values in `verbose` mode
unless Gym.config[:skip_profile_detection]
mapping_object = CodeSigningMapping.new(project: Gym.project)
hash_to_use = mapping_object.merge_profile_mapping(primary_mapping: hash_to_use,
export_method: Gym.config[:export_method])
end
return if hash_to_use.count == 0 # We don't want to set a mapping if we don't have one
Gym.config[:export_options][:provisioningProfiles] = hash_to_use
UI.message("Detected provisioning profile mapping: #{hash_to_use}")
rescue => ex
# We don't want to fail the build if the automatic detection doesn't work
# especially since the mapping is optional for pre Xcode 9 setups
if Helper.xcode_at_least?("9.0")
UI.error("Couldn't automatically detect the provisioning profile mapping")
UI.error("Since Xcode 9 you need to provide an explicit mapping of what")
UI.error("provisioning profile to use for each target of your app")
UI.error(ex)
UI.verbose(ex.backtrace.join("\n"))
end
end
# Detects name of a "3rd Party Mac Developer Installer" cert for the configured team id
def self.detect_third_party_installer
return if Gym.config[:installer_cert_name]
team_id = Gym.config[:export_team_id] || Gym.project.build_settings(key: "DEVELOPMENT_TEAM")
return if team_id.nil?
case Gym.config[:export_method]
when "app-store"
prefix = "3rd Party Mac Developer Installer: "
when "developer-id"
prefix = "Developer ID Installer: "
else
return
end
output = Helper.backticks("security find-certificate -a -c \"#{prefix}\"", print: false)
# Find matches, filter by team_id, prepend prefix for full cert name
certs = output.scan(/"(?:#{prefix})(.*)"/)
certs = certs.flatten.uniq.select do |cert|
cert.include?(team_id)
end.map do |cert|
prefix + cert
end
if certs.first
UI.verbose("Detected installer certificate to use: #{certs.first}")
Gym.config[:installer_cert_name] = certs.first
end
end
def self.detect_scheme
Gym.project.select_scheme
end
def self.min_xcode8?
Helper.xcode_at_least?("8.0")
end
# Is it an iOS device or a Mac?
def self.detect_platform
return if Gym.config[:destination]
platform = if Gym.project.tvos?
"tvOS"
elsif Gym.project.visionos?
"visionOS"
elsif Gym.building_for_ios?
"iOS"
elsif Gym.building_for_mac?
min_xcode8? ? "macOS" : "OS X"
else
"iOS"
end
Gym.config[:destination] = "generic/platform=#{platform}"
end
# Detects the available configurations (e.g. Debug, Release)
def self.detect_configuration
config = Gym.config
configurations = Gym.project.configurations
return if configurations.count == 0 # this is an optional value anyway
if config[:configuration]
# Verify the configuration is available
unless configurations.include?(config[:configuration])
UI.error("Couldn't find specified configuration '#{config[:configuration]}'.")
config[:configuration] = nil
end
end
end
# The toolchain parameter is used if you don't use the default toolchain of Xcode (e.g. Swift 2.3 with Xcode 8)
def self.detect_toolchain
return unless Gym.config[:toolchain]
# Convert the aliases to the full string to make it easier for the user #justfastlanethings
if Gym.config[:toolchain].to_s == "swift_2_3"
Gym.config[:toolchain] = "com.apple.dt.toolchain.Swift_2_3"
end
end
def self.ensure_export_options_is_hash
return if Gym.config[:export_options].nil? || Gym.config[:export_options].kind_of?(Hash)
# Reads options from file
plist_file_path = Gym.config[:export_options]
UI.user_error!("Couldn't find plist file at path #{File.expand_path(plist_file_path)}") unless File.exist?(plist_file_path)
hash = Plist.parse_xml(plist_file_path)
UI.user_error!("Couldn't read provided plist at path #{File.expand_path(plist_file_path)}") if hash.nil?
# Convert keys to symbols
Gym.config[:export_options] = keys_to_symbols(hash)
end
def self.keys_to_symbols(hash)
# Convert keys to symbols
hash = hash.each_with_object({}) do |(k, v), memo|
memo[k.b.to_s.to_sym] = v
memo
end
hash
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/xcode.rb | gym/lib/gym/xcode.rb | require_relative 'module'
module Gym
class Xcode
class << self
def xcode_path
Helper.xcode_path
end
def xcode_version
Helper.xcode_version
end
# Below Xcode 7 (which offers a new nice API to sign the app)
def pre_7?
UI.user_error!("Unable to locate Xcode. Please make sure to have Xcode installed on your machine") if xcode_version.nil?
v = xcode_version
is_pre = v.split('.')[0].to_i < 7
is_pre
end
def legacy_api_deprecated?
FastlaneCore::Helper.xcode_at_least?('8.3')
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/commands_generator.rb | gym/lib/gym/commands_generator.rb | require 'commander'
require 'fastlane_core/configuration/configuration'
require 'fastlane_core/ui/help_formatter'
require_relative 'module'
require_relative 'manager'
require_relative 'options'
HighLine.track_eof = false
module Gym
class CommandsGenerator
include Commander::Methods
def self.start
new.run
end
def convert_options(options)
o = options.__hash__.dup
o.delete(:verbose)
o
end
def run
program :name, 'gym'
program :version, Fastlane::VERSION
program :description, Gym::DESCRIPTION
program :help, "Author", "Felix Krause <gym@krausefx.com>"
program :help, "Website", "https://fastlane.tools"
program :help, "Documentation", "https://docs.fastlane.tools/actions/gym/"
program :help_formatter, FastlaneCore::HelpFormatter
global_option("--verbose") { FastlaneCore::Globals.verbose = true }
command :build do |c|
c.syntax = "fastlane gym"
c.description = "Build your iOS/macOS app"
FastlaneCore::CommanderGenerator.new.generate(Gym::Options.available_options, command: c)
c.action do |_args, options|
config = FastlaneCore::Configuration.create(Gym::Options.available_options,
convert_options(options))
Gym::Manager.new.work(config)
end
end
command :init do |c|
c.syntax = "fastlane gym init"
c.description = "Creates a new Gymfile for you"
c.action do |args, options|
containing = FastlaneCore::Helper.fastlane_enabled_folder_path
path = File.join(containing, Gym.gymfile_name)
UI.user_error!("Gymfile already exists") if File.exist?(path)
is_swift_fastfile = args.include?("swift")
if is_swift_fastfile
path = File.join(containing, Gym.gymfile_name + ".swift")
UI.user_error!("Gymfile.swift already exists") if File.exist?(path)
end
if is_swift_fastfile
template = File.read("#{Gym::ROOT}/lib/assets/GymfileTemplate.swift")
else
template = File.read("#{Gym::ROOT}/lib/assets/GymfileTemplate")
end
File.write(path, template)
UI.success("Successfully created '#{path}'. Open the file using a code editor.")
end
end
default_command(:build)
run!
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/error_handler.rb | gym/lib/gym/error_handler.rb | # coding: utf-8
require 'fastlane_core/print_table'
require_relative 'module'
module Gym
# This classes methods are called when something goes wrong in the building process
class ErrorHandler
class << self
# @param [String] The output of the errored build
# This method should raise an exception in any case, as the return code indicated a failed build
def handle_build_error(output)
# The order of the handling below is important
case output
when /Your build settings specify a provisioning profile with the UUID/
print("Invalid code signing settings")
print("Your project defines a provisioning profile which doesn't exist on your local machine")
print("You can use sigh (https://docs.fastlane.tools/actions/sigh/) to download and install the provisioning profile")
print("Follow this guide: https://docs.fastlane.tools/codesigning/GettingStarted/")
when /Provisioning profile does not match bundle identifier/
print("Invalid code signing settings")
print("Your project defines a provisioning profile that doesn't match the bundle identifier of your app")
print("Make sure you use the correct provisioning profile for this app")
print("Take a look at the output above for more information")
print("You can follow this guide: https://docs.fastlane.tools/codesigning/GettingStarted/")
when /provisioning profiles matching the bundle identifier .(.*)./ # the . around the (.*) are for the strange "
print("You don't have the provisioning profile for '#{$1}' installed on the local machine")
print("Make sure you have the profile on this computer and it's properly installed")
print("You can use sigh (https://docs.fastlane.tools/actions/sigh/) to download and install the provisioning profile")
print("Follow this guide: https://docs.fastlane.tools/codesigning/GettingStarted/")
when /matching the bundle identifier .(.*). were found/ # the . around the (.*) are for the strange "
print("You don't have a provisioning profile for the bundle identifier '#{$1}' installed on the local machine")
print("Make sure you have the profile on this computer and it's properly installed")
print("You can use sigh (https://docs.fastlane.tools/actions/sigh/) to download and install the provisioning profile")
print("Follow this guide: https://docs.fastlane.tools/codesigning/GettingStarted/")
# Insert more code signing specific errors here
when /code signing is required/
print("Your project settings define invalid code signing settings")
print("To generate an ipa file you need to enable code signing for your project")
print("Additionally make sure you have a code signing identity set")
print("Follow this guide: https://docs.fastlane.tools/codesigning/GettingStarted/")
when /US\-ASCII/
print("Your shell environment is not correctly configured")
print("Instead of UTF-8 your shell uses US-ASCII")
print("Please add the following to your '~/.bashrc':")
print("")
print(" export LANG=en_US.UTF-8")
print(" export LANGUAGE=en_US.UTF-8")
print(" export LC_ALL=en_US.UTF-8")
print("")
print("You'll have to restart your shell session after updating the file.")
print("If you are using zshell or another shell, make sure to edit the correct bash file.")
print("For more information visit this stackoverflow answer:")
print("https://stackoverflow.com/a/17031697/445598")
end
print_xcode_path_instructions
print_xcode_version
print_full_log_path
print_environment_information
print_build_error_instructions
# This error is rather common and should be below the other (a little noisy) output
case output
when /Code signing is required for product/
print("Seems like Xcode is not happy with the code signing setup")
print("Please make sure to check out the raw `xcodebuild` output")
UI.important(Gym::BuildCommandGenerator.xcodebuild_log_path)
print("The very bottom of the file will tell you the raw Xcode error message")
print("indicating on why the code signing step failed")
end
UI.build_failure!("Error building the application - see the log above", error_info: output)
end
# @param [Array] The output of the errored build (line by line)
# This method should raise an exception in any case, as the return code indicated a failed build
def handle_package_error(output)
case output
when /single\-bundle/
print("Your project does not contain a single–bundle application or contains multiple products")
print("Please read the documentation provided by Apple: https://developer.apple.com/library/ios/technotes/tn2215/_index.html")
when /no signing identity matches '(.*)'/
print("Could not find code signing identity '#{$1}'")
print("Make sure the name of the code signing identity is correct")
print("and it matches a locally installed code signing identity")
print("You can pass the name of the code signing identity using the")
print("`codesigning_identity` option")
when /no provisioning profile matches '(.*)'/
print("Could not find provisioning profile with the name '#{$1}'")
print("Make sure the name of the provisioning profile is correct")
print("and it matches a locally installed profile")
when /mismatch between specified provisioning profile and signing identity/
print("Mismatch between provisioning profile and code signing identity")
print("This means, the specified provisioning profile was not created using")
print("the specified certificate.")
print("Run cert and sigh before gym to make sure to have all signing resources ready")
when /requires a provisioning profile/
print("No provisioning profile provided")
print("Make sure to pass a valid provisioning for each required target")
print("Check out the docs on how to fix this: https://docs.fastlane.tools/actions/gym/#export-options")
# insert more specific code signing errors here
when /Codesign check fails/
print("A general code signing error occurred. Make sure you passed a valid")
print("provisioning profile and code signing identity.")
end
print_xcode_version
print_full_log_path
print_environment_information
print_build_error_instructions
print_xcode9_plist_warning
UI.build_failure!("Error packaging up the application", error_info: output)
end
def handle_empty_archive
print("The generated archive is invalid, this can have various reasons:")
print("Usually it's caused by the `Skip Install` option in Xcode, set it to `NO`")
print("For more information visit https://developer.apple.com/library/ios/technotes/tn2215/_index.html")
print("Also, make sure to have a valid code signing identity and provisioning profile installed")
print("Follow this guide to setup code signing https://docs.fastlane.tools/codesigning/GettingStarted/")
print("If your intention was only to export an ipa be sure to provide a valid archive at the archive path.")
print("This error might also happen if your workspace/project file is not in the root directory of your project.")
print("To workaround that issue, you can wrap your calls to gym with")
print("`Dir.chdir('../path/to/dir/containing/proj') do`")
print("For an example you can check out")
print("https://github.com/artsy/emission-nebula/commit/44fe51a7fea8f7d52f0f77d6c3084827fe5dd59e")
UI.build_failure!("Archive invalid")
end
def handle_empty_ipa
UI.build_failure!("IPA invalid")
end
def handle_empty_pkg
UI.build_failure!("PKG invalid")
end
private
# Just to make things easier
def print(text)
UI.error(text)
end
def print_full_log_path
return if Gym.config[:disable_xcpretty]
log_path = Gym::BuildCommandGenerator.xcodebuild_log_path
return unless File.exist?(log_path)
# `xcodebuild` doesn't properly mark lines as failure reason or important information
# so we assume that the last few lines show the error message that's relevant
# (at least that's what was correct during testing)
log_content = File.read(log_path).split("\n").last(5)
log_content.each do |row|
UI.command_output(row)
end
UI.message("")
UI.error("⬆️ Check out the few lines of raw `xcodebuild` output above for potential hints on how to solve this error")
UI.important("📋 For the complete and more detailed error log, check the full log at:")
UI.important("📋 #{log_path}")
end
def print_xcode9_plist_warning
return unless Helper.xcode_at_least?("9.0")
# prevent crash in case of packaging error AND if you have set export_options to a path.
return unless Gym.config[:export_options].kind_of?(Hash)
export_options = Gym.config[:export_options] || {}
provisioning_profiles = export_options[:provisioningProfiles] || []
if provisioning_profiles.count == 0
UI.error("Looks like no provisioning profile mapping was provided")
UI.error("Please check the complete output, in particular the very top")
UI.error("and see if you can find more information. You can also run fastlane")
UI.error("with the `--verbose` flag.")
UI.error("Alternatively you can provide the provisioning profile mapping manually")
UI.error("https://docs.fastlane.tools/codesigning/xcode-project/#xcode-9-and-up")
end
end
def print_xcode_version
# lots of the times, the user didn't set the correct Xcode version to their Xcode path
# since many users don't look at the table of summary before running a tool, let's make
# sure they are aware of the Xcode version and SDK they're using
values = {
xcode_path: File.expand_path("../..", FastlaneCore::Helper.xcode_path),
gym_version: Fastlane::VERSION,
export_method: Gym.config[:export_method]
}
sdk_path = Gym.project.build_settings(key: "SDKROOT")
values[:sdk] = File.basename(sdk_path) if sdk_path.to_s.length > 0
FastlaneCore::PrintTable.print_values(config: values,
hide_keys: [],
title: "Build environment".yellow)
end
def print_xcode_path_instructions
xcode_path = File.expand_path("../..", FastlaneCore::Helper.xcode_path)
default_xcode_path = "/Applications/"
xcode_installations_in_default_path = Dir[File.join(default_xcode_path, "Xcode*.app")]
return unless xcode_installations_in_default_path.count > 1
UI.message("")
UI.important("Maybe the error shown is caused by using the wrong version of Xcode")
UI.important("Found multiple versions of Xcode in '#{default_xcode_path}'")
UI.important("Make sure you selected the right version for your project")
UI.important("This build process was executed using '#{xcode_path}'")
UI.important("If you want to update your Xcode path, either")
UI.message("")
UI.message("- Specify the Xcode version in your Fastfile")
UI.command_output("xcversion(version: \"8.1\") # Selects Xcode 8.1.0")
UI.message("")
UI.message("- Specify an absolute path to your Xcode installation in your Fastfile")
UI.command_output("xcode_select \"/Applications/Xcode8.app\"")
UI.message("")
UI.message("- Manually update the path using")
UI.command_output("sudo xcode-select -s /Applications/Xcode.app")
UI.message("")
end
def print_environment_information
if Gym.config[:export_method].to_s == "development"
UI.message("")
UI.error("Your `export_method` in gym is defined as `development`")
UI.error("which might cause problems when signing your application")
UI.error("Are you sure want to build and export for development?")
UI.error("Please make sure to define the correct export methods when calling")
UI.error("gym in your Fastfile or from the command line")
UI.message("")
elsif Gym.config[:export_options] && Gym.config[:export_options].kind_of?(Hash)
# We want to tell the user if there is an obvious mismatch between the selected
# `export_method` and the selected provisioning profiles
selected_export_method = Gym.config[:export_method].to_s
selected_provisioning_profiles = Gym.config[:export_options][:provisioningProfiles] || []
# We could go ahead and find all provisioning profiles that match that name
# and then get its type, however that's not 100% reliable, as we can't distinguish between
# Ad Hoc and Development profiles for example.
# As an easier and more obvious alternative, we'll take the provisioning profile names
# and see if it contains the export_method name and see if there is a mismatch
# The reason we have multiple variations of the spelling is that
# the provisioning profile might be called anything below
# There is no 100% good way to detect the profile type based on the name
available_export_types = {
"app-store" => "app-store",
"app store" => "app-store",
"appstore" => "app-store",
"enterprise" => "enterprise",
"in-house" => "enterprise",
"in house" => "enterprise",
"inhouse" => "enterprise",
"ad-hoc" => "ad-hoc",
"adhoc" => "ad-hoc",
"ad hoc" => "ad-hoc",
"development" => "development"
}
selected_provisioning_profiles.each do |current_bundle_identifier, current_profile_name|
available_export_types.each do |current_to_try, matching_type|
next unless current_profile_name.to_s.downcase.include?(current_to_try.to_s.downcase)
# Check if there is a mismatch between the name and the selected export method
# Example
#
# current_profile_name = "me.themoji.app.beta App Store""
# current_to_try = "app store"
# matching_type = :appstore
# selected_export_method = "enterprise"
#
# As seen above, there is obviously a mismatch, the user selected an App Store
# profile, but the export method that's being passed to Xcode is "enterprise"
break if matching_type.to_s == selected_export_method
UI.message("")
UI.error("There seems to be a mismatch between your provided `export_method` in gym")
UI.error("and the selected provisioning profiles. You passed the following options:")
UI.important(" export_method: #{selected_export_method}")
UI.important(" Bundle identifier: #{current_bundle_identifier}")
UI.important(" Profile name: #{current_profile_name}")
UI.important(" Profile type: #{matching_type}")
UI.error("Make sure to either change the `export_method` passed from your Fastfile or CLI")
UI.error("or select the correct provisioning profiles by updating your Xcode project")
UI.error("or passing the profiles to use by using match or manually via the `export_options` hash")
UI.message("")
break
end
end
end
end
# Indicate that code signing errors are not caused by fastlane
# and that fastlane only runs `xcodebuild` commands
def print_build_error_instructions
UI.message("")
UI.error("Looks like fastlane ran into a build/archive error with your project")
UI.error("It's hard to tell what's causing the error, so we wrote some guides on how")
UI.error("to troubleshoot build and signing issues: https://docs.fastlane.tools/codesigning/getting-started/")
UI.error("Before submitting an issue on GitHub, please follow the guide above and make")
UI.error("sure your project is set up correctly.")
UI.error("fastlane uses `xcodebuild` commands to generate your binary, you can see the")
UI.error("the full commands printed out in yellow in the above log.")
UI.error("Make sure to inspect the output above, as usually you'll find more error information there")
UI.message("")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/runner.rb | gym/lib/gym/runner.rb | require 'open3'
require 'fileutils'
require 'shellwords'
require 'terminal-table'
require 'fastlane_core/print_table'
require 'fastlane_core/command_executor'
require_relative 'module'
require_relative 'generators/package_command_generator'
require_relative 'generators/build_command_generator'
require_relative 'error_handler'
module Gym
class Runner
# @return (String) The path to the resulting ipa
def run
unless Gym.config[:skip_build_archive]
build_app
end
verify_archive unless Gym.config[:skip_archive]
return nil if Gym.config[:skip_archive]
FileUtils.mkdir_p(File.expand_path(Gym.config[:output_directory]))
# Archive
if Gym.building_for_ipa?
fix_generic_archive unless Gym.project.watchos? # See https://github.com/fastlane/fastlane/pull/4325
return BuildCommandGenerator.archive_path if Gym.config[:skip_package_ipa]
package_app
compress_and_move_dsym
unless Gym.export_destination_upload?
path = move_ipa
move_manifest
move_app_thinning
move_app_thinning_size_report
move_apps_folder
move_asset_packs
appstore_info_path = move_appstore_info
generate_appstore_info(path) unless appstore_info_path
end
elsif Gym.building_for_pkg?
path = File.expand_path(Gym.config[:output_directory])
compress_and_move_dsym
if Gym.project.mac_app? || Gym.building_mac_catalyst_for_mac?
path = copy_mac_app
return path if Gym.config[:skip_package_pkg]
package_app
unless Gym.export_destination_upload?
path = move_pkg
move_appstore_info
end
return path
end
copy_files_from_path(File.join(BuildCommandGenerator.archive_path, "Products/usr/local/bin/*")) if Gym.project.command_line_tool?
end
return path
end
# rubocop:enable Metrics/PerceivedComplexity
#####################################################
# @!group Printing out things
#####################################################
# @param [Array] An array containing all the parts of the command
def print_command(command, title)
rows = command.map do |c|
current = c.to_s.dup
next unless current.length > 0
match_default_parameter = current.match(/(-.*) '(.*)'/)
if match_default_parameter
# That's a default parameter, like `-project 'Name'`
match_default_parameter[1, 2]
else
current.gsub!("| ", "\| ") # as the | will somehow break the terminal table
[current, ""]
end
end
puts(Terminal::Table.new(
title: title.green,
headings: ["Option", "Value"],
rows: FastlaneCore::PrintTable.transform_output(rows.delete_if { |c| c.to_s.empty? })
))
end
private
#####################################################
# @!group The individual steps
#####################################################
def fix_generic_archive
return unless FastlaneCore::Env.truthy?("GYM_USE_GENERIC_ARCHIVE_FIX")
Gym::XcodebuildFixes.generic_archive_fix
end
def mark_archive_as_built_by_gym(archive_path)
escaped_archive_path = archive_path.shellescape
system("xattr -w info.fastlane.generated_by_gym 1 #{escaped_archive_path}")
end
# Builds the app and prepares the archive
def build_app
command = BuildCommandGenerator.generate
print_command(command, "Generated Build Command") if FastlaneCore::Globals.verbose?
FastlaneCore::CommandExecutor.execute(command: command,
print_all: true,
print_command: !Gym.config[:silent],
error: proc do |output|
ErrorHandler.handle_build_error(output)
end)
unless Gym.config[:skip_archive]
mark_archive_as_built_by_gym(BuildCommandGenerator.archive_path)
UI.success("Successfully stored the archive. You can find it in the Xcode Organizer.") unless Gym.config[:archive_path].nil?
UI.verbose("Stored the archive in: " + BuildCommandGenerator.archive_path)
end
post_build_app
end
# Post-processing of build_app
def post_build_app
command = BuildCommandGenerator.post_build
return if command.empty?
print_command(command, "Generated Post-Build Command") if FastlaneCore::Globals.verbose?
FastlaneCore::CommandExecutor.execute(command: command,
print_all: true,
print_command: !Gym.config[:silent],
error: proc do |output|
ErrorHandler.handle_build_error(output)
end)
end
# Makes sure the archive is there and valid
def verify_archive
# from https://github.com/fastlane/fastlane/issues/3179
if (Dir[BuildCommandGenerator.archive_path + "/*"]).count == 0
ErrorHandler.handle_empty_archive
end
end
def package_app
command = PackageCommandGenerator.generate
print_command(command, "Generated Package Command") if FastlaneCore::Globals.verbose?
FastlaneCore::CommandExecutor.execute(command: command,
print_all: false,
print_command: !Gym.config[:silent],
error: proc do |output|
ErrorHandler.handle_package_error(output)
end)
end
def compress_and_move_dsym
return unless PackageCommandGenerator.dsym_path
# Compress and move the dsym file
containing_directory = File.expand_path("..", PackageCommandGenerator.dsym_path)
bcsymbolmaps_directory = File.expand_path("../../BCSymbolMaps", PackageCommandGenerator.dsym_path)
available_dsyms = Dir.glob("#{containing_directory}/*.dSYM")
uuid_regex = /[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}/
if Dir.exist?(bcsymbolmaps_directory)
UI.message("Mapping dSYM(s) using generated BCSymbolMaps") unless Gym.config[:silent]
available_dsyms.each do |dsym|
dwarfdump_command = []
dwarfdump_command << "dwarfdump"
dwarfdump_command << "--uuid #{dsym.shellescape}"
# Extract uuids
dwarfdump_result = Helper.backticks(dwarfdump_command.join(" "), print: false)
architecture_infos = dwarfdump_result.split("\n")
architecture_infos.each do |info|
info_array = info.split(" ", 4)
uuid = info_array[1]
dwarf_file_path = info_array[3]
if uuid.nil? || !uuid.match(uuid_regex)
next
end
# Find bcsymbolmap file to be used:
# - if a <uuid>.plist file exists, we will extract uuid of bcsymbolmap and use it
# - if a <uuid>.bcsymbolmap file exists, we will use it
# - otherwise let dsymutil figure it out
symbol_map_path = nil
split_dwarf_file_path = File.split(dwarf_file_path)
dsym_plist_file_path = File.join(split_dwarf_file_path[0], "..", "#{uuid}.plist")
if File.exist?(dsym_plist_file_path)
dsym_plist = Plist.parse_xml(dsym_plist_file_path)
original_uuid = dsym_plist['DBGOriginalUUID']
possible_symbol_map_path = "#{bcsymbolmaps_directory}/#{original_uuid}.bcsymbolmap"
if File.exist?(possible_symbol_map_path)
symbol_map_path = possible_symbol_map_path.shellescape
end
end
if symbol_map_path.nil?
possible_symbol_map_path = File.join(bcsymbolmaps_directory, "#{uuid}.bcsymbolmap")
if File.exist?(possible_symbol_map_path)
symbol_map_path = possible_symbol_map_path.shellescape
end
end
if symbol_map_path.nil?
symbol_map_path = bcsymbolmaps_directory.shellescape
end
command = []
command << "dsymutil"
command << "--symbol-map #{symbol_map_path}"
command << dsym.shellescape
Helper.backticks(command.join(" "), print: !Gym.config[:silent])
end
end
end
UI.message("Compressing #{available_dsyms.count} dSYM(s)") unless Gym.config[:silent]
output_path = File.expand_path(File.join(Gym.config[:output_directory], Gym.config[:output_name] + ".app.dSYM.zip"))
command = "cd '#{containing_directory}' && zip -r '#{output_path}' *.dSYM"
Helper.backticks(command, print: !Gym.config[:silent])
puts("") # new line
UI.success("Successfully exported and compressed dSYM file")
end
# Moves over the binary and dsym file to the output directory
# @return (String) The path to the resulting ipa file
def move_ipa
FileUtils.mv(PackageCommandGenerator.ipa_path, File.expand_path(Gym.config[:output_directory]), force: true)
ipa_path = File.expand_path(File.join(Gym.config[:output_directory], File.basename(PackageCommandGenerator.ipa_path)))
UI.success("Successfully exported and signed the ipa file:")
UI.message(ipa_path)
ipa_path
end
# Moves over the binary and dsym file to the output directory
# @return (String) The path to the resulting pkg file
def move_pkg
binary_path = File.expand_path(File.join(Gym.config[:output_directory], File.basename(PackageCommandGenerator.binary_path)))
if File.exist?(binary_path)
UI.important(" Removing #{File.basename(binary_path)}") if FastlaneCore::Globals.verbose?
FileUtils.rm_rf(binary_path)
end
FileUtils.mv(PackageCommandGenerator.binary_path, File.expand_path(Gym.config[:output_directory]), force: true)
UI.success("Successfully exported and signed the pkg file:")
UI.message(binary_path)
binary_path
end
# copies framework from temp folder:
def copy_files_from_path(path)
UI.success("Exporting Files:")
Dir[path].each do |f|
existing_file = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(f))
# If the target file already exists in output directory
# we have to remove it first, otherwise cp_r fails even with remove_destination
# e.g.: there are symlinks in the .framework
if File.exist?(existing_file)
UI.important("Removing #{File.basename(f)} from output directory") if FastlaneCore::Globals.verbose?
FileUtils.rm_rf(existing_file)
end
FileUtils.cp_r(f, File.expand_path(Gym.config[:output_directory]), remove_destination: true)
UI.message("\t ▸ #{File.basename(f)}")
end
end
# Copies the .app from the archive into the output directory
def copy_mac_app
exe_name = Gym.project.build_settings(key: "EXECUTABLE_NAME")
app_path = File.join(BuildCommandGenerator.archive_path, "Products/Applications/#{exe_name}.app")
unless File.exist?(app_path)
# Apparently the `EXECUTABLE_NAME` is not correct. This can happen when building a workspace which has a project
# earlier in the build order that has a different `EXECUTABLE_NAME` than the app. Try to find the last `.app` as
# a fallback for this situation.
app_path = Dir[File.join(BuildCommandGenerator.archive_path, "Products", "Applications", "*.app")].last
end
UI.crash!("Couldn't find application in '#{BuildCommandGenerator.archive_path}'") unless File.exist?(app_path)
joined_app_path = File.join(Gym.config[:output_directory], File.basename(app_path))
FileUtils.rm_rf(joined_app_path)
FileUtils.cp_r(app_path, File.expand_path(Gym.config[:output_directory]), remove_destination: true)
UI.success("Successfully exported the .app file:")
UI.message(joined_app_path)
joined_app_path
end
# Move the manifest.plist if exists into the output directory
def move_manifest
if File.exist?(PackageCommandGenerator.manifest_path)
FileUtils.mv(PackageCommandGenerator.manifest_path, File.expand_path(Gym.config[:output_directory]), force: true)
manifest_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.manifest_path))
UI.success("Successfully exported the manifest.plist file:")
UI.message(manifest_path)
manifest_path
end
end
# Move the app-thinning.plist file into the output directory
def move_app_thinning
if File.exist?(PackageCommandGenerator.app_thinning_path)
FileUtils.mv(PackageCommandGenerator.app_thinning_path, File.expand_path(Gym.config[:output_directory]), force: true)
app_thinning_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.app_thinning_path))
UI.success("Successfully exported the app-thinning.plist file:")
UI.message(app_thinning_path)
app_thinning_path
end
end
# Move the App Thinning Size Report.txt file into the output directory
def move_app_thinning_size_report
if File.exist?(PackageCommandGenerator.app_thinning_size_report_path)
FileUtils.mv(PackageCommandGenerator.app_thinning_size_report_path, File.expand_path(Gym.config[:output_directory]), force: true)
app_thinning_size_report_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.app_thinning_size_report_path))
UI.success("Successfully exported the App Thinning Size Report.txt file:")
UI.message(app_thinning_size_report_path)
app_thinning_size_report_path
end
end
# Move the Apps folder to the output directory
def move_apps_folder
if Dir.exist?(PackageCommandGenerator.apps_path)
FileUtils.mv(PackageCommandGenerator.apps_path, File.expand_path(Gym.config[:output_directory]), force: true)
apps_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.apps_path))
UI.success("Successfully exported Apps folder:")
UI.message(apps_path)
apps_path
end
end
# Move Asset Packs folder to the output directory
# @return (String) The path to the resulting Asset Packs (aka OnDemandResources) folder
def move_asset_packs
if Dir.exist?(PackageCommandGenerator.asset_packs_path)
FileUtils.mv(PackageCommandGenerator.asset_packs_path, File.expand_path(Gym.config[:output_directory]), force: true)
asset_packs_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.asset_packs_path))
UI.success("Successfully exported Asset Pack folder:")
UI.message(asset_packs_path)
asset_packs_path
end
end
# Move the AppStoreInfo.plist folder to the output directory
def move_appstore_info
if File.exist?(PackageCommandGenerator.appstore_info_path)
FileUtils.mv(PackageCommandGenerator.appstore_info_path, File.expand_path(Gym.config[:output_directory]), force: true)
appstore_info_path = File.join(File.expand_path(Gym.config[:output_directory]), File.basename(PackageCommandGenerator.appstore_info_path))
UI.success("Successfully exported the AppStoreInfo.plist file:")
UI.message(appstore_info_path)
appstore_info_path
end
end
# Create AppStoreInfo.plist using swinfo for iOS app-store exports
def generate_appstore_info(ipa_path)
return unless Gym.config[:generate_appstore_info] && Gym.building_for_ios? && Gym.config[:export_method] == 'app-store'
swinfo_plist_path = File.join(File.expand_path(Gym.config[:output_directory]), "AppStoreInfo.plist")
swinfo_path = File.join(FastlaneCore::Helper.xcode_path, "usr/bin/swinfo")
begin
UI.message("Generating AppStoreInfo.plist...")
# Build the swinfo command
command = [
"xcrun",
swinfo_path.shellescape,
"-f", ipa_path.shellescape,
"-o", swinfo_plist_path.shellescape,
"-prettyprint", "true",
"--plistFormat", "binary"
].join(" ")
FastlaneCore::CommandExecutor.execute(command: command, print_all: FastlaneCore::Globals.verbose?, print_command: true)
if File.exist?(swinfo_plist_path)
UI.success("Successfully generated AppStoreInfo.plist:")
UI.message(swinfo_plist_path)
swinfo_plist_path
else
UI.error("Failed to generate AppStoreInfo.plist")
end
rescue => ex
UI.error("Error generating AppStoreInfo.plist: #{ex}")
end
end
def find_archive_path
Dir.glob(File.join(BuildCommandGenerator.build_path, "*.ipa")).last
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/manager.rb | gym/lib/gym/manager.rb | require 'fastlane_core/print_table'
require_relative 'module'
require_relative 'runner'
module Gym
class Manager
def work(options)
Gym.config = options
# Also print out the path to the used Xcode installation
# We go 2 folders up, to not show "Contents/Developer/"
values = Gym.config.values(ask: false)
values[:xcode_path] = File.expand_path("../..", FastlaneCore::Helper.xcode_path)
FastlaneCore::PrintTable.print_values(config: values,
hide_keys: [],
title: "Summary for gym #{Fastlane::VERSION}")
return Runner.new.run
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/module.rb | gym/lib/gym/module.rb | require 'fastlane_core/helper'
require 'fastlane/boolean'
require_relative 'detect_values'
module Gym
class << self
attr_accessor :config
attr_accessor :project
attr_accessor :cache
def config=(value)
@config = value
DetectValues.set_additional_default_values
@cache = {}
end
def gymfile_name
"Gymfile"
end
def init_libs
# Import all the fixes
require 'gym/xcodebuild_fixes/generic_archive_fix'
end
def building_for_ipa?
return !building_for_pkg?
end
def building_for_pkg?
return building_for_mac?
end
def building_for_ios?
if Gym.project.mac?
# Can be building for iOS if mac project and catalyst or multiplatform and set to iOS
return building_mac_catalyst_for_ios? || building_multiplatform_for_ios?
else
# Can be iOS project and build for mac if catalyst
return false if building_mac_catalyst_for_mac?
# Can be iOS project if iOS, tvOS, watchOS, or visionOS
return Gym.project.ios? || Gym.project.tvos? || Gym.project.watchos? || Gym.project.visionos?
end
end
def building_for_mac?
if Gym.project.supports_mac_catalyst?
# Can be a mac project and not build mac if catalyst
return building_mac_catalyst_for_mac?
else
return (!Gym.project.multiplatform? && Gym.project.mac?) || building_multiplatform_for_mac?
end
end
def building_mac_catalyst_for_ios?
Gym.project.supports_mac_catalyst? && Gym.config[:catalyst_platform] == "ios"
end
def building_mac_catalyst_for_mac?
Gym.project.supports_mac_catalyst? && Gym.config[:catalyst_platform] == "macos"
end
def building_multiplatform_for_ios?
Gym.project.multiplatform? && Gym.project.ios? && (Gym.config[:sdk] == "iphoneos" || Gym.config[:sdk] == "iphonesimulator")
end
def building_multiplatform_for_mac?
Gym.project.multiplatform? && Gym.project.mac? && Gym.config[:sdk] == "macosx"
end
def export_destination_upload?
config_path = Gym.cache[:config_path]
return false if config_path.nil?
result = CFPropertyList.native_types(CFPropertyList::List.new(file: config_path).value)
return result["destination"] == "upload"
end
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__))
DESCRIPTION = "Building your iOS apps has never been easier"
Gym.init_libs
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/xcodebuild_fixes/generic_archive_fix.rb | gym/lib/gym/xcodebuild_fixes/generic_archive_fix.rb | require 'shellwords'
require_relative '../module'
require_relative '../generators/build_command_generator'
module Gym
class XcodebuildFixes
class << self
# Determine IPAs for the Watch App which aren't inside of a containing
# iOS App and removes them.
#
# In the future it may be nice to modify the plist file for the archive
# itself so that it points to the correct IPA as well.
#
# This is a workaround for this bug
# https://github.com/CocoaPods/CocoaPods/issues/4178
def generic_archive_fix
UI.verbose("Looking For Orphaned WatchKit2 Applications")
Dir.glob("#{BuildCommandGenerator.archive_path}/Products/Applications/*.app").each do |app_path|
if is_watchkit_app?(app_path)
UI.verbose("Removing Orphaned WatchKit2 Application #{app_path}")
FileUtils.rm_rf(app_path)
end
end
end
# Does this application have a WatchKit target
def is_watchkit_app?(app_path)
plist_path = "#{app_path}/Info.plist"
`/usr/libexec/PlistBuddy -c 'Print :DTSDKName' #{plist_path.shellescape} 2>&1`.match(/^\s*watchos2\.\d+\s*$/) != nil
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/generators/build_command_generator.rb | gym/lib/gym/generators/build_command_generator.rb | require 'shellwords'
require_relative '../module'
module Gym
# Responsible for building the fully working xcodebuild command
class BuildCommandGenerator
class << self
def generate
parts = prefix
parts << Gym.config[:xcodebuild_command]
parts += options
parts += buildactions
parts += setting
parts += pipe
parts
end
def prefix
["set -o pipefail &&"]
end
# Path to the project or workspace as parameter
# This will also include the scheme (if given)
# @return [Array] The array with all the components to join
def project_path_array
proj = Gym.project.xcodebuild_parameters
return proj if proj.count > 0
UI.user_error!("No project/workspace found")
end
def options
config = Gym.config
options = []
options += project_path_array
options << "-sdk '#{config[:sdk]}'" if config[:sdk]
options << "-toolchain '#{config[:toolchain]}'" if config[:toolchain]
options << "-destination '#{config[:destination]}'" if config[:destination]
options << "-archivePath #{archive_path.shellescape}" unless config[:skip_archive]
options << "-resultBundlePath '#{result_bundle_path}'" if config[:result_bundle]
options << "-showBuildTimingSummary" if config[:build_timing_summary]
if config[:use_system_scm] && !options.include?("-scmProvider system")
options << "-scmProvider system"
end
options << config[:xcargs] if config[:xcargs]
options << "OTHER_SWIFT_FLAGS=\"\\\$(value) -Xfrontend -debug-time-function-bodies\"" if config[:analyze_build_time]
options
end
def buildactions
config = Gym.config
buildactions = []
buildactions << :clean if config[:clean]
buildactions << :build if config[:skip_archive]
buildactions << :archive unless config[:skip_archive]
buildactions
end
def setting
setting = []
if Gym.config[:skip_codesigning]
setting << "CODE_SIGN_IDENTITY='' CODE_SIGNING_REQUIRED=NO CODE_SIGN_ENTITLEMENTS='' CODE_SIGNING_ALLOWED=NO"
elsif Gym.config[:codesigning_identity]
setting << "CODE_SIGN_IDENTITY=#{Gym.config[:codesigning_identity].shellescape}"
end
setting
end
def pipe
pipe = []
pipe << "| tee #{xcodebuild_log_path.shellescape}"
formatter = Gym.config[:xcodebuild_formatter].chomp
options = legacy_xcpretty_options
if Gym.config[:disable_xcpretty] || formatter == ''
UI.verbose("Not using an xcodebuild formatter")
elsif !options.empty?
UI.important("Detected legacy xcpretty being used, so formatting with xcpretty")
UI.important("Option(s) used: #{options.join(', ')}")
pipe += pipe_xcpretty
elsif formatter == 'xcpretty'
pipe += pipe_xcpretty
elsif formatter == 'xcbeautify'
pipe += pipe_xcbeautify
else
pipe << "| #{formatter}"
end
pipe << "> /dev/null" if Gym.config[:suppress_xcode_output]
pipe
end
def pipe_xcbeautify
pipe = ['| xcbeautify']
if FastlaneCore::Helper.colors_disabled?
pipe << '--disable-colored-output'
end
return pipe
end
def legacy_xcpretty_options
options = []
options << "xcpretty_test_format" if Gym.config[:xcpretty_test_format]
options << "xcpretty_formatter" if Gym.config[:xcpretty_formatter]
options << "xcpretty_report_junit" if Gym.config[:xcpretty_report_junit]
options << "xcpretty_report_html" if Gym.config[:xcpretty_report_html]
options << "xcpretty_report_json" if Gym.config[:xcpretty_report_json]
options << "xcpretty_utf" if Gym.config[:xcpretty_utf]
return options
end
def pipe_xcpretty
pipe = []
formatter = Gym.config[:xcpretty_formatter]
pipe << "| xcpretty"
pipe << " --test" if Gym.config[:xcpretty_test_format]
pipe << " --no-color" if Helper.colors_disabled?
pipe << " --formatter " if formatter
pipe << formatter if formatter
pipe << "--utf" if Gym.config[:xcpretty_utf]
report_output_junit = Gym.config[:xcpretty_report_junit]
report_output_html = Gym.config[:xcpretty_report_html]
report_output_json = Gym.config[:xcpretty_report_json]
if report_output_junit
pipe << " --report junit --output "
pipe << report_output_junit.shellescape
elsif report_output_html
pipe << " --report html --output "
pipe << report_output_html.shellescape
elsif report_output_json
pipe << " --report json-compilation-database --output "
pipe << report_output_json.shellescape
end
pipe
end
def post_build
commands = []
commands << %{grep -E '^[0-9.]+ms' #{xcodebuild_log_path.shellescape} | grep -vE '^0\.[0-9]' | sort -nr > culprits.txt} if Gym.config[:analyze_build_time]
commands
end
def xcodebuild_log_path
file_name = "#{Gym.project.app_name}-#{Gym.config[:scheme]}.log"
containing = File.expand_path(Gym.config[:buildlog_path])
FileUtils.mkdir_p(containing)
return File.join(containing, file_name)
end
# The path where archive will be created
def build_path
unless Gym.cache[:build_path]
Gym.cache[:build_path] = Gym.config[:build_path]
FileUtils.mkdir_p(Gym.cache[:build_path])
end
Gym.cache[:build_path]
end
def archive_path
Gym.cache[:archive_path] ||= Gym.config[:archive_path]
unless Gym.cache[:archive_path]
file_name = [Gym.config[:output_name], Time.now.strftime("%F %H.%M.%S")] # e.g. 2015-08-07 14.49.12
Gym.cache[:archive_path] = File.join(build_path, file_name.join(" ") + ".xcarchive")
end
if File.extname(Gym.cache[:archive_path]) != ".xcarchive"
Gym.cache[:archive_path] += ".xcarchive"
end
return Gym.cache[:archive_path]
end
def result_bundle_path
unless Gym.cache[:result_bundle_path]
path = Gym.config[:result_bundle_path]
path ||= File.join(Gym.config[:output_directory], Gym.config[:output_name] + ".xcresult")
if File.directory?(path)
FileUtils.remove_dir(path)
end
Gym.cache[:result_bundle_path] = path
end
return Gym.cache[:result_bundle_path]
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/generators/package_command_generator_xcode7.rb | gym/lib/gym/generators/package_command_generator_xcode7.rb | # encoding: utf-8
# from https://stackoverflow.com/a/9857493/445598
# because of
# `incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string) (Encoding::CompatibilityError)`
require 'addressable/uri'
require 'tempfile'
require 'xcodeproj'
require 'fastlane_core/core_ext/cfpropertylist'
require_relative '../module'
require_relative '../error_handler'
require_relative 'build_command_generator'
module Gym
# Responsible for building the fully working xcodebuild command
class PackageCommandGeneratorXcode7
class << self
DEFAULT_EXPORT_METHOD = "app-store"
def generate
parts = ["/usr/bin/xcrun #{wrap_xcodebuild.shellescape} -exportArchive"]
parts += options
parts += pipe
File.write(config_path, config_content) # overwrite every time. Could be optimized
parts
end
def options
config = Gym.config
options = []
options << "-exportOptionsPlist '#{config_path}'"
options << "-archivePath #{BuildCommandGenerator.archive_path.shellescape}"
options << "-exportPath '#{temporary_output_path}'"
options << "-toolchain '#{config[:toolchain]}'" if config[:toolchain]
options << config[:export_xcargs] if config[:export_xcargs]
options << config[:xcargs] if config[:xcargs]
options
end
def pipe
[""]
end
# We export the ipa into this directory, as we can't specify the ipa file directly
def temporary_output_path
Gym.cache[:temporary_output_path] ||= Dir.mktmpdir('gym_output')
end
# Wrap xcodebuild to work around ipatool dependency to system ruby
def wrap_xcodebuild
require 'fileutils'
@wrapped_xcodebuild_path ||= File.join(Gym::ROOT, "lib/assets/wrap_xcodebuild/xcbuild-safe.sh")
end
def ipa_path
path = Gym.cache[:ipa_path]
return path if path
path = Dir[File.join(temporary_output_path, "*.ipa")].last
# We need to process generic IPA
if path
# Try to find IPA file in the output directory, used when app thinning was not set
Gym.cache[:ipa_path] = File.join(temporary_output_path, "#{Gym.config[:output_name]}.ipa")
FileUtils.mv(path, Gym.cache[:ipa_path]) unless File.expand_path(path).casecmp?(File.expand_path(Gym.cache[:ipa_path]).downcase)
elsif Dir.exist?(apps_path)
# Try to find "generic" IPA file inside "Apps" folder, used when app thinning was set
files = Dir[File.join(apps_path, "*.ipa")]
# Generic IPA file doesn't have suffix so its name is the shortest
path = files.min_by(&:length)
Gym.cache[:ipa_path] = File.join(temporary_output_path, "#{Gym.config[:output_name]}.ipa")
FileUtils.cp(path, Gym.cache[:ipa_path]) unless File.expand_path(path).casecmp?(File.expand_path(Gym.cache[:ipa_path]).downcase)
else
ErrorHandler.handle_empty_ipa unless path
end
Gym.cache[:ipa_path]
end
def binary_path
path = Gym.cache[:binary_path]
return path if path
path = Dir[File.join(temporary_output_path, "*.pkg")].last
app_path = Dir[File.join(temporary_output_path, "*.app")].last
# We need to process generic PKG or APP
if path
# Try to find PKG file in the output directory, used when app thinning was not set
Gym.cache[:binary_path] = File.join(temporary_output_path, "#{Gym.config[:output_name]}.pkg")
FileUtils.mv(path, Gym.cache[:binary_path]) unless File.expand_path(path).casecmp(File.expand_path(Gym.cache[:binary_path]).downcase).zero?
elsif Dir.exist?(apps_path)
# Try to find "generic" PKG file inside "Apps" folder, used when app thinning was set
files = Dir[File.join(apps_path, "*.pkg")]
# Generic PKG file doesn't have suffix so its name is the shortest
path = files.min_by(&:length)
Gym.cache[:binary_path] = File.join(temporary_output_path, "#{Gym.config[:output_name]}.pkg")
FileUtils.cp(path, Gym.cache[:binary_path]) unless File.expand_path(path).casecmp(File.expand_path(Gym.cache[:binary_path]).downcase).zero?
elsif app_path
# Try to find .app file in the output directory. This is used when macOS is set and .app is being generated.
Gym.cache[:binary_path] = File.join(temporary_output_path, "#{Gym.config[:output_name]}.app")
FileUtils.mv(app_path, Gym.cache[:binary_path]) unless File.expand_path(app_path).casecmp(File.expand_path(Gym.cache[:binary_path]).downcase).zero?
else
ErrorHandler.handle_empty_pkg unless path
end
Gym.cache[:binary_path]
end
# The path of the dSYM file for this app. Might be nil
def dsym_path
Dir[BuildCommandGenerator.archive_path + "/**/*.app.dSYM"].last
end
# The path the config file we use to sign our app
def config_path
Gym.cache[:config_path] ||= "#{Tempfile.new('gym_config').path}.plist"
return Gym.cache[:config_path]
end
# The path to the manifest plist file
def manifest_path
Gym.cache[:manifest_path] ||= File.join(temporary_output_path, "manifest.plist")
end
# The path to the app-thinning plist file
def app_thinning_path
Gym.cache[:app_thinning] ||= File.join(temporary_output_path, "app-thinning.plist")
end
# The path to the App Thinning Size Report file
def app_thinning_size_report_path
Gym.cache[:app_thinning_size_report] ||= File.join(temporary_output_path, "App Thinning Size Report.txt")
end
# The path to the Apps folder
def apps_path
Gym.cache[:apps_path] ||= File.join(temporary_output_path, "Apps")
end
# The path to the Apps folder
def asset_packs_path
Gym.cache[:asset_packs_path] ||= File.join(temporary_output_path, "OnDemandResources")
end
def appstore_info_path
Gym.cache[:appstore_info_path] ||= File.join(temporary_output_path, "AppStoreInfo.plist")
end
private
def normalize_export_options(hash)
# Normalize some values
hash[:onDemandResourcesAssetPacksBaseURL] = Addressable::URI.encode(hash[:onDemandResourcesAssetPacksBaseURL]) if hash[:onDemandResourcesAssetPacksBaseURL]
if hash[:manifest]
hash[:manifest][:appURL] = Addressable::URI.encode(hash[:manifest][:appURL]) if hash[:manifest][:appURL]
hash[:manifest][:displayImageURL] = Addressable::URI.encode(hash[:manifest][:displayImageURL]) if hash[:manifest][:displayImageURL]
hash[:manifest][:fullSizeImageURL] = Addressable::URI.encode(hash[:manifest][:fullSizeImageURL]) if hash[:manifest][:fullSizeImageURL]
hash[:manifest][:assetPackManifestURL] = Addressable::URI.encode(hash[:manifest][:assetPackManifestURL]) if hash[:manifest][:assetPackManifestURL]
end
hash
end
def read_export_options
# Reads export options
if Gym.config[:export_options]
hash = normalize_export_options(Gym.config[:export_options])
# Saves configuration for later use
Gym.config[:export_method] ||= hash[:method] || DEFAULT_EXPORT_METHOD
Gym.config[:include_symbols] = hash[:uploadSymbols] if Gym.config[:include_symbols].nil?
Gym.config[:include_bitcode] = hash[:uploadBitcode] if Gym.config[:include_bitcode].nil?
Gym.config[:export_team_id] ||= hash[:teamID]
else
hash = {}
# Sets default values
Gym.config[:export_method] ||= DEFAULT_EXPORT_METHOD
Gym.config[:include_symbols] = true if Gym.config[:include_symbols].nil?
Gym.config[:include_bitcode] = false if Gym.config[:include_bitcode].nil?
end
hash
end
def config_content
hash = read_export_options
# Overrides export options if needed
hash[:method] = Gym.config[:export_method]
if Gym.config[:export_method] == 'app-store'
hash[:uploadSymbols] = (Gym.config[:include_symbols] ? true : false) unless Gym.config[:include_symbols].nil?
hash[:uploadBitcode] = (Gym.config[:include_bitcode] ? true : false) unless Gym.config[:include_bitcode].nil?
end
# xcodebuild will not use provisioning profiles
# if we don't specify signingStyle as manual
if Helper.xcode_at_least?("9.0") && hash[:provisioningProfiles]
hash[:signingStyle] = 'manual'
end
if Gym.config[:installer_cert_name] && (Gym.project.mac? || Gym.building_mac_catalyst_for_mac?)
hash[:installerSigningCertificate] = Gym.config[:installer_cert_name]
end
hash[:teamID] = Gym.config[:export_team_id] if Gym.config[:export_team_id]
UI.important("Generated plist file with the following values:")
UI.command_output("-----------------------------------------")
UI.command_output(JSON.pretty_generate(hash))
UI.command_output("-----------------------------------------")
if FastlaneCore::Globals.verbose?
UI.message("This results in the following plist file:")
UI.command_output("-----------------------------------------")
UI.command_output(hash.to_plist)
UI.command_output("-----------------------------------------")
end
hash.to_plist
end
def signing_style
projects = Gym.project.project_paths
project = projects.first
xcodeproj = Xcodeproj::Project.open(project)
xcodeproj.root_object.attributes["TargetAttributes"].each do |target, sett|
return sett["ProvisioningStyle"].to_s.downcase
end
rescue => e
UI.verbose(e.to_s)
UI.error("Unable to read provisioning style from .pbxproj file.")
return "automatic"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/gym/lib/gym/generators/package_command_generator.rb | gym/lib/gym/generators/package_command_generator.rb | # encoding: utf-8
# from https://stackoverflow.com/a/9857493/445598
# because of
# `incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string) (Encoding::CompatibilityError)`
require 'shellwords'
# The concrete implementations
require_relative 'package_command_generator_xcode7'
module Gym
class PackageCommandGenerator
class << self
def generate
generator.generate
end
def appfile_path
generator.appfile_path
end
# The path in which the ipa file will be available after executing the command
def ipa_path
generator.ipa_path
end
def pkg_path
generator.pkg_path
end
def binary_path
generator.binary_path
end
def dsym_path
generator.dsym_path
end
def manifest_path
generator.manifest_path
end
def app_thinning_path
generator.app_thinning_path
end
def app_thinning_size_report_path
generator.app_thinning_size_report_path
end
def apps_path
generator.apps_path
end
def asset_packs_path
generator.asset_packs_path
end
def appstore_info_path
generator.appstore_info_path
end
# The generator we need to use for the currently used Xcode version
# Since we dropped Xcode 6 support, it's just this class, but maybe we'll have
# new classes in the future
def generator
PackageCommandGeneratorXcode7
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/commands_generator_spec.rb | snapshot/spec/commands_generator_spec.rb | require 'snapshot/commands_generator'
require 'snapshot/reset_simulators'
describe Snapshot::CommandsGenerator do
let(:available_options) { Snapshot::Options.available_options }
describe ":run option handling" do
def expect_runner_work
allow(Snapshot::DetectValues).to receive(:set_additional_default_values)
allow(Snapshot::DependencyChecker).to receive(:check_simulators)
expect(Snapshot::Runner).to receive_message_chain(:new, :work)
end
it "can use the languages short flag from tool options" do
# leaving out the command name defaults to 'run'
stub_commander_runner_args(['-g', 'en-US,fr-FR'])
expect_runner_work
Snapshot::CommandsGenerator.start
expect(Snapshot.config[:languages]).to eq(['en-US', 'fr-FR'])
end
it "can use the output_directory flag from tool options" do
# leaving out the command name defaults to 'run'
stub_commander_runner_args(['--output_directory', 'output/dir'])
expect_runner_work
Snapshot::CommandsGenerator.start
expect(Snapshot.config[:output_directory]).to eq('output/dir')
end
end
describe ":reset_simulators option handling" do
it "can use the ios_version short flag", requires_xcodebuild: true do
stub_commander_runner_args(['reset_simulators', '-i', '9.3.5,10.0'])
allow(Snapshot::DetectValues).to receive(:set_additional_default_values)
expect(Snapshot::ResetSimulators).to receive(:clear_everything!).with(['9.3.5', '10.0'], nil)
Snapshot::CommandsGenerator.start
end
it "can use the ios_version flag", requires_xcodebuild: true do
stub_commander_runner_args(['reset_simulators', '--ios_version', '9.3.5,10.0'])
allow(Snapshot::DetectValues).to receive(:set_additional_default_values)
expect(Snapshot::ResetSimulators).to receive(:clear_everything!).with(['9.3.5', '10.0'], nil)
Snapshot::CommandsGenerator.start
end
it "can use the force flag", requires_xcodebuild: true do
stub_commander_runner_args(['reset_simulators', '--ios_version', '9.3.5,10.0', '--force'])
allow(Snapshot::DetectValues).to receive(:set_additional_default_values)
expect(Snapshot::ResetSimulators).to receive(:clear_everything!).with(['9.3.5', '10.0'], true)
Snapshot::CommandsGenerator.start
end
end
describe ":clear_derived_data option handling" do
def allow_path_check
allow(Snapshot::DetectValues).to receive(:set_additional_default_values)
allow(Dir).to receive(:exist?).with('data/path').and_return(false)
allow(Snapshot::UI).to receive(:important)
end
it "can use the output_directory short flag from tool options" do
stub_commander_runner_args(['clear_derived_data', '-f', 'data/path'])
allow_path_check
Snapshot::CommandsGenerator.start
expect(Snapshot.config[:derived_data_path]).to eq('data/path')
end
it "can use the output_directory flag from tool options" do
stub_commander_runner_args(['clear_derived_data', '--derived_data_path', 'data/path'])
allow_path_check
Snapshot::CommandsGenerator.start
expect(Snapshot.config[:derived_data_path]).to eq('data/path')
end
end
# :init and :update are not tested here because they do not use any options
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/test_command_generator_xcode_8_spec.rb | snapshot/spec/test_command_generator_xcode_8_spec.rb | describe Snapshot do
describe Snapshot::TestCommandGeneratorXcode8 do
let(:os_version) { "9.3" }
let(:iphone6_9_3) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6", os_version: os_version, udid: "11111", state: "Don't Care", is_simulator: true) }
let(:iphone6_9_3_2) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6s", os_version: os_version, udid: "22222", state: "Don't Care", is_simulator: true) }
let(:iphone6_9_0) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6", os_version: '9.0', udid: "11111", state: "Don't Care", is_simulator: true) }
let(:iphone6_9_2) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6", os_version: '9.2', udid: "11111", state: "Don't Care", is_simulator: true) }
let(:iphone6_10_1) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6 (10.1)", os_version: '10.1', udid: "33333", state: "Don't Care", is_simulator: true) }
let(:iphone6s_10_1) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6s (10.1)", os_version: '10.1', udid: "98765", state: "Don't Care", is_simulator: true) }
let(:iphone4s_9_0) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 4s", os_version: '9.0', udid: "4444", state: "Don't Care", is_simulator: true) }
let(:iphone8_9_1) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 8", os_version: '9.1', udid: "55555", state: "Don't Care", is_simulator: true) }
let(:ipad_air_9_1) { FastlaneCore::DeviceManager::Device.new(name: "iPad Air (4th generation)", os_version: '9.1', udid: "12345", state: "Don't Care", is_simulator: true) }
let(:appleTV) { FastlaneCore::DeviceManager::Device.new(name: "Apple TV 1080p", os_version: os_version, udid: "22222", state: "Don't Care", is_simulator: true) }
before do
allow(Snapshot::LatestOsVersion).to receive(:version).and_return(os_version)
allow(FastlaneCore::DeviceManager).to receive(:simulators).and_return([iphone6_9_0, iphone6_9_3, iphone6_9_2, appleTV, iphone6_9_3_2, iphone6_10_1, iphone6s_10_1, iphone4s_9_0, iphone8_9_1, ipad_air_9_1])
fake_out_xcode_project_loading
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false)
end
describe '#destination' do
it "returns the highest version available for device if no match for the specified/latest os_version" do
allow(Snapshot).to receive(:config).and_return({ ios_version: os_version })
device = "iPhone 4s"
result = Snapshot::TestCommandGeneratorXcode8.destination(device)
expect(result).to eq(["-destination 'platform=iOS Simulator,id=4444,OS=9.0'"])
end
end
describe '#find_device' do
it 'finds a device that has a matching name and OS version' do
found = Snapshot::TestCommandGeneratorXcode8.find_device('iPhone 6', '9.0')
expect(found).to eq(iphone6_9_0)
end
it 'does not find a device that has a different name' do
found = Snapshot::TestCommandGeneratorXcode8.find_device('iPhone 5', '9.0')
expect(found).to be(nil)
end
it 'finds a device with the same name, but a different OS version, picking the highest available OS version' do
found = Snapshot::TestCommandGeneratorXcode8.find_device('iPhone 6', '10.0')
expect(found).to be(iphone6_9_3)
end
end
describe 'copy_simulator_logs' do
before (:each) do
@config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, {
output_directory: '/tmp/scan_results',
output_simulator_logs: true,
devices: ['iPhone 6 (10.1)', 'iPhone 6s'],
project: './snapshot/example/Example.xcodeproj',
scheme: 'ExampleUITests',
namespace_log_files: true
})
end
it 'copies all device log archives to the output directory on macOS 10.12 (Sierra)', requires_xcode: true do
Snapshot.config = @config
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: Snapshot.config)
allow(FastlaneCore::CommandExecutor).
to receive(:execute).
with(command: "sw_vers -productVersion", print_all: false, print_command: false).
and_return('10.12.1')
expect(FastlaneCore::CommandExecutor).
to receive(:execute).
with(command: %r{xcrun simctl spawn 33333 log collect --start '\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d' --output /tmp/scan_results/de-DE/system_logs-cfcd208495d565ef66e7dff9f98764da.logarchive 2>/dev/null}, print_all: false, print_command: true)
expect(FastlaneCore::CommandExecutor).
to receive(:execute).
with(command: %r{xcrun simctl spawn 98765 log collect --start '\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d' --output /tmp/scan_results/en-US/system_logs-cfcd208495d565ef66e7dff9f98764da.logarchive 2>/dev/null}, print_all: false, print_command: true)
Snapshot::SimulatorLauncherXcode8.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 6 (10.1)"], "de-DE", nil, 0)
Snapshot::SimulatorLauncherXcode8.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 6s (10.1)"], "en-US", nil, 0)
end
it 'copies all iOS 9 device log files to the output directory on macOS 10.12 (Sierra)', requires_xcode: true do
Snapshot.config = @config
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: Snapshot.config)
allow(File).to receive(:exist?).with(/.*system\.log/).and_return(true)
allow(FastlaneCore::CommandExecutor).to receive(:execute).with(command: "sw_vers -productVersion", print_all: false, print_command: false).and_return('10.12')
expect(FileUtils).to receive(:rm_f).with(%r{#{Snapshot.config[:output_directory]}/de-DE/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:cp).with(/.*/, %r{#{Snapshot.config[:output_directory]}/de-DE/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:rm_f).with(%r{#{Snapshot.config[:output_directory]}/en-US/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:cp).with(/.*/, %r{#{Snapshot.config[:output_directory]}/en-US/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
Snapshot::SimulatorLauncherXcode8.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 6s"], "de-DE", nil, 0)
Snapshot::SimulatorLauncherXcode8.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 6"], "en-US", nil, 0)
end
it 'copies all device log files to the output directory on macOS 10.11 (El Capitan)', requires_xcode: true do
Snapshot.config = @config
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: Snapshot.config)
allow(File).to receive(:exist?).with(/.*system\.log/).and_return(true)
allow(FastlaneCore::CommandExecutor).to receive(:execute).with(command: "sw_vers -productVersion", print_all: false, print_command: false).and_return('10.11.6')
expect(FileUtils).to receive(:rm_f).with(%r{#{Snapshot.config[:output_directory]}/de-DE/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:cp).with(/.*/, %r{#{Snapshot.config[:output_directory]}/de-DE/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:rm_f).with(%r{#{Snapshot.config[:output_directory]}/en-US/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:cp).with(/.*/, %r{#{Snapshot.config[:output_directory]}/en-US/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
Snapshot::SimulatorLauncherXcode8.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 6s"], "de-DE", nil, 0)
Snapshot::SimulatorLauncherXcode8.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPad Air (4th generation)"], "en-US", nil, 0)
end
end
describe "Valid iOS Configuration" do
let(:options) { { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", namespace_log_files: true } }
def configure(options)
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
end
context 'default options' do
it "uses the default parameters", requires_xcode: true do
configure(options)
expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
command = Snapshot::TestCommandGeneratorXcode8.generate(device_type: "iPhone 8", language: "en", locale: nil)
id = command.join('').match(/id=(.+?),/)[1]
ios = command.join('').match(/OS=(\d+.\d+)/)[1]
expect(command).to eq(
[
"set -o pipefail &&",
"xcodebuild",
"-scheme ExampleUITests",
"-project ./snapshot/example/Example.xcodeproj",
"-derivedDataPath /tmp/path/to/snapshot_derived",
"-destination 'platform=iOS Simulator,id=#{id},OS=#{ios}'",
"FASTLANE_SNAPSHOT=YES",
"FASTLANE_LANGUAGE=en",
:build,
:test,
"| tee #{File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests-iPhone\\ 8-en.log")}",
"| xcpretty "
]
)
end
it "allows to supply custom xcargs", requires_xcode: true do
configure(options.merge(xcargs: "-only-testing:TestBundle/TestSuite/Screenshots"))
expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
command = Snapshot::TestCommandGeneratorXcode8.generate(device_type: "iPhone 6", language: "en", locale: nil)
id = command.join('').match(/id=(.+?),/)[1]
ios = command.join('').match(/OS=(\d+.\d+)/)[1]
expect(command).to eq(
[
"set -o pipefail &&",
"xcodebuild",
"-scheme ExampleUITests",
"-project ./snapshot/example/Example.xcodeproj",
"-derivedDataPath /tmp/path/to/snapshot_derived",
"-only-testing:TestBundle/TestSuite/Screenshots",
"-destination 'platform=iOS Simulator,id=#{id},OS=#{ios}'",
"FASTLANE_SNAPSHOT=YES",
"FASTLANE_LANGUAGE=en",
:build,
:test,
"| tee #{File.expand_path('~/Library/Logs/snapshot/Example-ExampleUITests-iPhone\\ 6-en.log')}",
"| xcpretty "
]
)
end
it "uses the default parameters on tvOS too", requires_xcode: true do
configure(options.merge(devices: ["Apple TV 1080p"]))
expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
command = Snapshot::TestCommandGeneratorXcode8.generate(device_type: "Apple TV 1080p", language: "en", locale: nil)
id = command.join('').match(/id=(.+?),/)[1]
os = command.join('').match(/OS=(\d+.\d+)/)[1]
expect(command).to eq(
[
"set -o pipefail &&",
"xcodebuild",
"-scheme ExampleUITests",
"-project ./snapshot/example/Example.xcodeproj",
"-derivedDataPath /tmp/path/to/snapshot_derived",
"-destination 'platform=tvOS Simulator,id=#{id},OS=#{os}'",
"FASTLANE_SNAPSHOT=YES",
"FASTLANE_LANGUAGE=en",
:build,
:test,
"| tee #{File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests-Apple\\ TV\\ 1080p-en.log")}",
"| xcpretty "
]
)
end
end
context 'fixed derivedDataPath' do
let(:temp) { Dir.mktmpdir }
before do
configure(options.merge(derived_data_path: temp))
end
it 'uses the fixed derivedDataPath if given', requires_xcode: true do
expect(Dir).not_to(receive(:mktmpdir))
command = Snapshot::TestCommandGeneratorXcode8.generate(device_type: "iPhone 8", language: "en", locale: nil)
expect(command.join('')).to include("-derivedDataPath #{temp}")
end
end
context "disable_xcpretty" do
it "does not include xcpretty in the pipe command when true", requires_xcode: true do
configure(options.merge(disable_xcpretty: true))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to_not(include("| xcpretty "))
end
it "includes xcpretty in the pipe command when false", requires_xcode: true do
configure(options.merge(disable_xcpretty: false))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("| xcpretty ")
end
end
context "suppress_xcode_output" do
it "includes /dev/null in the pipe command when true", requires_xcode: true do
configure(options.merge(suppress_xcode_output: true))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("> /dev/null")
end
it "does not include /dev/null in the pipe command when false", requires_xcode: true do
configure(options.merge(suppress_xcode_output: false))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to_not(include("> /dev/null"))
end
end
end
describe "Valid macOS Configuration" do
let(:options) { { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleMacOS", namespace_log_files: true } }
it "uses default parameters on macOS", requires_xcode: true do
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options.merge(devices: ["Mac"]))
expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
command = Snapshot::TestCommandGeneratorXcode8.generate(device_type: "Mac", language: "en", locale: nil)
expect(command).to eq(
[
"set -o pipefail &&",
"xcodebuild",
"-scheme ExampleMacOS",
"-project ./snapshot/example/Example.xcodeproj",
"-derivedDataPath /tmp/path/to/snapshot_derived",
"-destination 'platform=macOS'",
"FASTLANE_SNAPSHOT=YES",
"FASTLANE_LANGUAGE=en",
:build,
:test,
"| tee #{File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/ExampleMacOS-ExampleMacOS-Mac-en.log")}",
"| xcpretty "
]
)
end
end
describe "Unique logs" do
let(:options) { { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", namespace_log_files: true } }
it 'uses correct name and language', requires_xcode: true do
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
log_path = Snapshot::TestCommandGeneratorXcode8.xcodebuild_log_path(device_type: "iPhone 8", language: "pt", locale: nil)
expect(log_path).to eq(
File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests-iPhone 8-pt.log").to_s
)
end
it 'uses includes locale if specified', requires_xcode: true do
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
log_path = Snapshot::TestCommandGeneratorXcode8.xcodebuild_log_path(device_type: "iPhone 8", language: "pt", locale: "pt_BR")
expect(log_path).to eq(
File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests-iPhone 8-pt-pt_BR.log").to_s
)
end
it 'can work without parameters', requires_xcode: true do
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
log_path = Snapshot::TestCommandGeneratorXcode8.xcodebuild_log_path
expect(log_path).to eq(
File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests.log").to_s
)
end
end
describe "Unique logs disabled" do
let(:options) { { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests" } }
it 'uses correct file name', requires_xcode: true do
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
log_path = Snapshot::TestCommandGeneratorXcode8.xcodebuild_log_path(device_type: "iPhone 8", language: "pt", locale: nil)
expect(log_path).to eq(
File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests.log").to_s
)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/collector_spec.rb | snapshot/spec/collector_spec.rb | describe Snapshot do
describe Snapshot::Collector do
describe '#attachments_in_file for Xcode 7.2.1 plist output' do
it 'finds attachments and returns filenames' do
expected_files = [
"Screenshot_658CD3E2-96C5-4598-86EF-18164AEDE71D.png",
"Screenshot_31FC792E-A9E9-4C04-A31D-9901EC425CD9.png",
"Screenshot_AE21B4B1-6C45-44A2-BDF6-A30A33735688.png",
"Screenshot_0B17C04E-5ED1-4667-AF31-EFDDCAC71EDB.png"
]
expect(Snapshot::Collector.attachments_in_file('snapshot/spec/fixtures/Xcode-7_2_1-TestSummaries.plist')).to contain_exactly(*expected_files)
end
end
describe '#attachments_in_file for Xcode 7.3 plist output' do
it 'finds attachments and returns filenames' do
expected_files = [
"Screenshot_75B3F0C3-BF0E-44D5-B26E-222B63B1D815.png",
"Screenshot_AE111D6A-15D7-4B35-A802-0E4481F6143F.png",
"Screenshot_75352671-22A3-4DAF-BCFA-D0DFF5EBFE2C.png",
"Screenshot_8752EB61-7EAB-4908-AD6D-A4973E40E9CB.png"
]
expect(Snapshot::Collector.attachments_in_file('snapshot/spec/fixtures/Xcode-7_3-TestSummaries.plist')).to contain_exactly(*expected_files)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/test_command_generator_spec.rb | snapshot/spec/test_command_generator_spec.rb | require 'tmpdir'
describe Snapshot do
describe Snapshot::TestCommandGenerator do
let(:os_version) { "9.3" }
let(:iphone6_9_3) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6", os_version: os_version, udid: "11111", state: "Don't Care", is_simulator: true) }
let(:iphone6_9_3_2) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6s", os_version: os_version, udid: "22222", state: "Don't Care", is_simulator: true) }
let(:iphone6_9_0) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6", os_version: '9.0', udid: "11111", state: "Don't Care", is_simulator: true) }
let(:iphone6_9_2) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6", os_version: '9.2', udid: "11111", state: "Don't Care", is_simulator: true) }
let(:iphone6_10_1) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6 (10.1)", os_version: '10.1', udid: "33333", state: "Don't Care", is_simulator: true) }
let(:iphone6s_10_1) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 6s (10.1)", os_version: '10.1', udid: "98765", state: "Don't Care", is_simulator: true) }
let(:iphone4s_9_0) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 4s", os_version: '9.0', udid: "4444", state: "Don't Care", is_simulator: true) }
let(:iphone8_9_1) { FastlaneCore::DeviceManager::Device.new(name: "iPhone 8", os_version: '9.1', udid: "55555", state: "Don't Care", is_simulator: true) }
let(:ipad_air_9_1) { FastlaneCore::DeviceManager::Device.new(name: "iPad Air (4th generation)", os_version: '9.1', udid: "12345", state: "Don't Care", is_simulator: true) }
let(:appleTV) { FastlaneCore::DeviceManager::Device.new(name: "Apple TV 1080p", os_version: os_version, udid: "22222", state: "Don't Care", is_simulator: true) }
let(:appleWatch6_44mm_7_4) { FastlaneCore::DeviceManager::Device.new(name: "Apple Watch Series 6 - 44mm", os_version: '7.4', udid: "5555544", state: "Don't Care", is_simulator: true) }
before do
allow(Snapshot::LatestOsVersion).to receive(:version).and_return(os_version)
allow(FastlaneCore::DeviceManager).to receive(:simulators).and_return([iphone6_9_0, iphone6_9_3, iphone6_9_2, appleTV, iphone6_9_3_2, iphone6_10_1, iphone6s_10_1, iphone4s_9_0, iphone8_9_1, ipad_air_9_1, appleWatch6_44mm_7_4])
fake_out_xcode_project_loading
end
context "with xcpretty" do
before(:each) do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false)
end
describe '#destination' do
it "returns the highest version available for device if no match for the specified/latest os_version" do
allow(Snapshot).to receive(:config).and_return({ ios_version: os_version })
devices = ["iPhone 4s", "iPhone 6", "iPhone 6s"]
result = Snapshot::TestCommandGenerator.destination(devices)
expect(result).to eq([[
"-destination 'platform=iOS Simulator,name=iPhone 4s,OS=9.0'",
"-destination 'platform=iOS Simulator,name=iPhone 6,OS=9.3'",
"-destination 'platform=iOS Simulator,name=iPhone 6s,OS=9.3'"
].join(' ')])
end
end
describe '#verify_devices_share_os' do
before(:each) do
@test_command_generator = Snapshot::TestCommandGenerator.new
end
it "returns true with only iOS devices" do
devices = ["iPhone 8", "iPad Air 2", "iPhone X", "iPhone 8 plus", "iPod touch (7th generation)"]
result = Snapshot::TestCommandGenerator.verify_devices_share_os(devices)
expect(result).to be(true)
end
it "returns true with only Apple TV devices" do
devices = ["Apple TV 1080p", "Apple TV 4K", "Apple TV 4K (at 1080p)"]
result = Snapshot::TestCommandGenerator.verify_devices_share_os(devices)
expect(result).to be(true)
end
it "returns true with only Apple Watch devices" do
devices = ["Apple Watch Series 6 - 44mm"]
result = Snapshot::TestCommandGenerator.verify_devices_share_os(devices)
expect(result).to be(true)
end
it "returns false with mixed device OS of Apple TV and iPhone" do
devices = ["Apple TV 1080p", "iPhone 8"]
result = Snapshot::TestCommandGenerator.verify_devices_share_os(devices)
expect(result).to be(false)
end
it "returns false with mixed device OS of Apple Watch and iPhone" do
devices = ["Apple Watch Series 6 - 44mm", "iPhone 8"]
result = Snapshot::TestCommandGenerator.verify_devices_share_os(devices)
expect(result).to be(false)
end
it "returns false with mixed device OS of Apple TV and iPad" do
devices = ["Apple TV 1080p", "iPad Air 2"]
result = Snapshot::TestCommandGenerator.verify_devices_share_os(devices)
expect(result).to be(false)
end
it "returns false with mixed device OS of Apple TV and iPod" do
devices = ["Apple TV 1080p", "iPod touch (7th generation)"]
result = Snapshot::TestCommandGenerator.verify_devices_share_os(devices)
expect(result).to be(false)
end
it "returns true with custom named iOS devices" do
devices = ["11.0 - iPhone X", "11.0 - iPad Air 2", "13.0 - iPod touch"]
result = Snapshot::TestCommandGenerator.verify_devices_share_os(devices)
expect(result).to be(true)
end
it "returns true with custom named Apple TV devices" do
devices = ["11.0 - Apple TV 1080p", "11.0 - Apple TV 4K", "11.0 - Apple TV 4K (at 1080p)"]
result = Snapshot::TestCommandGenerator.verify_devices_share_os(devices)
expect(result).to be(true)
end
end
describe '#find_device' do
it 'finds a device that has a matching name and OS version' do
found = Snapshot::TestCommandGenerator.find_device('iPhone 8', '9.0')
expect(found).to eq(iphone8_9_1)
end
it 'does not find a device that has a different name' do
found = Snapshot::TestCommandGenerator.find_device('iPhone 5', '9.0')
expect(found).to be(nil)
end
it 'finds a device with the same name, but a different OS version, picking the highest available OS version' do
found = Snapshot::TestCommandGenerator.find_device('iPhone 8', '10.0')
expect(found).to eq(iphone8_9_1)
end
end
describe 'copy_simulator_logs' do
before (:each) do
@config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, {
output_directory: '/tmp/scan_results',
output_simulator_logs: true,
devices: ['iPhone 6 (10.1)', 'iPhone 6s'],
project: './snapshot/example/Example.xcodeproj',
scheme: 'ExampleUITests',
namespace_log_files: true
})
end
it 'copies all device log archives to the output directory on macOS 10.12 (Sierra)', requires_xcode: true do
Snapshot.config = @config
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: Snapshot.config)
allow(FastlaneCore::CommandExecutor).
to receive(:execute).
with(command: "sw_vers -productVersion", print_all: false, print_command: false).
and_return('10.12.1')
expect(FastlaneCore::CommandExecutor).
to receive(:execute).
with(command: %r{xcrun simctl spawn 33333 log collect --start '\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d' --output /tmp/scan_results/de-DE/system_logs-cfcd208495d565ef66e7dff9f98764da.logarchive 2>/dev/null}, print_all: false, print_command: true)
expect(FastlaneCore::CommandExecutor).
to receive(:execute).
with(command: %r{xcrun simctl spawn 98765 log collect --start '\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d' --output /tmp/scan_results/en-US/system_logs-cfcd208495d565ef66e7dff9f98764da.logarchive 2>/dev/null}, print_all: false, print_command: true)
Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 6 (10.1)"], "de-DE", nil, 0)
Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 6s (10.1)"], "en-US", nil, 0)
end
it 'copies all iOS 9 device log files to the output directory on macOS 10.12 (Sierra)', requires_xcode: true do
Snapshot.config = @config
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: Snapshot.config)
allow(File).to receive(:exist?).with(/.*system\.log/).and_return(true)
allow(FastlaneCore::CommandExecutor).to receive(:execute).with(command: "sw_vers -productVersion", print_all: false, print_command: false).and_return('10.12')
expect(FileUtils).to receive(:rm_f).with(%r{#{Snapshot.config[:output_directory]}/de-DE/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:cp).with(/.*/, %r{#{Snapshot.config[:output_directory]}/de-DE/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:rm_f).with(%r{#{Snapshot.config[:output_directory]}/en-US/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:cp).with(/.*/, %r{#{Snapshot.config[:output_directory]}/en-US/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 6s"], "de-DE", nil, 0)
Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 6"], "en-US", nil, 0)
end
it 'copies all device log files to the output directory on macOS 10.11 (El Capitan)', requires_xcode: true do
Snapshot.config = @config
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: Snapshot.config)
allow(File).to receive(:exist?).with(/.*system\.log/).and_return(true)
allow(FastlaneCore::CommandExecutor).to receive(:execute).with(command: "sw_vers -productVersion", print_all: false, print_command: false).and_return('10.11.6')
expect(FileUtils).to receive(:rm_f).with(%r{#{Snapshot.config[:output_directory]}/de-DE/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:cp).with(/.*/, %r{#{Snapshot.config[:output_directory]}/de-DE/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:rm_f).with(%r{#{Snapshot.config[:output_directory]}/en-US/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
expect(FileUtils).to receive(:cp).with(/.*/, %r{#{Snapshot.config[:output_directory]}/en-US/system-cfcd208495d565ef66e7dff9f98764da\.log}).and_return(true)
Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPhone 8"], "de-DE", nil, 0)
Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config).copy_simulator_logs(["iPad Air (4th generation)"], "en-US", nil, 0)
end
end
describe "Valid iOS Configuration" do
let(:options) { { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", namespace_log_files: true } }
def configure(options)
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
end
context 'default options' do
it "uses the default parameters", requires_xcode: true do
configure(options)
expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
command = Snapshot::TestCommandGenerator.generate(
devices: ["iPhone 8"],
language: "en",
locale: nil,
log_path: '/path/to/logs'
)
name = command.join('').match(/name=(.+?),/)[1]
ios = command.join('').match(/OS=(\d+.\d+)/)[1]
expect(command).to eq(
[
"set -o pipefail &&",
"xcodebuild",
"-scheme ExampleUITests",
"-project ./snapshot/example/Example.xcodeproj",
"-derivedDataPath /tmp/path/to/snapshot_derived",
"-destination 'platform=iOS Simulator,name=#{name},OS=#{ios}'",
"FASTLANE_SNAPSHOT=YES",
"FASTLANE_LANGUAGE=en",
:build,
:test,
"| tee /path/to/logs",
"| xcpretty "
]
)
end
it "allows to supply custom xcargs", requires_xcode: true do
configure(options.merge(xcargs: "-only-testing:TestBundle/TestSuite/Screenshots"))
expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
command = Snapshot::TestCommandGenerator.generate(
devices: ["iPhone 8"],
language: "en",
locale: nil,
log_path: '/path/to/logs'
)
name = command.join('').match(/name=(.+?),/)[1]
ios = command.join('').match(/OS=(\d+.\d+)/)[1]
expect(command).to eq(
[
"set -o pipefail &&",
"xcodebuild",
"-scheme ExampleUITests",
"-project ./snapshot/example/Example.xcodeproj",
"-derivedDataPath /tmp/path/to/snapshot_derived",
"-only-testing:TestBundle/TestSuite/Screenshots",
"-destination 'platform=iOS Simulator,name=#{name},OS=#{ios}'",
"FASTLANE_SNAPSHOT=YES",
"FASTLANE_LANGUAGE=en",
:build,
:test,
"| tee /path/to/logs",
"| xcpretty "
]
)
end
it "uses the default parameters on tvOS too", requires_xcode: true do
configure(options.merge(devices: ["Apple TV 1080p"]))
expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
command = Snapshot::TestCommandGenerator.generate(
devices: ["Apple TV 1080p"],
language: "en",
locale: nil,
log_path: '/path/to/logs'
)
name = command.join('').match(/name=(.+?),/)[1]
os = command.join('').match(/OS=(\d+.\d+)/)[1]
expect(command).to eq(
[
"set -o pipefail &&",
"xcodebuild",
"-scheme ExampleUITests",
"-project ./snapshot/example/Example.xcodeproj",
"-derivedDataPath /tmp/path/to/snapshot_derived",
"-destination 'platform=tvOS Simulator,name=#{name},OS=#{os}'",
"FASTLANE_SNAPSHOT=YES",
"FASTLANE_LANGUAGE=en",
:build,
:test,
"| tee /path/to/logs",
"| xcpretty "
]
)
end
it "uses the default parameters on watchOS too", requires_xcode: true do
configure(options.merge(devices: ["Apple Watch Series 6 - 44mm"]))
expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
command = Snapshot::TestCommandGenerator.generate(
devices: ["Apple Watch Series 6 - 44mm"],
language: "en",
locale: nil,
log_path: '/path/to/logs'
)
name = command.join('').match(/name=(.+?),/)[1]
os = command.join('').match(/OS=(\d+.\d+)/)[1]
expect(command).to eq(
[
"set -o pipefail &&",
"xcodebuild",
"-scheme ExampleUITests",
"-project ./snapshot/example/Example.xcodeproj",
"-derivedDataPath /tmp/path/to/snapshot_derived",
"-destination 'platform=watchOS Simulator,name=#{name},OS=#{os}'",
"FASTLANE_SNAPSHOT=YES",
"FASTLANE_LANGUAGE=en",
:build,
:test,
"| tee /path/to/logs",
"| xcpretty "
]
)
end
end
context 'fixed derivedDataPath' do
let(:temp) { Dir.mktmpdir }
before do
configure(options.merge(derived_data_path: temp))
end
it 'uses the fixed derivedDataPath if given', requires_xcode: true do
expect(Dir).not_to(receive(:mktmpdir))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("-derivedDataPath #{temp}")
end
end
context 'test-without-building' do
let(:temp) { Dir.mktmpdir }
before do
configure(options.merge(derived_data_path: temp, test_without_building: true))
end
it 'uses the "test-without-building" command and not the default "build test"', requires_xcode: true do
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("test-without-building")
expect(command.join('')).not_to(include("build test"))
end
end
context 'test-plan' do
it 'adds the testplan to the xcodebuild command', requires_xcode: true do
configure(options.merge(testplan: 'simple'))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("-testPlan 'simple'") if FastlaneCore::Helper.xcode_at_least?(11)
end
end
context "only-testing" do
it "only tests the test bundle/suite/cases specified in only_testing when the input is an array", requires_xcode: true do
configure(options.merge(only_testing: %w(TestBundleA/TestSuiteB TestBundleC)))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("-only-testing:TestBundleA/TestSuiteB")
expect(command.join('')).to include("-only-testing:TestBundleC")
end
it "only tests the test bundle/suite/cases specified in only_testing when the input is a string", requires_xcode: true do
configure(options.merge(only_testing: 'TestBundleA/TestSuiteB'))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("-only-testing:TestBundleA/TestSuiteB")
expect(command.join('')).not_to(include("-only-testing:TestBundleC"))
end
end
context "skip-testing" do
it "does not test the test bundle/suite/cases specified in skip_testing when the input is an array", requires_xcode: true do
configure(options.merge(skip_testing: %w(TestBundleA/TestSuiteB TestBundleC)))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("-skip-testing:TestBundleA/TestSuiteB")
expect(command.join('')).to include("-skip-testing:TestBundleC")
end
it "does not test the test bundle/suite/cases specified in skip_testing when the input is a string", requires_xcode: true do
configure(options.merge(skip_testing: 'TestBundleA/TestSuiteB'))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("-skip-testing:TestBundleA/TestSuiteB")
expect(command.join('')).not_to(include("-skip-testing:TestBundleC"))
end
end
context "disable_xcpretty" do
it "does not include xcpretty in the pipe command when true", requires_xcode: true do
configure(options.merge(disable_xcpretty: true))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to_not(include("| xcpretty "))
end
it "includes xcpretty in the pipe command when false", requires_xcode: true do
configure(options.merge(disable_xcpretty: false))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("| xcpretty ")
end
end
context "suppress_xcode_output" do
it "includes /dev/null in the pipe command when true", requires_xcode: true do
configure(options.merge(suppress_xcode_output: true))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to include("> /dev/null")
end
it "does not include /dev/null in the pipe command when false", requires_xcode: true do
configure(options.merge(suppress_xcode_output: false))
command = Snapshot::TestCommandGenerator.generate(devices: ["iPhone 8"], language: "en", locale: nil)
expect(command.join('')).to_not(include("> /dev/null"))
end
end
end
describe "Valid macOS Configuration" do
let(:options) { { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleMacOS", namespace_log_files: true } }
it "uses default parameters on macOS", requires_xcode: true do
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options.merge(devices: ["Mac"]))
expect(Dir).to receive(:mktmpdir).with("snapshot_derived").and_return("/tmp/path/to/snapshot_derived")
command = Snapshot::TestCommandGenerator.generate(
devices: ["Mac"],
language: "en",
locale: nil,
log_path: '/path/to/logs'
)
expect(command).to eq(
[
"set -o pipefail &&",
"xcodebuild",
"-scheme ExampleMacOS",
"-project ./snapshot/example/Example.xcodeproj",
"-derivedDataPath /tmp/path/to/snapshot_derived",
"-destination 'platform=macOS'",
"FASTLANE_SNAPSHOT=YES",
"FASTLANE_LANGUAGE=en",
:build,
:test,
"| tee /path/to/logs",
"| xcpretty "
]
)
end
end
describe "Unique logs" do
let(:options) { { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", namespace_log_files: true } }
let(:simulator_launcher) do
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: Snapshot.config)
launcher_config.devices = ["iPhone 8"]
return simulator_launcher = Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config)
end
it 'uses correct name and language', requires_xcode: true do
log_path = simulator_launcher.xcodebuild_log_path(language: "pt", locale: nil)
expect(log_path).to eq(
File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests-iPhone 8-pt.log").to_s
)
end
it 'uses includes locale if specified', requires_xcode: true do
log_path = simulator_launcher.xcodebuild_log_path(language: "pt", locale: "pt_BR")
expect(log_path).to eq(
File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests-iPhone 8-pt-pt_BR.log").to_s
)
end
it 'can work without parameters', requires_xcode: true do
simulator_launcher.launcher_config.devices = []
log_path = simulator_launcher.xcodebuild_log_path
expect(log_path).to eq(
File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests.log").to_s
)
end
end
describe "Unique logs disabled" do
let(:options) { { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests" } }
let(:simulator_launcher) do
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: Snapshot.config)
launcher_config.devices = ["iPhone 8"]
return simulator_launcher = Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config)
end
it 'uses correct file name', requires_xcode: true do
log_path = simulator_launcher.xcodebuild_log_path(language: "pt", locale: nil)
expect(log_path).to eq(
File.expand_path("#{FastlaneCore::Helper.buildlog_path}/snapshot/Example-ExampleUITests.log").to_s
)
end
end
end
describe "#pipe" do
it "uses no pipe with disable_xcpretty", requires_xcodebuild: true do
options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", disable_xcpretty: true }
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
pipe = Snapshot::TestCommandGenerator.pipe.join(" ")
expect(pipe).not_to include("| xcpretty")
expect(pipe).not_to include("| xcbeautify")
end
it "uses no pipe with xcodebuild_formatter with empty string", requires_xcodebuild: true do
options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", xcodebuild_formatter: '' }
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
pipe = Snapshot::TestCommandGenerator.pipe.join(" ")
expect(pipe).not_to include("| xcpretty")
expect(pipe).not_to include("| xcbeautify")
end
describe "with xcodebuild_formatter" do
describe "with no xcpretty options" do
it "default when xcbeautify not installed", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false)
options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests" }
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
pipe = Snapshot::TestCommandGenerator.pipe.join(" ")
expect(pipe).to include("| xcpretty")
end
it "default when xcbeautify installed", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(true)
options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests" }
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
pipe = Snapshot::TestCommandGenerator.pipe.join(" ")
expect(pipe).to include("| xcbeautify")
end
it "xcpretty override when xcbeautify installed", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(true)
options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", xcodebuild_formatter: 'xcpretty' }
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
pipe = Snapshot::TestCommandGenerator.pipe.join(" ")
expect(pipe).to include("| xcpretty")
end
it "customer formatter", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(true)
options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", xcodebuild_formatter: "/path/to/xcbeautify" }
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
pipe = Snapshot::TestCommandGenerator.pipe.join(" ")
expect(pipe).to include("| /path/to/xcbeautify")
end
end
it "with xcpretty options when xcbeautify installed", requires_xcodebuild: true do
allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(true)
options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", xcpretty_args: "--rspec" }
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
pipe = Snapshot::TestCommandGenerator.pipe.join(" ")
expect(pipe).to include("| xcpretty")
end
end
describe "#legacy_xcpretty_options" do
it "with xcpretty_args", requires_xcodebuild: true do
options = { project: "./snapshot/example/Example.xcodeproj", scheme: "ExampleUITests", xcpretty_args: "--rspec" }
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.plain_options, options)
options = Snapshot::TestCommandGenerator.legacy_xcpretty_options
expect(options).to eq(['xcpretty_args'])
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/simulator_launcher_base_spec.rb | snapshot/spec/simulator_launcher_base_spec.rb | describe Snapshot do
describe Snapshot::SimulatorLauncherBase do
let(:device_udid) { "123456789" }
let(:paths) { ['./logo.png'] }
describe '#add_media' do
it "should call simctl addmedia", requires_xcode: true do
allow(Snapshot::TestCommandGenerator).to receive(:device_udid).and_return(device_udid)
if FastlaneCore::Helper.xcode_at_least?("13")
expect(Fastlane::Helper).to receive(:backticks)
.with("open -a Simulator.app --args -CurrentDeviceUDID #{device_udid} &> /dev/null")
.and_return("").exactly(1).times
else
expect(Fastlane::Helper).to receive(:backticks)
.with("xcrun instruments -w #{device_udid} &> /dev/null")
.and_return("").exactly(1).times
end
expect(Fastlane::Helper).to receive(:backticks)
.with("xcrun simctl addmedia #{device_udid} #{paths.join(' ')} &> /dev/null")
.and_return("").exactly(1).times
# Verify that backticks isn't called for the fallback to addphoto/addvideo
expect(Fastlane::Helper).to receive(:backticks).with(anything).and_return(anything).exactly(0).times
launcher = Snapshot::SimulatorLauncherBase.new
launcher.add_media(['phone'], 'photo', paths)
end
it "should call simctl addmedia and fallback to addphoto", requires_xcode: true do
allow(Snapshot::TestCommandGenerator).to receive(:device_udid).and_return(device_udid)
if FastlaneCore::Helper.xcode_at_least?("13")
expect(Fastlane::Helper).to receive(:backticks)
.with("open -a Simulator.app --args -CurrentDeviceUDID #{device_udid} &> /dev/null")
.and_return("").exactly(1).times
else
expect(Fastlane::Helper).to receive(:backticks)
.with("xcrun instruments -w #{device_udid} &> /dev/null")
.and_return("").exactly(1).times
end
expect(Fastlane::Helper).to receive(:backticks)
.with("xcrun simctl addmedia #{device_udid} #{paths.join(' ')} &> /dev/null")
.and_return("usage: simctl [--noxpc] [--set <path>] [--profiles <path>] <subcommand> ...\n").exactly(1).times
expect(Fastlane::Helper).to receive(:backticks).with(anything).and_return(anything).exactly(1).times
launcher = Snapshot::SimulatorLauncherBase.new
launcher.add_media(['phone'], 'photo', paths)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/reports_generator_spec.rb | snapshot/spec/reports_generator_spec.rb | require 'snapshot/reports_generator'
describe Snapshot::ReportsGenerator do
describe '#available_devices' do
# the Collector generates file names that remove all spaces from the device names, so
# any keys here can't contain spaces
it "xcode 8 devices don't have keys that contain spaces" do
allow(FastlaneCore::Helper).to receive(:xcode_at_least?).with("9.0").and_return(false)
device_name_keys = Snapshot::ReportsGenerator.new.available_devices.keys
expect(device_name_keys.none? { |k| k.include?(' ') }).to be(true)
end
it "xcode 9 devices have keys that contain spaces" do
allow(FastlaneCore::Helper).to receive(:xcode_at_least?).with("9.0").and_return(false)
device_name_keys = Snapshot::ReportsGenerator.new.available_devices.keys
expect(device_name_keys.none? { |k| k.include?(' ') }).to be(true)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/runner_spec.rb | snapshot/spec/runner_spec.rb | require 'os'
describe Snapshot do
describe Snapshot::Runner do
let(:runner) { Snapshot::Runner.new }
describe 'Parses embedded SnapshotHelper.swift' do
it 'finds the current embedded version' do
allow(FastlaneCore::Helper).to receive(:xcode_at_least?).with("9.0").and_return(true)
helper_version = runner.version_of_bundled_helper
expect(helper_version).to match(/^SnapshotHelperVersion \[\d+.\d+\]$/)
end
end
describe 'Parses embedded SnapshotHelperXcode8.swift' do
it 'finds the current embedded version' do
allow(FastlaneCore::Helper).to receive(:xcode_at_least?).with("9.0").and_return(false)
helper_version = runner.version_of_bundled_helper
expect(helper_version).to match(/^SnapshotHelperXcode8Version \[\d+.\d+\]$/)
end
end
describe 'Decides on the number of sims to launch when simultaneously snapshotting' do
it 'returns 1 if CPUs is 1' do
snapshot_config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, {})
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: snapshot_config)
allow(Snapshot::CPUInspector).to receive(:cpu_count).and_return(1)
sims = Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config).default_number_of_simultaneous_simulators
expect(sims).to eq(1)
end
it 'returns 2 if CPUs is 2' do
snapshot_config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, {})
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: snapshot_config)
allow(Snapshot::CPUInspector).to receive(:cpu_count).and_return(2)
sims = Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config).default_number_of_simultaneous_simulators
expect(sims).to eq(2)
end
it 'returns 3 if CPUs is 4' do
snapshot_config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, {})
launcher_config = Snapshot::SimulatorLauncherConfiguration.new(snapshot_config: snapshot_config)
allow(Snapshot::CPUInspector).to receive(:cpu_count).and_return(4)
sims = Snapshot::SimulatorLauncher.new(launcher_configuration: launcher_config).default_number_of_simultaneous_simulators
expect(sims).to eq(3)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/detect_values_spec.rb | snapshot/spec/detect_values_spec.rb | describe Snapshot do
describe Snapshot::DetectValues do
describe "value coercion" do
before(:each) do
allow(Snapshot).to receive(:snapfile_name).and_return("some fake snapfile")
end
it "coerces only_testing to be an array", requires_xcodebuild: true do
options = {
project: "./snapshot/example/Example.xcodeproj",
scheme: "ExampleUITests",
only_testing: "Bundle/SuiteA"
}
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, options)
expect(Snapshot.config[:only_testing]).to eq(["Bundle/SuiteA"])
end
it "coerces skip_testing to be an array", requires_xcodebuild: true do
options = {
project: "./snapshot/example/Example.xcodeproj",
scheme: "ExampleUITests",
skip_testing: "Bundle/SuiteA,Bundle/SuiteB"
}
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, options)
expect(Snapshot.config[:skip_testing]).to eq(["Bundle/SuiteA", "Bundle/SuiteB"])
end
it "leaves skip_testing as an array", requires_xcodebuild: true do
options = {
project: "./snapshot/example/Example.xcodeproj",
scheme: "ExampleUITests",
skip_testing: ["Bundle/SuiteA", "Bundle/SuiteB"]
}
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, options)
expect(Snapshot.config[:skip_testing]).to eq(["Bundle/SuiteA", "Bundle/SuiteB"])
end
end
describe "device configuration for Mac projects" do
before(:each) do
allow(Snapshot).to receive(:snapfile_name).and_return("some fake snapfile")
fake_out_xcode_project_loading
allow(File).to receive(:expand_path).and_call_original
allow(File).to receive(:expand_path).with("some fake snapfile").and_return("/fake/path/Snapfile")
allow(File).to receive(:expand_path).with("..", "./snapshot/example/Example.xcodeproj").and_return("./snapshot/example")
allow(File).to receive(:exist?).and_call_original
allow(File).to receive(:exist?).with("./snapshot/example/Example.xcodeproj").and_return(true)
allow(File).to receive(:exist?).with("/fake/path/Snapfile").and_return(false)
allow(File).to receive(:exist?).with("./snapshot/example/some fake snapfile").and_return(false)
allow(Dir).to receive(:chdir).and_yield
end
it "sets devices to ['Mac'] when devices is nil and project is Mac", requires_xcodebuild: true do
options = {
project: "./snapshot/example/Example.xcodeproj",
scheme: "ExampleMacOSUITests"
}
mock_project = instance_double(FastlaneCore::Project, mac?: true, path: "./snapshot/example/Example.xcodeproj", select_scheme: nil)
allow(FastlaneCore::Project).to receive(:new).and_return(mock_project)
allow(FastlaneCore::Project).to receive(:detect_projects)
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, options)
expect(Snapshot.config[:devices]).to eq(["Mac"])
end
it "does not overwrite devices when devices is already set and project is Mac", requires_xcodebuild: true do
# Get a real device name from available simulators to avoid validation errors
available_devices = FastlaneCore::Simulator.all.map(&:name)
test_device = available_devices.first || "iPhone 16 Pro Max"
options = {
project: "./snapshot/example/Example.xcodeproj",
scheme: "ExampleMacOSUITests",
devices: [test_device]
}
mock_project = instance_double(FastlaneCore::Project, mac?: true, path: "./snapshot/example/Example.xcodeproj", select_scheme: nil)
allow(FastlaneCore::Project).to receive(:new).and_return(mock_project)
allow(FastlaneCore::Project).to receive(:detect_projects)
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, options)
expect(Snapshot.config[:devices]).to eq([test_device])
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/reset_simulators_spec.rb | snapshot/spec/reset_simulators_spec.rb | require 'snapshot/reset_simulators'
describe Snapshot::ResetSimulators do
let(:usable_devices) do
[
[" iPhone 6s Plus (0311D4EC-14E7-443B-9F27-F32E72342799) (Shutdown)", "iPhone 6s Plus", "0311D4EC-14E7-443B-9F27-F32E72342799"],
[" iPad Pro (AD6A06DF-16EF-492D-8AF3-8128FCC03CBF) (Shutdown)", "iPad Pro", "AD6A06DF-16EF-492D-8AF3-8128FCC03CBF"],
[" Apple TV 1080p (D7D591A8-17D2-47B4-8D2A-AFAFA28874C9) (Shutdown)", "Apple TV 1080p", "D7D591A8-17D2-47B4-8D2A-AFAFA28874C9"],
[" Apple Watch - 38mm (2A58326E-50F3-4575-9049-E119A4E6852D) (Shutdown)", "Apple Watch - 38mm", "2A58326E-50F3-4575-9049-E119A4E6852D"],
[" Apple Watch - 42mm (C8250DD7-8C4E-4803-838A-731B42785262) (Shutdown)", "Apple Watch - 42mm", "C8250DD7-8C4E-4803-838A-731B42785262"]
]
end
let(:unusable_devices) do
[
[" Apple Watch - 38mm (22C04589-2AD4-42BB-9869-FB2331708E62) (Creating) (unavailable, runtime profile not found)", "Apple Watch - 38mm", "22C04589-2AD4-42BB-9869-FB2331708E62"],
[" Apple Watch - 42mm (B98D4701-C719-41CD-BCCD-1288464D9B26) (Creating) (unavailable, runtime profile not found)", "Apple Watch - 42mm", "B98D4701-C719-41CD-BCCD-1288464D9B26"],
[" Apple Watch - 38mm (AF341B69-678E-48B0-9D12-A7502662D1BE) (Creating) (unavailable, runtime profile not found)", "Apple Watch - 38mm", "AF341B69-678E-48B0-9D12-A7502662D1BE"],
[" Apple Watch - 42mm (D2C4CBD0-DF62-45E3-8E25-72201827482E) (Creating) (unavailable, runtime profile not found)", "Apple Watch - 42mm", "D2C4CBD0-DF62-45E3-8E25-72201827482E"]
]
end
let(:runtimes) do
[
["iOS 10.3", "com.apple.CoreSimulator.SimRuntime.iOS-10-3"],
["tvOS 10.2", "com.apple.CoreSimulator.SimRuntime.tvOS-10-2"],
["watchOS 3.2", "com.apple.CoreSimulator.SimRuntime.watchOS-3-2"]
]
end
let(:all_devices) do
usable_devices + unusable_devices
end
let(:fixture_data) { File.read('snapshot/spec/fixtures/xcrun-simctl-list-devices.txt') }
let(:fixture_runtimes_xcode8) { File.read('snapshot/spec/fixtures/xcrun-simctl-list-runtimes-Xcode8.txt') }
let(:fixture_runtimes_xcode9) { File.read('snapshot/spec/fixtures/xcrun-simctl-list-runtimes-Xcode9.txt') }
describe '#devices' do
it 'should read simctl output into arrays of device info' do
expect(FastlaneCore::Helper).to receive(:backticks).with(/xcrun simctl list devices/, print: FastlaneCore::Globals.verbose?).and_return(fixture_data)
expect(Snapshot::ResetSimulators.devices).to eq(all_devices)
end
end
describe '#clear_everything' do
describe 'runtimes' do
it "should find runtimes that are available for Xcode 8" do
expect(FastlaneCore::Helper).to receive(:backticks).with(/xcrun simctl list runtimes/, print: FastlaneCore::Globals.verbose?).and_return(fixture_runtimes_xcode8)
expect(Snapshot::ResetSimulators.runtimes).to eq(runtimes)
end
it "should find runtimes that are available for Xcode 9" do
expect(FastlaneCore::Helper).to receive(:backticks).with(/xcrun simctl list runtimes/, print: FastlaneCore::Globals.verbose?).and_return(fixture_runtimes_xcode9)
expect(Snapshot::ResetSimulators.runtimes).to eq(runtimes)
end
end
end
describe '#device_line_usable?' do
describe 'usable devices' do
it "should find normal devices to be usable" do
usable_devices.each do |usable|
expect(Snapshot::ResetSimulators.device_line_usable?(usable[0])).to be(true)
end
end
end
describe 'unusable devices' do
it "should find devices in bad states to be unusable" do
unusable_devices.each do |unusable|
expect(Snapshot::ResetSimulators.device_line_usable?(unusable[0])).to be(false)
end
end
end
end
describe '#make_phone_watch_pair' do
describe 'with no phones present' do
it 'does not call out to simctl' do
mocked_devices = [
[" iPad Pro (AD6A06DF-16EF-492D-8AF3-8128FCC03CBF) (Shutdown)", "iPad Pro", "AD6A06DF-16EF-492D-8AF3-8128FCC03CBF"],
[" Apple TV 1080p (D7D591A8-17D2-47B4-8D2A-AFAFA28874C9) (Shutdown)", "Apple TV 1080p", "D7D591A8-17D2-47B4-8D2A-AFAFA28874C9"],
[" Apple Watch - 38mm (2A58326E-50F3-4575-9049-E119A4E6852D) (Shutdown)", "Apple Watch - 38mm", "2A58326E-50F3-4575-9049-E119A4E6852D"],
[" Apple Watch - 42mm (C8250DD7-8C4E-4803-838A-731B42785262) (Shutdown)", "Apple Watch - 42mm", "C8250DD7-8C4E-4803-838A-731B42785262"]
]
expect(Snapshot::ResetSimulators).to receive(:devices).and_return(mocked_devices)
expect(FastlaneCore::Helper).not_to(receive(:backticks))
Snapshot::ResetSimulators.make_phone_watch_pair
end
end
describe 'with no watches present' do
it 'does not call out to simctl' do
mocked_devices = [
[" iPhone 6s Plus (0311D4EC-14E7-443B-9F27-F32E72342799) (Shutdown)", "iPhone 6s Plus", "0311D4EC-14E7-443B-9F27-F32E72342799"],
[" iPad Pro (AD6A06DF-16EF-492D-8AF3-8128FCC03CBF) (Shutdown)", "iPad Pro", "AD6A06DF-16EF-492D-8AF3-8128FCC03CBF"],
[" Apple TV 1080p (D7D591A8-17D2-47B4-8D2A-AFAFA28874C9) (Shutdown)", "Apple TV 1080p", "D7D591A8-17D2-47B4-8D2A-AFAFA28874C9"]
]
expect(Snapshot::ResetSimulators).to receive(:devices).and_return(mocked_devices)
expect(FastlaneCore::Helper).not_to(receive(:backticks))
Snapshot::ResetSimulators.make_phone_watch_pair
end
end
describe 'with an available phone-watch pair' do
it 'calls out to simctl pair' do
expected_command = "xcrun simctl pair C8250DD7-8C4E-4803-838A-731B42785262 0311D4EC-14E7-443B-9F27-F32E72342799"
# By checking against all_devices, we expect those which are in an unusable state
# NOT to be selected!
expect(Snapshot::ResetSimulators).to receive(:devices).and_return(all_devices)
expect(FastlaneCore::Helper).to receive(:backticks).with(expected_command, print: FastlaneCore::Globals.verbose?)
Snapshot::ResetSimulators.make_phone_watch_pair
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/spec/spec_helper.rb | snapshot/spec/spec_helper.rb | # Loading the XCode Project is really slow (>1 second)
# fake it out for tests
def fake_out_xcode_project_loading
fake_result = <<-EOS
Information about project "Example":
Targets:
Example
ExampleUITests
ExampleMacOS
ExampleMacOSUITests
Build Configurations:
Debug
Release
If no build configuration is specified and -scheme is not passed then "Release" is used.
Schemes:
Example
ExampleUITests
ExampleMacOS
EOS
allow_any_instance_of(FastlaneCore::Project).to receive(:raw_info).and_return(fake_result)
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot.rb | snapshot/lib/snapshot.rb | require_relative 'snapshot/runner'
require_relative 'snapshot/reports_generator'
require_relative 'snapshot/detect_values'
require_relative 'snapshot/screenshot_flatten'
require_relative 'snapshot/screenshot_rotate'
require_relative 'snapshot/dependency_checker'
require_relative 'snapshot/latest_os_version'
require_relative 'snapshot/test_command_generator'
require_relative 'snapshot/test_command_generator_xcode_8'
require_relative 'snapshot/error_handler'
require_relative 'snapshot/collector'
require_relative 'snapshot/options'
require_relative 'snapshot/update'
require_relative 'snapshot/fixes/simulator_zoom_fix'
require_relative 'snapshot/fixes/hardware_keyboard_fix'
require_relative 'snapshot/simulator_launchers/launcher_configuration'
require_relative 'snapshot/simulator_launchers/simulator_launcher'
require_relative 'snapshot/simulator_launchers/simulator_launcher_xcode_8'
require_relative 'snapshot/module'
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/screenshot_flatten.rb | snapshot/lib/snapshot/screenshot_flatten.rb | require_relative 'module'
module Snapshot
# This class takes care of removing the alpha channel of the generated screenshots
class ScreenshotFlatten
# @param (String) The path in which the screenshots are located in
def run(path)
UI.message("Removing the alpha channel from generated png files")
flatten(path)
end
def flatten(path)
Dir.glob([path, '/**/*.png'].join('/')).each do |file|
UI.verbose("Removing alpha channel from '#{file}'")
`sips -s format bmp '#{file}' &> /dev/null` # &> /dev/null because there is warning because of the extension
`sips -s format png '#{file}'`
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/test_command_generator.rb | snapshot/lib/snapshot/test_command_generator.rb | require_relative 'test_command_generator_base'
require_relative 'latest_os_version'
module Snapshot
# Responsible for building the fully working xcodebuild command
# Xcode 9 introduced the ability to run tests in parallel on multiple simulators
# This TestCommandGenerator constructs the appropriate `xcodebuild` command
# to be used for executing simultaneous tests
class TestCommandGenerator < TestCommandGeneratorBase
class << self
def generate(devices: nil, language: nil, locale: nil, log_path: nil)
parts = prefix
parts << "xcodebuild"
parts += options(language, locale)
parts += destination(devices)
parts += build_settings(language, locale)
parts += actions
parts += suffix
parts += pipe(log_path: log_path)
return parts
end
def pipe(log_path: nil)
tee_command = ['tee']
tee_command << '-a' if log_path && File.exist?(log_path)
tee_command << log_path.shellescape if log_path
pipe = ["| #{tee_command.join(' ')}"]
formatter = Snapshot.config[:xcodebuild_formatter].chomp
options = legacy_xcpretty_options
if Snapshot.config[:disable_xcpretty] || formatter == ''
UI.verbose("Not using an xcodebuild formatter")
elsif !options.empty?
UI.important("Detected legacy xcpretty being used, so formatting with xcpretty")
UI.important("Option(s) used: #{options.join(', ')}")
pipe += pipe_xcpretty
elsif formatter == 'xcpretty'
pipe += pipe_xcpretty
elsif formatter == 'xcbeautify'
pipe += pipe_xcbeautify
else
pipe << "| #{formatter}"
end
pipe
end
def pipe_xcbeautify
pipe = ['| xcbeautify']
if FastlaneCore::Helper.colors_disabled?
pipe << '--disable-colored-output'
end
return pipe
end
def legacy_xcpretty_options
options = []
options << "xcpretty_args" if Snapshot.config[:xcpretty_args]
return options
end
def pipe_xcpretty
pipe = []
xcpretty = "xcpretty #{Snapshot.config[:xcpretty_args]}"
xcpretty << "--no-color" if Helper.colors_disabled?
pipe << "| #{xcpretty}"
pipe << "> /dev/null" if Snapshot.config[:suppress_xcode_output]
return pipe
end
def destination(devices)
unless verify_devices_share_os(devices)
UI.user_error!('All devices provided to snapshot should run the same operating system')
end
# on Mac we will always run on host machine, so should specify only platform
return ["-destination 'platform=macOS'"] if devices.first.to_s =~ /^Mac/
case devices.first.to_s
when /^Apple TV/
os = 'tvOS'
when /^Apple Watch/
os = 'watchOS'
else
os = 'iOS'
end
os_version = Snapshot.config[:ios_version] || Snapshot::LatestOsVersion.version(os)
destinations = devices.map do |d|
device = find_device(d, os_version)
if device.nil?
UI.user_error!("No device found named '#{d}' for version '#{os_version}'") if device.nil?
elsif device.os_version != os_version
UI.important("Using device named '#{device.name}' with version '#{device.os_version}' because no match was found for version '#{os_version}'")
end
"-destination 'platform=#{os} Simulator,name=#{device.name},OS=#{device.os_version}'"
end
return [destinations.join(' ')]
end
def verify_devices_share_os(device_names)
# Get device types based off of device name
devices = get_device_type_with_simctl(device_names)
# Check each device to see if it is an iOS device
all_ios = devices.map do |device|
device = device.downcase
device.include?('iphone') || device.include?('ipad') || device.include?('ipod')
end
# Return true if all devices are iOS devices
return true unless all_ios.include?(false)
all_tvos = devices.map do |device|
device = device.downcase
device.include?('apple tv')
end
# Return true if all devices are tvOS devices
return true unless all_tvos.include?(false)
all_watchos = devices.map do |device|
device = device.downcase
device.include?('apple watch')
end
# Return true if all devices are watchOS devices
return true unless all_watchos.include?(false)
# There should only be more than 1 device type if
# it is iOS or tvOS, therefore, if there is more than 1
# device in the array, and they are not all iOS or tvOS
# as checked above, that would imply that this is a mixed bag
return devices.count == 1
end
private
def get_device_type_with_simctl(device_names)
return device_names if Helper.test?
require("simctl")
# Gets actual simctl device type from device name
return device_names.map do |device_name|
device = SimCtl.device(name: device_name)
if device
device.devicetype.name
end
end.compact
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/update.rb | snapshot/lib/snapshot/update.rb | require_relative 'module'
require_relative 'runner'
module Snapshot
# Migrate helper files
class Update
# @return [Array] A list of helper files (usually just one)
def self.find_helper
paths = Dir["./**/SnapshotHelper.swift"] + Dir["./**/SnapshotHelperXcode8.swift"]
# exclude assets in gym
paths.reject { |p| p.include?("snapshot/lib/assets/") || p.include?("DerivedData") }
end
def update(force: false)
paths = self.class.find_helper
UI.user_error!("Couldn't find any SnapshotHelper files in current directory") if paths.count == 0
UI.message("Found the following SnapshotHelper:")
paths.each { |p| UI.message("\t#{p}") }
UI.important("Are you sure you want to automatically update the helpers listed above?")
UI.message("This will overwrite all its content with the latest code.")
UI.message("The underlying API will not change. You can always migrate manually by looking at")
UI.message("https://github.com/fastlane/fastlane/blob/master/snapshot/lib/assets/SnapshotHelper.swift")
if !force && !UI.confirm("Overwrite configuration files?")
return 1
end
paths.each do |path|
UI.message("Updating '#{path}'...")
input_path = Snapshot::Runner.path_to_helper_file_from_gem
File.write(path, File.read(input_path))
end
UI.success("Successfully updated helper files")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/setup.rb | snapshot/lib/snapshot/setup.rb | require_relative 'module'
module Snapshot
class Setup
# This method will take care of creating a Snapfile and other necessary files
def self.create(path, is_swift_fastfile: false, print_instructions_on_failure: false)
# First generate all the names & paths
if is_swift_fastfile
template_path = "#{Snapshot::ROOT}/lib/assets/SnapfileTemplate.swift"
snapfile_path = File.join(path, 'Snapfile.swift')
else
template_path = "#{Snapshot::ROOT}/lib/assets/SnapfileTemplate"
snapfile_path = File.join(path, 'Snapfile')
end
snapshot_helper_filename = "SnapshotHelperXcode8.swift"
if Helper.xcode_at_least?("9.0")
snapshot_helper_filename = "SnapshotHelper.swift"
end
if File.exist?(snapfile_path)
if print_instructions_on_failure
print_instructions(snapshot_helper_filename: snapshot_helper_filename)
return
else
UI.user_error!("Snapfile already exists at path '#{snapfile_path}'. Run 'fastlane snapshot' to generate screenshots.")
end
end
File.write(snapfile_path, File.read(template_path))
# ensure that upgrade is cause when going from 8 to 9
File.write(File.join(path, snapshot_helper_filename), File.read("#{Snapshot::ROOT}/lib/assets/#{snapshot_helper_filename}"))
puts("✅ Successfully created #{snapshot_helper_filename} '#{File.join(path, snapshot_helper_filename)}'".green)
puts("✅ Successfully created new Snapfile at '#{snapfile_path}'".green)
puts("-------------------------------------------------------".yellow)
print_instructions(snapshot_helper_filename: snapshot_helper_filename)
end
def self.print_instructions(snapshot_helper_filename: nil)
puts("Open your Xcode project and make sure to do the following:".yellow)
puts("1) Add a new UI Test target to your project".yellow)
puts("2) Add the ./fastlane/#{snapshot_helper_filename} to your UI Test target".yellow)
puts(" You can move the file anywhere you want".yellow)
puts("3) Call `setupSnapshot(app)` when launching your app".yellow)
puts("")
puts(" let app = XCUIApplication()")
puts(" setupSnapshot(app)")
puts(" app.launch()")
puts("")
puts("4) Add `snapshot(\"0Launch\")` to wherever you want to trigger screenshots".yellow)
puts("5) Add a new Xcode scheme for the newly created UITest target".yellow)
puts("6) Add a Check to enable the `Shared` box of the newly created scheme".yellow)
puts("")
puts("More information: https://docs.fastlane.tools/getting-started/ios/screenshots/".green)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/collector.rb | snapshot/lib/snapshot/collector.rb | require 'plist'
require_relative 'module'
require_relative 'test_command_generator'
module Snapshot
# Responsible for collecting the generated screenshots and copying them over to the output directory
class Collector
# Returns true if it succeeds
def self.fetch_screenshots(output, dir_name, device_type, launch_arguments_index)
# Documentation about how this works in the project README
containing = File.join(TestCommandGenerator.derived_data_path, "Logs", "Test")
attachments_path = File.join(containing, "Attachments")
language_folder = File.join(Snapshot.config[:output_directory], dir_name)
FileUtils.mkdir_p(language_folder)
# Xcode 9 introduced a new API to take screenshots which allows us
# to avoid parsing the generated plist file to find the screenshots
# and instead, we can save them to a known location to use later on.
if Helper.xcode_at_least?(9)
return collect_screenshots_for_language_folder(language_folder)
else
to_store = attachments(containing)
matches = output.scan(/snapshot: (.*)/)
end
if to_store.count == 0 && matches.count == 0
return false
end
if matches.count != to_store.count
UI.error("Looks like the number of screenshots (#{to_store.count}) doesn't match the number of names (#{matches.count})")
end
matches.each_with_index do |current, index|
name = current[0]
filename = to_store[index]
device_name = device_type.delete(" ")
components = [launch_arguments_index].delete_if { |a| a.to_s.length == 0 }
screenshot_name = device_name + "-" + name + "-" + Digest::MD5.hexdigest(components.join("-")) + ".png"
output_path = File.join(language_folder, screenshot_name)
from_path = File.join(attachments_path, filename)
copy(from_path, output_path)
end
return true
end
# Returns true if it succeeds
def self.collect_screenshots_for_language_folder(destination)
screenshots = Dir["#{SCREENSHOTS_DIR}/*.png"]
return false if screenshots.empty?
screenshots.each do |screenshot|
filename = File.basename(screenshot)
to_path = File.join(destination, filename)
copy(screenshot, to_path)
end
FileUtils.rm_rf(SCREENSHOTS_DIR)
return true
end
def self.copy(from_path, to_path)
if FastlaneCore::Globals.verbose?
UI.success("Copying file '#{from_path}' to '#{to_path}'...")
else
UI.success("Copying '#{to_path}'...")
end
FileUtils.cp(from_path, to_path)
end
def self.attachments(containing)
UI.message("Collecting screenshots...")
plist_path = Dir[File.join(containing, "*.plist")].last # we clean the folder before each run
return attachments_in_file(plist_path)
end
def self.attachments_in_file(plist_path)
UI.verbose("Loading up '#{plist_path}'...")
report = Plist.parse_xml(plist_path)
to_store = [] # contains the names of all the attachments we want to use
report["TestableSummaries"].each do |summary|
(summary["Tests"] || []).each do |test|
(test["Subtests"] || []).each do |subtest|
(subtest["Subtests"] || []).each do |subtest2|
(subtest2["Subtests"] || []).each do |subtest3|
(subtest3["ActivitySummaries"] || []).each do |activity|
check_activity(activity, to_store)
end
end
end
end
end
end
UI.message("Found #{to_store.count} screenshots...")
UI.verbose("Found #{to_store.join(', ')}")
return to_store
end
def self.check_activity(activity, to_store)
# On iOS, we look for the "Unknown" rotation gesture that signals a snapshot was taken here.
# On tvOS, we look for "Browser" count.
# On OSX we look for type `Fn` key on keyboard, it shouldn't change anything for app
# These are events that are not normally triggered by UI testing, making it easy for us to
# locate where snapshot() was invoked.
ios_detected = activity["Title"] == "Set device orientation to Unknown"
tvos_detected = activity["Title"] == "Get number of matches for: Children matching type Browser"
osx_detected = activity["Title"] == "Type 'Fn' key (XCUIKeyboardKeySecondaryFn) with no modifiers"
if ios_detected || tvos_detected || osx_detected
find_screenshot = find_screenshot(activity)
to_store << find_screenshot
end
(activity["SubActivities"] || []).each do |subactivity|
check_activity(subactivity, to_store)
end
end
def self.find_screenshot(activity)
(activity["SubActivities"] || []).each do |subactivity|
# we are interested in `Synthesize event` part of event in subactivities
return find_screenshot(subactivity) if subactivity["Title"] == "Synthesize event"
end
if activity["Attachments"] && activity["Attachments"].last && activity["Attachments"].last["Filename"]
return activity["Attachments"].last["Filename"]
elsif activity["Attachments"]
return activity["Attachments"].last["FileName"]
else # Xcode 7.3 has stopped including 'Attachments', so we synthesize the filename manually
return "Screenshot_#{activity['UUID']}.png"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/options.rb | snapshot/lib/snapshot/options.rb | require 'fastlane_core/configuration/config_item'
require 'fastlane_core/device_manager'
require 'fastlane/helper/xcodebuild_formatter_helper'
require 'credentials_manager/appfile_config'
require_relative 'module'
module Snapshot
class Options
def self.verify_type(item_name, acceptable_types, value)
type_ok = [Array, String].any? { |type| value.kind_of?(type) }
UI.user_error!("'#{item_name}' should be of type #{acceptable_types.join(' or ')} but found: #{value.class.name}") unless type_ok
end
def self.available_options
@options ||= plain_options
end
def self.plain_options
output_directory = (File.directory?("fastlane") ? "fastlane/screenshots" : "screenshots")
[
FastlaneCore::ConfigItem.new(key: :workspace,
short_option: "-w",
env_name: "SNAPSHOT_WORKSPACE",
optional: true,
description: "Path to the workspace file",
verify_block: proc do |value|
v = File.expand_path(value.to_s)
UI.user_error!("Workspace file not found at path '#{v}'") unless File.exist?(v)
UI.user_error!("Workspace file invalid") unless File.directory?(v)
UI.user_error!("Workspace file is not a workspace, must end with .xcworkspace") unless v.include?(".xcworkspace")
end),
FastlaneCore::ConfigItem.new(key: :project,
short_option: "-p",
optional: true,
env_name: "SNAPSHOT_PROJECT",
description: "Path to the project file",
verify_block: proc do |value|
v = File.expand_path(value.to_s)
UI.user_error!("Project file not found at path '#{v}'") unless File.exist?(v)
UI.user_error!("Project file invalid") unless File.directory?(v)
UI.user_error!("Project file is not a project file, must end with .xcodeproj") unless v.include?(".xcodeproj")
end),
FastlaneCore::ConfigItem.new(key: :xcargs,
short_option: "-X",
env_name: "SNAPSHOT_XCARGS",
description: "Pass additional arguments to xcodebuild for the test phase. Be sure to quote the setting names and values e.g. OTHER_LDFLAGS=\"-ObjC -lstdc++\"",
optional: true,
type: :shell_string),
FastlaneCore::ConfigItem.new(key: :xcconfig,
short_option: "-y",
env_name: "SNAPSHOT_XCCONFIG",
description: "Use an extra XCCONFIG file to build your app",
optional: true,
verify_block: proc do |value|
UI.user_error!("File not found at path '#{File.expand_path(value)}'") unless File.exist?(value)
end),
FastlaneCore::ConfigItem.new(key: :devices,
description: "A list of devices you want to take the screenshots from",
short_option: "-d",
type: Array,
optional: true,
verify_block: proc do |value|
available = FastlaneCore::DeviceManager.simulators
value.each do |current|
device = current.strip
unless available.any? { |d| d.name.strip == device } || device == "Mac"
UI.user_error!("Device '#{device}' not in list of available simulators '#{available.join(', ')}'")
end
end
end),
FastlaneCore::ConfigItem.new(key: :languages,
description: "A list of languages which should be used",
short_option: "-g",
type: Array,
default_value: ['en-US']),
FastlaneCore::ConfigItem.new(key: :launch_arguments,
env_name: 'SNAPSHOT_LAUNCH_ARGUMENTS',
description: "A list of launch arguments which should be used",
short_option: "-m",
type: Array,
default_value: ['']),
FastlaneCore::ConfigItem.new(key: :output_directory,
short_option: "-o",
env_name: "SNAPSHOT_OUTPUT_DIRECTORY",
description: "The directory where to store the screenshots",
default_value: output_directory,
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :output_simulator_logs,
env_name: "SNAPSHOT_OUTPUT_SIMULATOR_LOGS",
description: "If the logs generated by the app (e.g. using NSLog, perror, etc.) in the Simulator should be written to the output_directory",
type: Boolean,
default_value: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :ios_version,
description: "By default, the latest version should be used automatically. If you want to change it, do it here",
short_option: "-i",
optional: true),
FastlaneCore::ConfigItem.new(key: :skip_open_summary,
env_name: 'SNAPSHOT_SKIP_OPEN_SUMMARY',
description: "Don't open the HTML summary after running _snapshot_",
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :skip_helper_version_check,
env_name: 'SNAPSHOT_SKIP_SKIP_HELPER_VERSION_CHECK',
description: "Do not check for most recent SnapshotHelper code",
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :clear_previous_screenshots,
env_name: 'SNAPSHOT_CLEAR_PREVIOUS_SCREENSHOTS',
description: "Enabling this option will automatically clear previously generated screenshots before running snapshot",
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :reinstall_app,
env_name: 'SNAPSHOT_REINSTALL_APP',
description: "Enabling this option will automatically uninstall the application before running it",
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :erase_simulator,
env_name: 'SNAPSHOT_ERASE_SIMULATOR',
description: "Enabling this option will automatically erase the simulator before running the application",
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :headless,
env_name: 'SNAPSHOT_HEADLESS',
description: "Enabling this option will prevent displaying the simulator window",
default_value: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :override_status_bar,
env_name: 'SNAPSHOT_OVERRIDE_STATUS_BAR',
description: "Enabling this option will automatically override the status bar to show 9:41 AM, full battery, and full reception (Adjust 'SNAPSHOT_SIMULATOR_WAIT_FOR_BOOT_TIMEOUT' environment variable if override status bar is not working. Might be because simulator is not fully booted. Defaults to 10 seconds)",
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :override_status_bar_arguments,
env_name: 'SNAPSHOT_OVERRIDE_STATUS_BAR_ARGUMENTS',
description: "Fully customize the status bar by setting each option here. Requires `override_status_bar` to be set to `true`. See `xcrun simctl status_bar --help`",
optional: true,
type: String),
FastlaneCore::ConfigItem.new(key: :localize_simulator,
env_name: 'SNAPSHOT_LOCALIZE_SIMULATOR',
description: "Enabling this option will configure the Simulator's system language",
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :dark_mode,
env_name: 'SNAPSHOT_DARK_MODE',
description: "Enabling this option will configure the Simulator to be in dark mode (false for light, true for dark)",
optional: true,
type: Boolean),
FastlaneCore::ConfigItem.new(key: :app_identifier,
env_name: 'SNAPSHOT_APP_IDENTIFIER',
short_option: "-a",
optional: true,
description: "The bundle identifier of the app to uninstall (only needed when enabling reinstall_app)",
code_gen_sensitive: true,
# This incorrect env name is here for backwards compatibility
default_value: ENV["SNAPSHOT_APP_IDENTITIFER"] || CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier),
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :add_photos,
env_name: 'SNAPSHOT_PHOTOS',
short_option: "-j",
description: "A list of photos that should be added to the simulator before running the application",
type: Array,
optional: true),
FastlaneCore::ConfigItem.new(key: :add_videos,
env_name: 'SNAPSHOT_VIDEOS',
short_option: "-u",
description: "A list of videos that should be added to the simulator before running the application",
type: Array,
optional: true),
FastlaneCore::ConfigItem.new(key: :html_template,
env_name: 'SNAPSHOT_HTML_TEMPLATE',
short_option: "-e",
description: "A path to screenshots.html template",
optional: true),
# Everything around building
FastlaneCore::ConfigItem.new(key: :buildlog_path,
short_option: "-l",
env_name: "SNAPSHOT_BUILDLOG_PATH",
description: "The directory where to store the build log",
default_value: "#{FastlaneCore::Helper.buildlog_path}/snapshot",
default_value_dynamic: true),
FastlaneCore::ConfigItem.new(key: :clean,
short_option: "-c",
env_name: "SNAPSHOT_CLEAN",
description: "Should the project be cleaned before building it?",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :test_without_building,
short_option: "-T",
env_name: "SNAPSHOT_TEST_WITHOUT_BUILDING",
description: "Test without building, requires a derived data path",
is_string: false,
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :configuration,
short_option: "-q",
env_name: "SNAPSHOT_CONFIGURATION",
description: "The configuration to use when building the app. Defaults to 'Release'",
default_value_dynamic: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :sdk,
short_option: "-k",
env_name: "SNAPSHOT_SDK",
description: "The SDK that should be used for building the application",
optional: true),
FastlaneCore::ConfigItem.new(key: :scheme,
short_option: "-s",
env_name: 'SNAPSHOT_SCHEME',
description: "The scheme you want to use, this must be the scheme for the UI Tests",
optional: true), # optional true because we offer a picker to the user
FastlaneCore::ConfigItem.new(key: :number_of_retries,
short_option: "-n",
env_name: 'SNAPSHOT_NUMBER_OF_RETRIES',
description: "The number of times a test can fail before snapshot should stop retrying",
type: Integer,
default_value: 1),
FastlaneCore::ConfigItem.new(key: :stop_after_first_error,
env_name: 'SNAPSHOT_BREAK_ON_FIRST_ERROR',
description: "Should snapshot stop immediately after the tests completely failed on one device?",
default_value: false,
is_string: false),
FastlaneCore::ConfigItem.new(key: :derived_data_path,
short_option: "-f",
env_name: "SNAPSHOT_DERIVED_DATA_PATH",
description: "The directory where build products and other derived data will go",
optional: true),
FastlaneCore::ConfigItem.new(key: :result_bundle,
short_option: "-z",
env_name: "SNAPSHOT_RESULT_BUNDLE",
is_string: false,
description: "Should an Xcode result bundle be generated in the output directory",
default_value: false,
optional: true),
FastlaneCore::ConfigItem.new(key: :test_target_name,
env_name: "SNAPSHOT_TEST_TARGET_NAME",
description: "The name of the target you want to test (if you desire to override the Target Application from Xcode)",
optional: true),
FastlaneCore::ConfigItem.new(key: :namespace_log_files,
env_name: "SNAPSHOT_NAMESPACE_LOG_FILES",
description: "Separate the log files per device and per language",
optional: true,
is_string: false),
FastlaneCore::ConfigItem.new(key: :concurrent_simulators,
env_name: "SNAPSHOT_EXECUTE_CONCURRENT_SIMULATORS",
description: "Take snapshots on multiple simulators concurrently. Note: This option is only applicable when running against Xcode 9",
default_value: true,
is_string: false),
FastlaneCore::ConfigItem.new(key: :disable_slide_to_type,
env_name: "SNAPSHOT_DISABLE_SLIDE_TO_TYPE",
description: "Disable the simulator from showing the 'Slide to type' prompt",
default_value: false,
optional: true,
is_string: false),
FastlaneCore::ConfigItem.new(key: :cloned_source_packages_path,
env_name: "SNAPSHOT_CLONED_SOURCE_PACKAGES_PATH",
description: "Sets a custom path for Swift Package Manager dependencies",
type: String,
optional: true),
FastlaneCore::ConfigItem.new(key: :package_cache_path,
env_name: "SNAPSHOT_PACKAGE_CACHE_PATH",
description: "Sets a custom package cache path for Swift Package Manager dependencies",
type: String,
optional: true),
FastlaneCore::ConfigItem.new(key: :skip_package_dependencies_resolution,
env_name: "SNAPSHOT_SKIP_PACKAGE_DEPENDENCIES_RESOLUTION",
description: "Skips resolution of Swift Package Manager dependencies",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :disable_package_automatic_updates,
env_name: "SNAPSHOT_DISABLE_PACKAGE_AUTOMATIC_UPDATES",
description: "Prevents packages from automatically being resolved to versions other than those recorded in the `Package.resolved` file",
type: Boolean,
default_value: false),
FastlaneCore::ConfigItem.new(key: :package_authorization_provider,
env_name: "SNAPSHOT_PACKAGE_AUTHORIZATION_PROVIDER",
description: "Lets xcodebuild use a specified package authorization provider (keychain|netrc)",
optional: true,
type: String,
verify_block: proc do |value|
av = %w(netrc keychain)
UI.user_error!("Unsupported authorization provider '#{value}', must be: #{av}") unless av.include?(value)
end),
FastlaneCore::ConfigItem.new(key: :testplan,
env_name: "SNAPSHOT_TESTPLAN",
description: "The testplan associated with the scheme that should be used for testing",
is_string: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :only_testing,
env_name: "SNAPSHOT_ONLY_TESTING",
description: "Array of strings matching Test Bundle/Test Suite/Test Cases to run",
optional: true,
is_string: false,
verify_block: proc do |value|
verify_type('only_testing', [Array, String], value)
end),
FastlaneCore::ConfigItem.new(key: :skip_testing,
env_name: "SNAPSHOT_SKIP_TESTING",
description: "Array of strings matching Test Bundle/Test Suite/Test Cases to skip",
optional: true,
is_string: false,
verify_block: proc do |value|
verify_type('skip_testing', [Array, String], value)
end),
FastlaneCore::ConfigItem.new(key: :xcodebuild_formatter,
env_names: ["SNAPSHOT_XCODEBUILD_FORMATTER", "FASTLANE_XCODEBUILD_FORMATTER"],
description: "xcodebuild formatter to use (ex: 'xcbeautify', 'xcbeautify --quieter', 'xcpretty', 'xcpretty -test'). Use empty string (ex: '') to disable any formatter (More information: https://docs.fastlane.tools/best-practices/xcodebuild-formatters/)",
type: String,
default_value: Fastlane::Helper::XcodebuildFormatterHelper.xcbeautify_installed? ? 'xcbeautify' : 'xcpretty',
default_value_dynamic: true),
# xcpretty
FastlaneCore::ConfigItem.new(key: :xcpretty_args,
short_option: "-x",
env_name: "SNAPSHOT_XCPRETTY_ARGS",
deprecated: "Use `xcodebuild_formatter: ''` instead",
description: "Additional xcpretty arguments",
is_string: true,
optional: true),
FastlaneCore::ConfigItem.new(key: :disable_xcpretty,
env_name: "SNAPSHOT_DISABLE_XCPRETTY",
description: "Disable xcpretty formatting of build",
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :suppress_xcode_output,
env_name: "SNAPSHOT_SUPPRESS_XCODE_OUTPUT",
description: "Suppress the output of xcodebuild to stdout. Output is still saved in buildlog_path",
type: Boolean,
optional: true),
FastlaneCore::ConfigItem.new(key: :use_system_scm,
env_name: "SNAPSHOT_USE_SYSTEM_SCM",
description: "Lets xcodebuild use system's scm configuration",
type: Boolean,
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/snapshot/lib/snapshot/detect_values.rb | snapshot/lib/snapshot/detect_values.rb | require 'fastlane_core/project'
require 'fastlane_core/device_manager'
require_relative 'module'
module Snapshot
class DetectValues
# This is needed as these are more complex default values
def self.set_additional_default_values
config = Snapshot.config
# First, try loading the Snapfile from the current directory
configuration_file_path = File.expand_path(Snapshot.snapfile_name)
config.load_configuration_file(Snapshot.snapfile_name)
# Detect the project
FastlaneCore::Project.detect_projects(config)
Snapshot.project = FastlaneCore::Project.new(config)
# Go into the project's folder, as there might be a Snapfile there
Dir.chdir(File.expand_path("..", Snapshot.project.path)) do
unless File.expand_path(Snapshot.snapfile_name) == configuration_file_path
config.load_configuration_file(Snapshot.snapfile_name)
end
end
if config[:test_without_building] == true && config[:derived_data_path].to_s.length == 0
UI.user_error!("Cannot use test_without_building option without a derived_data_path!")
end
Snapshot.project.select_scheme(preferred_to_include: "UITests")
coerce_to_array_of_strings(:only_testing)
coerce_to_array_of_strings(:skip_testing)
# Devices
if config[:devices].nil? && !Snapshot.project.mac?
config[:devices] = []
# We only care about a subset of the simulators
all_simulators = FastlaneCore::Simulator.all
all_simulators.each do |sim|
# Filter iPads, we only want the following simulators
# Xcode 7:
# ["iPad Pro", "iPad Air"]
# Xcode 8:
# ["iPad Pro (9.7-Inch)", "iPad Pro (12.9-Inch)"]
#
# Full list: ["iPad 2", "iPad Retina", "iPad Air", "iPad Air 2", "iPad Pro"]
next if sim.name.include?("iPad 2")
next if sim.name.include?("iPad Retina")
next if sim.name.include?("iPad Air 2")
# In Xcode 8, we only need iPad Pro 9.7 inch, not the iPad Air
next if all_simulators.any? { |a| a.name.include?("9.7-inch") } && sim.name.include?("iPad Air")
# In Xcode 9, we only need one iPad Pro (12.9-inch)
next if sim.name.include?('iPad Pro (12.9-inch) (2nd generation)')
# Filter iPhones
# Full list: ["iPhone 4s", "iPhone 5", "iPhone 5s", "iPhone 6", "iPhone 6 Plus", "iPhone 6s", "iPhone 6s Plus"]
next if sim.name.include?("5s") # same screen resolution as iPhone 5
next if sim.name.include?("SE") # duplicate of iPhone 5
next if sim.name.include?("iPhone 6") # same as iPhone 7
next if sim.name.include?("Apple TV")
config[:devices] << sim.name
end
elsif config[:devices].nil? && Snapshot.project.mac?
config[:devices] = ["Mac"]
end
end
def self.coerce_to_array_of_strings(config_key)
config_value = Snapshot.config[config_key]
return if config_value.nil?
# splitting on comma allows us to support comma-separated lists of values
# from the command line, even though the ConfigItem is not defined as an
# Array type
config_value = config_value.split(',') unless config_value.kind_of?(Array)
Snapshot.config[config_key] = config_value.map(&:to_s)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/dependency_checker.rb | snapshot/lib/snapshot/dependency_checker.rb | require 'fastlane_core/device_manager'
require 'fastlane_core/helper'
require_relative 'latest_os_version'
module Snapshot
class DependencyChecker
def self.check_dependencies
return if FastlaneCore::Helper.test?
return unless FastlaneCore::Helper.mac?
self.check_xcode_select
self.check_simctl
end
def self.check_xcode_select
xcode_available = nil
begin
xcode_available = `xcode-select -v`.include?("xcode-select version")
rescue
xcode_available = true
end
unless xcode_available
FastlaneCore::UI.error('#############################################################')
FastlaneCore::UI.error("# You have to install Xcode command line tools to use snapshot")
FastlaneCore::UI.error("# Install the latest version of Xcode from the AppStore")
FastlaneCore::UI.error("# Run xcode-select --install to install the developer tools")
FastlaneCore::UI.error('#############################################################')
FastlaneCore::UI.user_error!("Run 'xcode-select --install' and start snapshot again")
end
if Snapshot::LatestOsVersion.ios_version.to_f < 9 # to_f is bad, but should be good enough
FastlaneCore::UI.error('#############################################################')
FastlaneCore::UI.error("# Your xcode-select Xcode version is below 7.0")
FastlaneCore::UI.error("# To use snapshot 1.0 and above you need at least iOS 9")
FastlaneCore::UI.error("# Set the path to the Xcode version that supports UI Tests")
FastlaneCore::UI.error("# or downgrade to versions older than snapshot 1.0")
FastlaneCore::UI.error('#############################################################')
FastlaneCore::UI.user_error!("Run 'sudo xcode-select -s /Applications/Xcode-beta.app'")
end
end
def self.check_simulators
FastlaneCore::UI.verbose("Found #{FastlaneCore::Simulator.all.count} simulators.")
if FastlaneCore::Simulator.all.count == 0
FastlaneCore::UI.error('#############################################################')
FastlaneCore::UI.error("# You have to add new simulators using Xcode")
FastlaneCore::UI.error("# You can let snapshot create new simulators: 'fastlane snapshot reset_simulators'")
FastlaneCore::UI.error("# Manually: Xcode => Window => Devices")
FastlaneCore::UI.error("# Please run `instruments -s` to verify your xcode path")
FastlaneCore::UI.error('#############################################################')
FastlaneCore::UI.user_error!("Create the new simulators and run this script again")
end
end
def self.check_simctl
simctl_available = nil
begin
simctl_available = `xcrun simctl`.include?("openurl")
rescue
simctl_available = true
end
unless simctl_available
FastlaneCore::UI.user_error!("Could not find `xcrun simctl`. Make sure you have the latest version of Xcode and macOS installed.")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/reports_generator.rb | snapshot/lib/snapshot/reports_generator.rb | require_relative 'module'
module Snapshot
class ReportsGenerator
require 'erb'
require 'fastimage'
def html_path
if Snapshot.config[:html_template]
Snapshot.config[:html_template]
else
File.join(Snapshot::ROOT, "lib", "snapshot/page.html.erb")
end
end
def generate
UI.message("Generating HTML Report")
screens_path = Snapshot.config[:output_directory]
@data_by_language = {}
@data_by_screen = {}
Dir[File.join(screens_path, "*")].sort.each do |language_folder|
language = File.basename(language_folder)
Dir[File.join(language_folder, '*.png')].sort.each do |screenshot|
file_name = File.basename(screenshot)
available_devices.each do |key_name, output_name|
next unless file_name.include?(key_name)
# This screenshot is from this device
@data_by_language[language] ||= {}
@data_by_language[language][output_name] ||= []
screen_name = file_name.sub(key_name + '-', '').sub('.png', '')
@data_by_screen[screen_name] ||= {}
@data_by_screen[screen_name][output_name] ||= {}
resulting_path = File.join('.', language, file_name)
@data_by_language[language][output_name] << resulting_path
@data_by_screen[screen_name][output_name][language] = resulting_path
break # to not include iPhone 6 and 6 Plus (name is contained in the other name)
end
end
end
html = ERB.new(File.read(html_path)).result(binding) # https://web.archive.org/web/20160430190141/www.rrn.dk/rubys-erb-templating-system
export_path = "#{screens_path}/screenshots.html"
File.write(export_path, html)
export_path = File.expand_path(export_path)
UI.success("Successfully created HTML file with an overview of all the screenshots: '#{export_path}'")
system("open '#{export_path}'") unless Snapshot.config[:skip_open_summary]
end
def xcode_8_and_below_device_name_mappings
# The order IS important, since those names are used to check for include?
# and the iPhone 6 is included in the iPhone 6 Plus
{
'AppleTV1080p' => 'Apple TV',
'iPhone7Plus' => "iPhone7Plus (5.5-Inch)",
'iPhone7' => "iPhone7 (4.7-Inch)",
'iPhone6sPlus' => "iPhone6sPlus (5.5-Inch)",
'iPhone6Plus' => "iPhone6Plus (5.5-Inch)",
'iPhone6s' => "iPhone6s (4.7-Inch)",
'iPhone6' => "iPhone6 (4.7-Inch)",
'iPhone5' => "iPhone5 (4-Inch)",
'iPhone4' => "iPhone4 (3.5-Inch)",
'iPhoneSE' => "iPhone SE",
'iPad2' => "iPad2",
'iPadAir2' => 'iPad Air 2',
'iPadPro(12.9-inch)' => 'iPad Air Pro (12.9-inch)',
'iPadPro(9.7-inch)' => 'iPad Air Pro (9.7-inch)',
'iPadPro(9.7inch)' => "iPad Pro (9.7-inch)",
'iPadPro(12.9inch)' => "iPad Pro (12.9-inch)",
'iPadPro' => "iPad Pro",
'iPad' => "iPad",
'Mac' => "Mac"
}
end
def xcode_9_and_above_device_name_mappings
{
# snapshot in Xcode 9 saves screenshots with the SIMULATOR_DEVICE_NAME
# which includes spaces
'iPhone 15 Pro Max' => "iPhone 15 Pro Max",
'iPhone 15 Pro' => "iPhone 15 Pro",
'iPhone 15 Plus' => "iPhone 15 Plus",
'iPhone 15' => "iPhone 15",
'iPhone 14 Pro Max' => "iPhone 14 Pro Max",
'iPhone 14 Pro' => "iPhone 14 Pro",
'iPhone 14 Plus' => "iPhone 14 Plus",
'iPhone 14' => "iPhone 14",
'iPhone SE (3rd generation)' => "iPhone SE (3rd generation)",
'iPhone 13 Pro Max' => "iPhone 13 Pro Max",
'iPhone 13 Pro' => "iPhone 13 Pro",
'iPhone 13 mini' => "iPhone 13 mini",
'iPhone 13' => "iPhone 13",
'iPhone 12 Pro Max' => "iPhone 12 Pro Max",
'iPhone 12 Pro' => "iPhone 12 Pro",
'iPhone 12 mini' => "iPhone 12 mini",
'iPhone 12' => "iPhone 12",
'iPhone SE (2nd generation)' => "iPhone SE (2nd generation)",
'iPhone 11 Pro Max' => "iPhone 11 Pro Max",
'iPhone 11 Pro' => "iPhone 11 Pro",
'iPhone 11' => "iPhone 11",
'iPhone XS Max' => "iPhone XS Max",
'iPhone XS' => "iPhone XS",
'iPhone XR' => "iPhone XR",
'iPhone 8 Plus' => "iPhone 8 Plus",
'iPhone 8' => "iPhone 8",
'iPhone X' => "iPhone X",
'iPhone 7 Plus' => "iPhone 7 Plus (5.5-Inch)",
'iPhone 7' => "iPhone 7 (4.7-Inch)",
'iPhone 6s Plus' => "iPhone 6s Plus (5.5-Inch)",
'iPhone 6 Plus' => "iPhone 6 Plus (5.5-Inch)",
'iPhone 6s' => "iPhone 6s (4.7-Inch)",
'iPhone 6' => "iPhone 6 (4.7-Inch)",
'iPhone 5s' => "iPhone 5s (4-Inch)",
'iPhone 5' => "iPhone 5 (4-Inch)",
'iPhone SE' => "iPhone SE",
'iPhone 4s' => "iPhone 4s (3.5-Inch)",
'iPad 2' => 'iPad 2',
'iPad Air (5th generation)' => 'iPad Air (5th generation)',
'iPad Air (4th generation)' => 'iPad Air (4th generation)',
'iPad Air (3rd generation)' => 'iPad Air (3rd generation)',
'iPad Air 2' => 'iPad Air 2',
'iPad Air' => 'iPad Air',
'iPad (10th generation)' => 'iPad (10th generation)',
'iPad (9th generation)' => 'iPad (9th generation)',
'iPad (8th generation)' => 'iPad (8th generation)',
'iPad (7th generation)' => 'iPad (7th generation)',
'iPad (6th generation)' => 'iPad (6th generation)',
'iPad (5th generation)' => 'iPad (5th generation)',
'iPad mini (6th generation)' => 'iPad mini (6th generation)',
'iPad mini (5th generation)' => 'iPad mini (5th generation)',
'iPad mini 4' => 'iPad mini 4',
'iPad mini 3' => 'iPad mini 3',
'iPad mini 2' => 'iPad mini 2',
'iPad Pro (9.7-inch)' => 'iPad Pro (9.7-inch)',
'iPad Pro (9.7 inch)' => 'iPad Pro (9.7-inch)', # iOS 10.3.1 simulator
'iPad Pro (10.5-inch)' => 'iPad Pro (10.5-inch)',
'iPad Pro (11-inch) (4th generation) (16GB)' => 'iPad Pro (11-inch) (4th generation) (16GB)',
'iPad Pro (11-inch) (4th generation)' => 'iPad Pro (11-inch) (4th generation)',
'iPad Pro (11-inch) (3rd generation)' => 'iPad Pro (11-inch) (3rd generation)',
'iPad Pro (11-inch) (2nd generation)' => 'iPad Pro (11-inch) (2nd generation)',
'iPad Pro (11-inch) (1st generation)' => 'iPad Pro (11-inch) (1st generation)',
'iPad Pro (11-inch)' => 'iPad Pro (11-inch)',
'iPad Pro (12.9-inch) (6th generation) (16GB)' => 'iPad Pro (12.9-inch) (6th generation) (16GB)',
'iPad Pro (12.9-inch) (6th generation)' => 'iPad Pro (12.9-inch) (6th generation)',
'iPad Pro (12.9-inch) (5th generation)' => 'iPad Pro (12.9-inch) (5th generation)',
'iPad Pro (12.9-inch) (4th generation)' => 'iPad Pro (12.9-inch) (4th generation)',
'iPad Pro (12.9-inch) (3rd generation)' => 'iPad Pro (12.9-inch) (3rd generation)',
'iPad Pro (12.9-inch) (2nd generation)' => 'iPad Pro (12.9-inch) (2nd generation)',
'iPad Pro (12.9-inch)' => 'iPad Pro (12.9-inch)',
'iPad Pro (12.9 inch)' => 'iPad Pro (12.9-inch)', # iOS 10.3.1 simulator
'iPad Pro' => 'iPad Pro (12.9-inch)', # iOS 9.3 simulator
'iPod touch (7th generation)' => 'iPod touch (7th generation)',
'Apple TV 4K (3rd generation)' => 'Apple TV 4K (3rd generation)',
'Apple TV 4K (3rd generation) (at 1080p)' => 'Apple TV 4K (3rd generation) (at 1080p)',
'Apple TV 4K (2nd generation)' => 'Apple TV 4K (2nd generation)',
'Apple TV 4K (2nd generation) (at 1080p)' => 'Apple TV 4K (2nd generation) (at 1080p)',
'Apple TV 4K (at 1080p)' => 'Apple TV 4K (at 1080p)',
'Apple TV 4K' => 'Apple TV 4K',
'Apple TV 1080p' => 'Apple TV',
'Apple TV' => 'Apple TV',
'Mac' => 'Mac',
'Apple Watch Ultra 2 (49mm)' => 'Apple Watch Ultra 2 (49mm)',
'Apple Watch SE (44mm)' => 'Apple Watch SE (44mm)',
'Apple Watch SE (40mm)' => 'Apple Watch SE (40mm)',
'Apple Watch Series 9 (45mm)' => 'Apple Watch Series 9 (45mm)',
'Apple Watch Series 9 (41mm)' => 'Apple Watch Series 9 (41mm)',
'Apple Watch Series 8 (45mm)' => 'Apple Watch Series 8 (45mm)',
'Apple Watch Series 8 (41mm)' => 'Apple Watch Series 8 (41mm)',
'Apple Watch Series 7 (45mm)' => 'Apple Watch Series 7 (45mm)',
'Apple Watch Series 7 (41mm)' => 'Apple Watch Series 7 (41mm)',
'Apple Watch Series 6 (44mm)' => 'Apple Watch Series 6 (44mm)',
'Apple Watch Series 6 (40mm)' => 'Apple Watch Series 6 (40mm)',
'Apple Watch Series 5 (44mm)' => 'Apple Watch Series 5 (44mm)',
'Apple Watch Series 5 (40mm)' => 'Apple Watch Series 5 (40mm)',
'Apple Watch Series 6 - 44mm' => 'Apple Watch Series 6 - 44mm',
'Apple Watch Series 5 - 44mm' => 'Apple Watch Series 5 - 44mm'
}
end
def available_devices
if Helper.xcode_at_least?("9.0")
return xcode_9_and_above_device_name_mappings
else
return xcode_8_and_below_device_name_mappings
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/commands_generator.rb | snapshot/lib/snapshot/commands_generator.rb | require 'commander'
require 'fastlane_core/ui/help_formatter'
require_relative 'module'
require_relative 'runner'
require_relative 'options'
HighLine.track_eof = false
module Snapshot
class CommandsGenerator
include Commander::Methods
def self.start
self.new.run
end
def run
program :name, 'snapshot'
program :version, Fastlane::VERSION
program :description, 'CLI for \'snapshot\' - Automate taking localized screenshots of your iOS app on every device'
program :help, 'Author', 'Felix Krause <snapshot@krausefx.com>'
program :help, 'Website', 'https://fastlane.tools'
program :help, 'Documentation', 'https://docs.fastlane.tools/actions/snapshot/'
program :help_formatter, FastlaneCore::HelpFormatter
global_option('--verbose', 'Shows a more verbose output') { FastlaneCore::Globals.verbose = true }
always_trace!
command :run do |c|
c.syntax = 'fastlane snapshot'
c.description = 'Take new screenshots based on the Snapfile.'
FastlaneCore::CommanderGenerator.new.generate(Snapshot::Options.available_options, command: c)
c.action do |args, options|
load_config(options)
Snapshot::DependencyChecker.check_simulators
Snapshot::Runner.new.work
end
end
command :init do |c|
c.syntax = 'fastlane snapshot init'
c.description = "Creates a new Snapfile in the current directory"
c.action do |args, options|
require 'snapshot/setup'
path = Snapshot::Helper.fastlane_enabled? ? FastlaneCore::FastlaneFolder.path : '.'
is_swift_fastfile = args.include?("swift")
Snapshot::Setup.create(path, is_swift_fastfile: is_swift_fastfile)
end
end
command :update do |c|
c.syntax = 'fastlane snapshot update'
c.description = "Updates your SnapshotHelper.swift to the latest version"
c.option('--force', 'Disables confirmation prompts')
c.action do |args, options|
require 'snapshot/update'
Snapshot::Update.new.update(force: options.force)
end
end
command :reset_simulators do |c|
c.syntax = 'fastlane snapshot reset_simulators'
c.description = "This will remove all your existing simulators and re-create new ones"
c.option('-i', '--ios_version String', String, 'The comma separated list of iOS Versions you want to use')
c.option('--force', 'Disables confirmation prompts')
c.action do |args, options|
options.default(ios_version: Snapshot::LatestOsVersion.ios_version)
versions = options.ios_version.split(',') if options.ios_version
require 'snapshot/reset_simulators'
Snapshot::ResetSimulators.clear_everything!(versions, options.force)
end
end
command :clear_derived_data do |c|
c.syntax = 'fastlane snapshot clear_derived_data -f path'
c.description = "Clear the directory where build products and other derived data will go"
FastlaneCore::CommanderGenerator.new.generate(Snapshot::Options.available_options, command: c)
c.action do |args, options|
load_config(options)
derived_data_path = Snapshot.config[:derived_data_path]
if !derived_data_path
Snapshot::UI.user_error!("No derived_data_path")
elsif !Dir.exist?(derived_data_path)
Snapshot::UI.important("Path #{derived_data_path} does not exist")
else
FileUtils.rm_rf(derived_data_path)
Snapshot::UI.success("Removed #{derived_data_path}")
end
end
end
default_command(:run)
run!
end
private
def load_config(options)
o = options.__hash__.dup
o.delete(:verbose)
Snapshot.config = FastlaneCore::Configuration.create(Snapshot::Options.available_options, o)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/latest_os_version.rb | snapshot/lib/snapshot/latest_os_version.rb | require 'open3'
require 'fastlane_core/ui/ui'
module Snapshot
class LatestOsVersion
def self.ios_version
return ENV["SNAPSHOT_IOS_VERSION"] if FastlaneCore::Env.truthy?("SNAPSHOT_IOS_VERSION")
self.version("iOS")
end
@versions = {}
def self.version(os)
@versions[os] ||= version_for_os(os)
end
def self.version_for_os(os)
# We do all this, because we would get all kind of crap output generated by xcodebuild
# so we need to ignore stderror
stdout, _stderr, _status = Open3.capture3('xcodebuild -version -sdk')
matched = stdout.match(/#{os} ([\d\.]+) \(.*/)
if matched.nil?
FastlaneCore::UI.user_error!("Could not determine installed #{os} SDK version. Try running the _xcodebuild_ command manually to ensure it works.")
elsif matched.length > 1
return matched[1]
else
FastlaneCore::UI.user_error!("Could not determine installed #{os} SDK version. Please pass it via the environment variable 'SNAPSHOT_IOS_VERSION'")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/error_handler.rb | snapshot/lib/snapshot/error_handler.rb | require_relative 'module'
module Snapshot
class ErrorHandler
class << self
# @param [Array] The output of the errored build (line by line)
# This method should raise an exception in any case, as the return code indicated a failed build
def handle_test_error(output, return_code)
# The order of the handling below is import
if return_code == 65
UI.user_error!("Tests failed - check out the log above")
end
case output
when /com\.apple\.CoreSimulator\.SimError/
UI.important("The simulator failed to launch - retrying...")
when /is not configured for Running/
UI.user_error!("Scheme is not properly configured, make sure to check out the snapshot README")
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/runner.rb | snapshot/lib/snapshot/runner.rb | require 'shellwords'
require 'plist'
require 'os'
require 'thread'
require 'terminal-table'
require 'fastlane_core/print_table'
require_relative 'module'
require_relative 'update'
require_relative 'test_command_generator'
require_relative 'reports_generator'
require_relative 'simulator_launchers/simulator_launcher'
require_relative 'simulator_launchers/simulator_launcher_xcode_8'
require_relative 'simulator_launchers/launcher_configuration'
module Snapshot
class Runner
def work
if File.exist?("./fastlane/snapshot.js") || File.exist?("./snapshot.js")
UI.error("Found old snapshot configuration file 'snapshot.js'")
UI.error("You updated to snapshot 1.0 which now uses UI Automation")
UI.error("Please follow the migration guide: https://github.com/fastlane/fastlane/blob/master/snapshot/MigrationGuide.md")
UI.error("And read the updated documentation: https://docs.fastlane.tools/actions/snapshot/")
sleep(3) # to be sure the user sees this, as compiling clears the screen
end
Snapshot.config[:output_directory] = File.expand_path(Snapshot.config[:output_directory])
verify_helper_is_current
# Also print out the path to the used Xcode installation
# We go 2 folders up, to not show "Contents/Developer/"
values = Snapshot.config.values(ask: false)
values[:xcode_path] = File.expand_path("../..", FastlaneCore::Helper.xcode_path)
FastlaneCore::PrintTable.print_values(config: values, hide_keys: [], title: "Summary for snapshot #{Fastlane::VERSION}")
clear_previous_screenshots if Snapshot.config[:clear_previous_screenshots]
UI.success("Building and running project - this might take some time...")
launcher_config = SimulatorLauncherConfiguration.new(snapshot_config: Snapshot.config)
if Helper.xcode_at_least?(9)
launcher = SimulatorLauncher.new(launcher_configuration: launcher_config)
results = launcher.take_screenshots_simultaneously
else
launcher = SimulatorLauncherXcode8.new(launcher_configuration: launcher_config)
results = launcher.take_screenshots_one_simulator_at_a_time
end
print_results(results)
UI.test_failure!(launcher.collected_errors.uniq.join('; ')) if launcher.collected_errors.count > 0
# Generate HTML report
ReportsGenerator.new.generate
# Clear the Derived Data
unless Snapshot.config[:derived_data_path]
# this should actually be launcher.derived_data_path
FileUtils.rm_rf(TestCommandGeneratorBase.derived_data_path)
end
end
def print_results(results)
return if results.count == 0
rows = []
results.each do |device, languages|
current = [device]
languages.each do |language, value|
current << (value == true ? " 💚" : " ❌")
end
rows << current
end
params = {
rows: FastlaneCore::PrintTable.transform_output(rows),
headings: ["Device"] + results.values.first.keys,
title: "snapshot results"
}
puts("")
puts(Terminal::Table.new(params))
puts("")
end
def clear_previous_screenshots
UI.important("Clearing previously generated screenshots")
path = File.join(Snapshot.config[:output_directory], "*", "*.png")
Dir[path].each do |current|
UI.verbose("Deleting #{current}")
File.delete(current)
end
end
# Depending on the Xcode version, the return value is different
def self.path_to_helper_file_from_gem
runner_dir = File.dirname(__FILE__)
if Helper.xcode_at_least?("9.0")
return File.expand_path('../assets/SnapshotHelper.swift', runner_dir)
else
return File.expand_path('../assets/SnapshotHelperXcode8.swift', runner_dir)
end
end
def version_of_bundled_helper
asset_path = self.class.path_to_helper_file_from_gem
regex_to_use = Helper.xcode_at_least?("9.0") ? /\n.*SnapshotHelperVersion \[.+\]/ : /\n.*SnapshotHelperXcode8Version \[.+\]/
bundled_helper = File.read(asset_path)
current_version = bundled_helper.match(regex_to_use)[0]
# Something like "// SnapshotHelperVersion [1.2]", but be relaxed about whitespace
return current_version.gsub(%r{^//\w*}, '').strip
end
# rubocop:disable Style/Next
def verify_helper_is_current
return if Snapshot.config[:skip_helper_version_check]
current_version = version_of_bundled_helper
UI.verbose("Checking that helper files contain #{current_version}")
helper_files = Update.find_helper
if helper_files.empty?
UI.error("Your Snapshot Helper file is missing, please place a copy")
UI.error("in your project directory")
UI.message("More information about Snapshot setup can be found here:")
UI.message("https://docs.fastlane.tools/actions/snapshot/#quick-start")
UI.user_error!("Please add a Snapshot Helper file to your project")
return
end
helper_files.each do |path|
content = File.read(path)
unless content.include?(current_version)
UI.error("Your '#{path}' is outdated, please run `fastlane snapshot update`")
UI.error("to update your Helper file")
UI.user_error!("Please update your Snapshot Helper file using `fastlane snapshot update`")
end
end
end
# rubocop:enable Style/Next
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/test_command_generator_xcode_8.rb | snapshot/lib/snapshot/test_command_generator_xcode_8.rb | require_relative 'test_command_generator_base'
require_relative 'module'
require_relative 'latest_os_version'
module Snapshot
# Responsible for building the fully working xcodebuild command
# This TestCommandGenerator supports Xcode 8's `xcodebuild` requirements
# It is its own object, as the logic differs for how we want to handle
# creating `xcodebuild` commands for Xcode 9 (see test_command_generator.rb)
class TestCommandGeneratorXcode8 < TestCommandGeneratorBase
class << self
def generate(device_type: nil, language: nil, locale: nil)
parts = prefix
parts << "xcodebuild"
parts += options(language, locale)
parts += destination(device_type)
parts += build_settings(language, locale)
parts += actions
parts += suffix
parts += pipe(device_type, language, locale)
return parts
end
def pipe(device_type, language, locale)
log_path = xcodebuild_log_path(device_type: device_type, language: language, locale: locale)
pipe = ["| tee #{log_path.shellescape}"]
pipe << "| xcpretty #{Snapshot.config[:xcpretty_args]}"
pipe << "> /dev/null" if Snapshot.config[:suppress_xcode_output]
return pipe
end
def destination(device_name)
# on Mac we will always run on host machine, so should specify only platform
return ["-destination 'platform=macOS'"] if device_name =~ /^Mac/
# if device_name is nil, use the config and get all devices
os = device_name =~ /^Apple TV/ ? "tvOS" : "iOS"
os_version = Snapshot.config[:ios_version] || Snapshot::LatestOsVersion.version(os)
device = find_device(device_name, os_version)
if device.nil?
UI.user_error!("No device found named '#{device_name}' for version '#{os_version}'")
elsif device.os_version != os_version
UI.important("Using device named '#{device_name}' with version '#{device.os_version}' because no match was found for version '#{os_version}'")
end
value = "platform=#{os} Simulator,id=#{device.udid},OS=#{device.os_version}"
return ["-destination '#{value}'"]
end
def xcodebuild_log_path(device_type: nil, language: nil, locale: nil)
name_components = [Snapshot.project.app_name, Snapshot.config[:scheme]]
if Snapshot.config[:namespace_log_files]
name_components << device_type if device_type
name_components << language if language
name_components << locale if locale
end
file_name = "#{name_components.join('-')}.log"
containing = File.expand_path(Snapshot.config[:buildlog_path])
FileUtils.mkdir_p(containing)
return File.join(containing, file_name)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/reset_simulators.rb | snapshot/lib/snapshot/reset_simulators.rb | require 'fastlane_core/device_manager'
require_relative 'module'
module Snapshot
class ResetSimulators
def self.clear_everything!(ios_versions, force = false)
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# !! Warning: This script will remove all your existing simulators !!
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
sure = true if FastlaneCore::Env.truthy?("SNAPSHOT_FORCE_DELETE") || force
begin
sure = UI.confirm("Are you sure? All your simulators will be DELETED and new ones will be created! (You can use `SNAPSHOT_FORCE_DELETE` to skip this confirmation)") unless sure
rescue => e
UI.user_error!("Please make sure to pass the `--force` option to reset simulators when running in non-interactive mode") unless UI.interactive?
raise e
end
UI.abort_with_message!("User cancelled action") unless sure
if ios_versions
ios_versions.each do |version|
FastlaneCore::Simulator.delete_all_by_version(os_version: version)
end
else
FastlaneCore::Simulator.delete_all
end
FastlaneCore::SimulatorTV.delete_all
FastlaneCore::SimulatorWatch.delete_all
all_runtime_type = runtimes
# == Runtimes ==
# iOS 9.3 (9.3 - 13E233) (com.apple.CoreSimulator.SimRuntime.iOS-9-3)
# iOS 10.0 (10.0 - 14A345) (com.apple.CoreSimulator.SimRuntime.iOS-10-0)
# iOS 10.1 (10.1 - 14B72) (com.apple.CoreSimulator.SimRuntime.iOS-10-1)
# iOS 10.2 (10.2 - 14C89) (com.apple.CoreSimulator.SimRuntime.iOS-10-2)
# tvOS 10.1 (10.1 - 14U591) (com.apple.CoreSimulator.SimRuntime.tvOS-10-1)
# watchOS 3.1 (3.1 - 14S471a) (com.apple.CoreSimulator.SimRuntime.watchOS-3-1)
#
# Xcode 9 changed the format
# == Runtimes ==
# iOS 11.0 (11.0 - 15A5361a) - com.apple.CoreSimulator.SimRuntime.iOS-11-0
# tvOS 11.0 (11.0 - 15J5368a) - com.apple.CoreSimulator.SimRuntime.tvOS-11-0
# watchOS 4.0 (4.0 - 15R5363a) - com.apple.CoreSimulator.SimRuntime.watchOS-4-0
ios_versions_ids = filter_runtimes(all_runtime_type, 'iOS', ios_versions)
tv_version_ids = filter_runtimes(all_runtime_type, 'tvOS')
watch_versions_ids = filter_runtimes(all_runtime_type, 'watchOS')
all_device_types = `xcrun simctl list devicetypes`.scan(/(.*)\s\((.*)\)/)
# == Device Types ==
# iPhone 4s (com.apple.CoreSimulator.SimDeviceType.iPhone-4s)
# iPhone 5 (com.apple.CoreSimulator.SimDeviceType.iPhone-5)
# iPhone 5s (com.apple.CoreSimulator.SimDeviceType.iPhone-5s)
# iPhone 6 (com.apple.CoreSimulator.SimDeviceType.iPhone-6)
all_device_types.each do |device_type|
if device_type.join(' ').include?("Watch")
create(device_type, watch_versions_ids, 'watchOS')
elsif device_type.join(' ').include?("TV")
create(device_type, tv_version_ids, 'tvOS')
else
create(device_type, ios_versions_ids)
end
end
make_phone_watch_pair
end
def self.create(device_type, os_versions, os_name = 'iOS')
os_versions.each do |os_version|
puts("Creating #{device_type[0]} for #{os_name} version #{os_version[0]}")
command = "xcrun simctl create '#{device_type[0]}' #{device_type[1]} #{os_version[1]}"
UI.command(command) if FastlaneCore::Globals.verbose?
`#{command}`
end
end
def self.filter_runtimes(all_runtimes, os = 'iOS', versions = [])
all_runtimes.select { |v, id| v[/^#{os}/] }.select { |v, id| v[/#{versions.join("|")}$/] }.uniq
end
def self.devices
all_devices = Helper.backticks('xcrun simctl list devices', print: FastlaneCore::Globals.verbose?)
# == Devices ==
# -- iOS 9.0 --
# iPhone 4s (32246EBC-33B0-47F9-B7BB-5C23C550DF29) (Shutdown)
# iPhone 5 (4B56C101-6B95-43D1-9485-3FBA0E127FFA) (Shutdown)
# iPhone 5s (6379C204-E82A-4FBD-8A22-6A01C7791D62) (Shutdown)
# -- Unavailable: com.apple.CoreSimulator.SimRuntime.iOS-8-4 --
# iPhone 4s (FE9D6F85-1C51-4FE6-8597-FCAB5286B869) (Shutdown) (unavailable, runtime profile not found)
result = all_devices.lines.map do |line|
(line.match(/\s+(.+?)\s\(([\w\-]+)\).*/) || []).to_a
end
result.select { |parsed| parsed.length == 3 } # we don't care about those headers
end
def self.runtimes
Helper.backticks('xcrun simctl list runtimes', print: FastlaneCore::Globals.verbose?).scan(/(.*)\s\(\d.*(com\.apple[^)\s]*)/)
end
def self.make_phone_watch_pair
phones = []
watches = []
devices.each do |device|
full_line, name, id = device
phones << id if name.start_with?('iPhone 6') && device_line_usable?(full_line)
watches << id if name.end_with?('mm') && device_line_usable?(full_line)
end
if phones.any? && watches.any?
puts("Creating device pair of #{phones.last} and #{watches.last}")
Helper.backticks("xcrun simctl pair #{watches.last} #{phones.last}", print: FastlaneCore::Globals.verbose?)
end
end
def self.device_line_usable?(line)
!line.include?("unavailable")
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/module.rb | snapshot/lib/snapshot/module.rb | require 'fastlane_core/helper'
require 'fastlane/boolean'
require_relative 'detect_values'
require_relative 'dependency_checker'
module Snapshot
# Use this to just setup the configuration attribute and set it later somewhere else
class << self
attr_accessor :config
attr_accessor :project
attr_accessor :cache
def config=(value)
@config = value
DetectValues.set_additional_default_values
@cache = {}
end
def snapfile_name
"Snapfile"
end
def kill_simulator
`killall 'iOS Simulator' &> /dev/null`
`killall Simulator &> /dev/null`
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__))
DESCRIPTION = "Automate taking localized screenshots of your iOS and tvOS apps on every device"
CACHE_DIR = File.join(Dir.home, "Library/Caches/tools.fastlane")
SCREENSHOTS_DIR = File.join(CACHE_DIR, 'screenshots')
Boolean = Fastlane::Boolean
Snapshot::DependencyChecker.check_dependencies
def self.min_xcode7?
xcode_version.split(".").first.to_i >= 7
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/screenshot_rotate.rb | snapshot/lib/snapshot/screenshot_rotate.rb | require_relative 'module'
require 'fastlane_core/fastlane_pty'
module Snapshot
# This class takes care of rotating images
class ScreenshotRotate
require 'shellwords'
# @param (String) The path in which the screenshots are located in
def run(path)
UI.verbose("Rotating the screenshots (if necessary)")
rotate(path)
end
def rotate(path)
Dir.glob([path, '/**/*.png'].join('/')).each do |file|
UI.verbose("Rotating '#{file}'")
command = nil
if file.end_with?("landscapeleft.png")
command = "sips -r -90 '#{file}'"
elsif file.end_with?("landscaperight.png")
command = "sips -r 90 '#{file}'"
elsif file.end_with?("portrait_upsidedown.png")
command = "sips -r 180 '#{file}'"
end
# Only rotate if we need to
next unless command
# Rotate
FastlaneCore::CommandExecutor.execute(command: command, print_all: false, print_command: false)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/test_command_generator_base.rb | snapshot/lib/snapshot/test_command_generator_base.rb | require 'fastlane_core/device_manager'
require_relative 'module'
module Snapshot
class TestCommandGeneratorBase
class << self
def prefix
["set -o pipefail &&"]
end
# Path to the project or workspace as parameter
# This will also include the scheme (if given)
# @return [Array] The array with all the components to join
def project_path_array
proj = Snapshot.project.xcodebuild_parameters
return proj if proj.count > 0
UI.user_error!("No project/workspace found")
end
def options(language, locale)
config = Snapshot.config
result_bundle_path = resolve_result_bundle_path(language, locale) if config[:result_bundle]
options = []
options += project_path_array
options << "-sdk '#{config[:sdk]}'" if config[:sdk]
if derived_data_path && !options.include?("-derivedDataPath #{derived_data_path.shellescape}")
options << "-derivedDataPath #{derived_data_path.shellescape}"
end
options << "-resultBundlePath '#{result_bundle_path}'" if result_bundle_path
if FastlaneCore::Helper.xcode_at_least?(11)
options << "-testPlan '#{config[:testplan]}'" if config[:testplan]
end
options << config[:xcargs] if config[:xcargs]
# detect_values will ensure that these values are present as Arrays if
# they are present at all
options += config[:only_testing].map { |test_id| "-only-testing:#{test_id.shellescape}" } if config[:only_testing]
options += config[:skip_testing].map { |test_id| "-skip-testing:#{test_id.shellescape}" } if config[:skip_testing]
return options
end
def build_settings(language, locale)
config = Snapshot.config
build_settings = []
build_settings << "FASTLANE_SNAPSHOT=YES"
build_settings << "FASTLANE_LANGUAGE=#{language}" if language
build_settings << "FASTLANE_LOCALE=#{locale}" if locale
build_settings << "TEST_TARGET_NAME=#{config[:test_target_name].shellescape}" if config[:test_target_name]
return build_settings
end
def actions
actions = []
if Snapshot.config[:test_without_building]
actions << "test-without-building"
else
actions << :clean if Snapshot.config[:clean]
actions << :build # https://github.com/fastlane/fastlane/issues/2581
actions << :test
end
return actions
end
def suffix
return []
end
def find_device(device_name, os_version = Snapshot.config[:ios_version])
# We might get this error message
# > The requested device could not be found because multiple devices matched the request.
#
# This happens when you have multiple simulators for a given device type / iOS combination
# { platform:iOS Simulator, id:1685B071-AFB2-4DC1-BE29-8370BA4A6EBD, OS:9.0, name:iPhone 5 }
# { platform:iOS Simulator, id:A141F23B-96B3-491A-8949-813B376C28A7, OS:9.0, name:iPhone 5 }
#
simulators = FastlaneCore::DeviceManager.simulators
# Sort devices with matching names by OS version, largest first, so that we can
# pick the device with the newest OS in case an exact OS match is not available
name_matches = simulators.find_all { |sim| sim.name.strip == device_name.strip }
.sort_by { |sim| Gem::Version.new(sim.os_version) }
.reverse
return name_matches.find { |sim| sim.os_version == os_version } || name_matches.first
end
def device_udid(device_name, os_version = Snapshot.config[:ios_version])
device = find_device(device_name, os_version)
return device ? device.udid : nil
end
def derived_data_path
Snapshot.cache[:derived_data_path] ||= (Snapshot.config[:derived_data_path] || Dir.mktmpdir("snapshot_derived"))
end
def resolve_result_bundle_path(language, locale)
Snapshot.cache[:result_bundle_path] = {}
language_key = locale || language
unless Snapshot.cache[:result_bundle_path][language_key]
ext = FastlaneCore::Helper.xcode_at_least?(11) ? '.xcresult' : '.test_result'
path = File.join(Snapshot.config[:output_directory], "test_output", language_key, Snapshot.config[:scheme]) + ext
if File.directory?(path)
FileUtils.remove_dir(path)
end
Snapshot.cache[:result_bundle_path][language_key] = path
end
return Snapshot.cache[:result_bundle_path][language_key]
end
def initialize
not_implemented(__method__)
end
def pipe(device_type, language, locale)
not_implemented(__method__)
end
def destination(device_name)
not_implemented(__method__)
end
def xcodebuild_log_path(device_type: nil, language: nil, locale: nil)
not_implemented(__method__)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/simulator_launchers/launcher_configuration.rb | snapshot/lib/snapshot/simulator_launchers/launcher_configuration.rb | module Snapshot
class SimulatorLauncherConfiguration
# both
attr_accessor :languages
attr_accessor :devices
attr_accessor :add_photos
attr_accessor :add_videos
attr_accessor :clean
attr_accessor :erase_simulator
attr_accessor :headless
attr_accessor :localize_simulator
attr_accessor :dark_mode
attr_accessor :reinstall_app
attr_accessor :app_identifier
attr_accessor :disable_slide_to_type
attr_accessor :override_status_bar
attr_accessor :override_status_bar_arguments
# xcode 8
attr_accessor :number_of_retries
attr_accessor :stop_after_first_error
attr_accessor :output_simulator_logs
# runner
attr_accessor :launch_args_set
attr_accessor :output_directory
# xcode 9
attr_accessor :concurrent_simulators
alias concurrent_simulators? concurrent_simulators
def initialize(snapshot_config: nil)
@languages = snapshot_config[:languages]
@devices = snapshot_config[:devices]
@add_photos = snapshot_config[:add_photos]
@add_videos = snapshot_config[:add_videos]
@clean = snapshot_config[:clean]
@erase_simulator = snapshot_config[:erase_simulator]
@headless = snapshot_config[:headless]
@localize_simulator = snapshot_config[:localize_simulator]
@dark_mode = snapshot_config[:dark_mode]
@reinstall_app = snapshot_config[:reinstall_app]
@app_identifier = snapshot_config[:app_identifier]
@number_of_retries = snapshot_config[:number_of_retries]
@stop_after_first_error = snapshot_config[:stop_after_first_error]
@output_simulator_logs = snapshot_config[:output_simulator_logs]
@output_directory = snapshot_config[:output_directory]
@concurrent_simulators = snapshot_config[:concurrent_simulators]
@disable_slide_to_type = snapshot_config[:disable_slide_to_type]
@override_status_bar = snapshot_config[:override_status_bar]
@override_status_bar_arguments = snapshot_config[:override_status_bar_arguments]
launch_arguments = Array(snapshot_config[:launch_arguments])
# if more than 1 set of arguments, use a tuple with an index
if launch_arguments.count == 0
@launch_args_set = [[""]]
elsif launch_arguments.count == 1
@launch_args_set = [launch_arguments]
else
@launch_args_set = launch_arguments.map.with_index { |e, i| [i, e] }
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/simulator_launchers/simulator_launcher_xcode_8.rb | snapshot/lib/snapshot/simulator_launchers/simulator_launcher_xcode_8.rb | require_relative 'simulator_launcher_base'
require_relative '../error_handler'
require_relative '../collector'
require_relative '../test_command_generator_xcode_8'
module Snapshot
class SimulatorLauncherXcode8 < SimulatorLauncherBase
def take_screenshots_one_simulator_at_a_time
results = {} # collect all the results for a nice table
launcher_config.devices.each_with_index do |device, device_index|
# launch_args_set always has at at least 1 item (could be "")
launcher_config.launch_args_set.each do |launch_args|
launcher_config.languages.each_with_index do |language, language_index|
locale = nil
if language.kind_of?(Array)
locale = language[1]
language = language[0]
end
results[device] ||= {}
current_run = device_index * launcher_config.languages.count + language_index + 1
number_of_runs = launcher_config.languages.count * launcher_config.devices.count
UI.message("snapshot run #{current_run} of #{number_of_runs}")
results[device][language] = run_for_device_and_language(language, locale, device, launch_args)
copy_simulator_logs([device], language, locale, launch_args)
end
end
end
results
end
# This is its own method so that it can re-try if the tests fail randomly
# @return true/false depending on if the tests succeeded
def run_for_device_and_language(language, locale, device, launch_arguments, retries = 0)
return launch_one_at_a_time(language, locale, device, launch_arguments)
rescue => ex
UI.error(ex.to_s) # show the reason for failure to the user, but still maybe retry
if retries < launcher_config.number_of_retries
UI.important("Tests failed, re-trying #{retries + 1} out of #{launcher_config.number_of_retries + 1} times")
run_for_device_and_language(language, locale, device, launch_arguments, retries + 1)
else
UI.error("Backtrace:\n\t#{ex.backtrace.join("\n\t")}") if FastlaneCore::Globals.verbose?
self.collected_errors << ex
raise ex if launcher_config.stop_after_first_error
return false # for the results
end
end
# Returns true if it succeeded
def launch_one_at_a_time(language, locale, device_type, launch_arguments)
prepare_for_launch([device_type], language, locale, launch_arguments)
add_media([device_type], :photo, launcher_config.add_photos) if launcher_config.add_photos
add_media([device_type], :video, launcher_config.add_videos) if launcher_config.add_videos
open_simulator_for_device(device_type)
command = TestCommandGeneratorXcode8.generate(device_type: device_type, language: language, locale: locale)
if locale
UI.header("#{device_type} - #{language} (#{locale})")
else
UI.header("#{device_type} - #{language}")
end
execute(command: command, language: language, locale: locale, device_type: device_type, launch_args: launch_arguments)
raw_output = File.read(TestCommandGeneratorXcode8.xcodebuild_log_path(device_type: device_type, language: language, locale: locale))
dir_name = locale || language
return Collector.fetch_screenshots(raw_output, dir_name, device_type, launch_arguments.first)
end
def execute(command: nil, language: nil, locale: nil, device_type: nil, launch_args: nil)
prefix_hash = [
{
prefix: "Running Tests: ",
block: proc do |value|
value.include?("Touching")
end
}
]
FastlaneCore::CommandExecutor.execute(command: command,
print_all: true,
print_command: true,
prefix: prefix_hash,
loading: "Loading...",
error: proc do |output, return_code|
ErrorHandler.handle_test_error(output, return_code)
# no exception raised... that means we need to retry
UI.error("Caught error... #{return_code}")
self.current_number_of_retries_due_to_failing_simulator += 1
if self.current_number_of_retries_due_to_failing_simulator < 20
launch_one_at_a_time(language, locale, device_type, launch_arguments)
else
# It's important to raise an error, as we don't want to collect the screenshots
UI.crash!("Too many errors... no more retries...")
end
end)
end
def open_simulator_for_device(device_name)
return unless FastlaneCore::Env.truthy?('FASTLANE_EXPLICIT_OPEN_SIMULATOR')
device = TestCommandGeneratorBase.find_device(device_name)
FastlaneCore::Simulator.launch(device) if device
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/simulator_launchers/simulator_launcher.rb | snapshot/lib/snapshot/simulator_launchers/simulator_launcher.rb | require 'fastlane_core/test_parser'
require_relative 'simulator_launcher_base'
module Snapshot
class CPUInspector
def self.hwprefs_available?
`which hwprefs` != ''
end
def self.cpu_count
@cpu_count ||=
case RUBY_PLATFORM
when /darwin9/
`hwprefs cpu_count`.to_i
when /darwin10/
(hwprefs_available? ? `hwprefs thread_count` : `sysctl -n hw.physicalcpu_max`).to_i
when /linux/
UI.user_error!("We detected that you are running snapshot on Linux, but snapshot is only supported on macOS")
when /freebsd/
UI.user_error!("We detected that you are running snapshot on FreeBSD, but snapshot is only supported on macOS")
else
if RbConfig::CONFIG['host_os'] =~ /darwin/
(hwprefs_available? ? `hwprefs thread_count` : `sysctl -n hw.physicalcpu_max`).to_i
else
UI.crash!("Cannot find the machine's processor count.")
end
end
end
end
class SimulatorLauncher < SimulatorLauncherBase
# With Xcode 9's ability to run tests on multiple concurrent simulators,
# this method sets the maximum number of simulators to run simultaneously
# to avoid overloading your machine.
def default_number_of_simultaneous_simulators
cpu_count = CPUInspector.cpu_count
if cpu_count <= 2
return cpu_count
end
return cpu_count - 1
end
def take_screenshots_simultaneously
languages_finished = {}
launcher_config.launch_args_set.each do |launch_args|
launcher_config.languages.each_with_index do |language, language_index|
locale = nil
if language.kind_of?(Array)
locale = language[1]
language = language[0]
end
# Clear logs so subsequent xcodebuild executions don't append to old ones
log_path = xcodebuild_log_path(language: language, locale: locale)
File.delete(log_path) if File.exist?(log_path)
# Break up the array of devices into chunks that can
# be run simultaneously.
if launcher_config.concurrent_simulators?
all_devices = launcher_config.devices
# We have to break up the concurrent simulators by device version too, otherwise there is an error (see #10969)
by_simulator_version = all_devices.group_by { |d| FastlaneCore::DeviceManager.latest_simulator_version_for_device(d) }.values
device_batches = by_simulator_version.flat_map { |a| a.each_slice(default_number_of_simultaneous_simulators).to_a }
else
# Put each device in it's own array to run tests one at a time
device_batches = launcher_config.devices.map { |d| [d] }
end
device_batches.each do |devices|
languages_finished[language] = launch_simultaneously(devices, language, locale, launch_args)
end
end
end
launcher_config.devices.each_with_object({}) do |device, results_hash|
results_hash[device] = languages_finished
end
end
def launch_simultaneously(devices, language, locale, launch_arguments)
prepare_for_launch(devices, language, locale, launch_arguments)
add_media(devices, :photo, launcher_config.add_photos) if launcher_config.add_photos
add_media(devices, :video, launcher_config.add_videos) if launcher_config.add_videos
command = TestCommandGenerator.generate(
devices: devices,
language: language,
locale: locale,
log_path: xcodebuild_log_path(language: language, locale: locale)
)
devices.each { |device_type| override_status_bar(device_type, launcher_config.override_status_bar_arguments) } if launcher_config.override_status_bar
UI.important("Running snapshot on: #{devices.join(', ')}")
execute(command: command, language: language, locale: locale, launch_args: launch_arguments, devices: devices)
devices.each { |device_type| clear_status_bar(device_type) } if launcher_config.override_status_bar
return copy_screenshots(language: language, locale: locale, launch_args: launch_arguments)
end
def execute(retries = 0, command: nil, language: nil, locale: nil, launch_args: nil, devices: nil)
prefix_hash = [
{
prefix: "Running Tests: ",
block: proc do |value|
value.include?("Touching")
end
}
]
error_proc = proc do |output, return_code|
self.collected_errors.concat(failed_devices.map do |device, messages|
"#{device}: #{messages.join(', ')}"
end)
cleanup_after_failure(devices, language, locale, launch_args, return_code)
# no exception raised... that means we need to retry
UI.error("Caught error... #{return_code}")
self.current_number_of_retries_due_to_failing_simulator += 1
if self.current_number_of_retries_due_to_failing_simulator < 20 && return_code != 65
# If the return code is not 65, we should assume its a simulator failure and retry
launch_simultaneously(devices, language, locale, launch_args)
elsif retries < launcher_config.number_of_retries
# If there are retries remaining, run the tests again
retry_tests(retries, command, language, locale, launch_args, devices)
else
# It's important to raise an error, as we don't want to collect the screenshots
UI.crash!("Too many errors... no more retries...") if launcher_config.stop_after_first_error
end
end
FastlaneCore::CommandExecutor.execute(command: command,
print_all: true,
print_command: true,
prefix: prefix_hash,
loading: "Loading...",
error: error_proc)
end
def cleanup_after_failure(devices, language, locale, launch_args, return_code)
copy_screenshots(language: language, locale: locale, launch_args: launch_args)
UI.important("Tests failed while running on: #{devices.join(', ')}")
UI.important("For more detail about the test failures, check the logs here:")
UI.important(xcodebuild_log_path(language: language, locale: locale))
UI.important(" ")
UI.important("You can also find the test result data here:")
UI.important(test_results_path)
UI.important(" ")
UI.important("You can find the incomplete screenshots here:")
UI.important(SCREENSHOTS_DIR)
UI.important(launcher_config.output_directory)
end
def retry_tests(retries, command, language, locale, launch_args, devices)
UI.important("Retrying on devices: #{devices.join(', ')}")
UI.important("Number of retries remaining: #{launcher_config.number_of_retries - retries - 1}")
# Make sure all needed directories exist for next retry
# `copy_screenshots` in `cleanup_after_failure` can delete some needed directories
# https://github.com/fastlane/fastlane/issues/10786
prepare_directories_for_launch(language: language, locale: locale, launch_arguments: launch_args)
# Clear errors so a successful retry isn't reported as an over failure
self.collected_errors = []
execute(retries + 1, command: command, language: language, locale: locale, launch_args: launch_args, devices: devices)
end
def copy_screenshots(language: nil, locale: nil, launch_args: nil)
raw_output = File.read(xcodebuild_log_path(language: language, locale: locale))
dir_name = locale || language
return Collector.fetch_screenshots(raw_output, dir_name, '', launch_args.first)
end
def test_results_path
derived_data_path = TestCommandGenerator.derived_data_path
return File.join(derived_data_path, 'Logs/Test')
end
# This method returns a hash of { device name => [failure messages] }
# {
# 'iPhone 7': [], # this empty array indicates success
# 'iPhone 7 Plus': ["No tests were executed"],
# 'iPad Air': ["Launch session expired", "Array out of bounds"]
# }
def failed_devices
test_summaries = Dir["#{test_results_path}/*_TestSummaries.plist"]
test_summaries.each_with_object({}) do |plist, hash|
summary = FastlaneCore::TestParser.new(plist)
name = summary.data.first[:run_destination_name]
if summary.data.first[:number_of_tests] == 0
hash[name] = ["No tests were executed"]
else
tests = Array(summary.data.first[:tests])
hash[name] = tests.flat_map { |test| Array(test[:failures]).map { |failure| failure[:failure_message] } }
end
end
end
def xcodebuild_log_path(language: nil, locale: nil)
name_components = [Snapshot.project.app_name, Snapshot.config[:scheme]]
if Snapshot.config[:namespace_log_files]
name_components << launcher_config.devices.join('-') if launcher_config.devices.count >= 1
name_components << language if language
name_components << locale if locale
end
file_name = "#{name_components.join('-')}.log"
containing = File.expand_path(Snapshot.config[:buildlog_path])
FileUtils.mkdir_p(containing)
return File.join(containing, file_name)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/simulator_launchers/simulator_launcher_base.rb | snapshot/lib/snapshot/simulator_launchers/simulator_launcher_base.rb | require 'plist'
require 'time'
require_relative '../module'
require_relative '../test_command_generator'
require_relative '../collector'
require_relative '../fixes/hardware_keyboard_fix'
require_relative '../fixes/simulator_zoom_fix'
require_relative '../fixes/simulator_shared_pasteboard'
module Snapshot
class SimulatorLauncherBase
attr_accessor :collected_errors
# The number of times we failed on launching the simulator... sigh
attr_accessor :current_number_of_retries_due_to_failing_simulator
attr_accessor :launcher_config
def initialize(launcher_configuration: nil)
@launcher_config = launcher_configuration
@device_boot_datetime = DateTime.now
end
def collected_errors
@collected_errors ||= []
end
def current_number_of_retries_due_to_failing_simulator
@current_number_of_retries_due_to_failing_simulator || 0
end
def prepare_for_launch(device_types, language, locale, launch_arguments)
prepare_directories_for_launch(language: language, locale: locale, launch_arguments: launch_arguments)
prepare_simulators_for_launch(device_types, language: language, locale: locale)
end
def prepare_directories_for_launch(language: nil, locale: nil, launch_arguments: nil)
screenshots_path = TestCommandGenerator.derived_data_path
FileUtils.rm_rf(File.join(screenshots_path, "Logs"))
FileUtils.rm_rf(screenshots_path) if launcher_config.clean
FileUtils.mkdir_p(screenshots_path)
FileUtils.mkdir_p(CACHE_DIR)
FileUtils.mkdir_p(SCREENSHOTS_DIR)
File.write(File.join(CACHE_DIR, "language.txt"), language)
File.write(File.join(CACHE_DIR, "locale.txt"), locale || "")
File.write(File.join(CACHE_DIR, "snapshot-launch_arguments.txt"), launch_arguments.last)
end
def prepare_simulators_for_launch(device_types, language: nil, locale: nil)
# Kill and shutdown all currently running simulators so that the following settings
# changes will be picked up when they are started again.
Snapshot.kill_simulator # because of https://github.com/fastlane/fastlane/issues/2533
`xcrun simctl shutdown booted &> /dev/null`
Fixes::SimulatorZoomFix.patch
Fixes::HardwareKeyboardFix.patch
Fixes::SharedPasteboardFix.patch
device_types.each do |type|
if launcher_config.erase_simulator || launcher_config.localize_simulator || !launcher_config.dark_mode.nil?
if launcher_config.erase_simulator
erase_simulator(type)
end
if launcher_config.localize_simulator
localize_simulator(type, language, locale)
end
unless launcher_config.dark_mode.nil?
interface_style(type, launcher_config.dark_mode)
end
end
if launcher_config.reinstall_app && !launcher_config.erase_simulator
# no need to reinstall if device has been erased
uninstall_app(type)
end
if launcher_config.disable_slide_to_type
disable_slide_to_type(type)
end
end
unless launcher_config.headless
simulator_path = File.join(Helper.xcode_path, 'Applications', 'Simulator.app')
Helper.backticks("open -a #{simulator_path} -g", print: FastlaneCore::Globals.verbose?)
end
end
# pass an array of device types
def add_media(device_types, media_type, paths)
media_type = media_type.to_s
device_types.each do |device_type|
UI.verbose("Adding #{media_type}s to #{device_type}...")
device_udid = TestCommandGenerator.device_udid(device_type)
UI.message("Launch Simulator #{device_type}")
if FastlaneCore::Helper.xcode_at_least?("13")
Helper.backticks("open -a Simulator.app --args -CurrentDeviceUDID #{device_udid} &> /dev/null")
else
Helper.backticks("xcrun instruments -w #{device_udid} &> /dev/null")
end
paths.each do |path|
UI.message("Adding '#{path}'")
# Attempting addmedia since addphoto and addvideo are deprecated
output = Helper.backticks("xcrun simctl addmedia #{device_udid} #{path.shellescape} &> /dev/null")
# Run legacy addphoto and addvideo if addmedia isn't found
# Output will be empty string if it was a success
# Output will contain "usage: simctl" if command not found
if output.include?('usage: simctl')
Helper.backticks("xcrun simctl add#{media_type} #{device_udid} #{path.shellescape} &> /dev/null")
end
end
end
end
def override_status_bar(device_type, arguments = nil)
device_udid = TestCommandGenerator.device_udid(device_type)
UI.message("Launch Simulator #{device_type}")
# Boot the simulator and wait for it to finish booting
Helper.backticks("xcrun simctl bootstatus #{device_udid} -b &> /dev/null")
# "Booted" status is not enough for to adjust the status bar
# Simulator could still be booting with Apple logo
# Need to wait "some amount of time" until home screen shows
boot_sleep = ENV["SNAPSHOT_SIMULATOR_WAIT_FOR_BOOT_TIMEOUT"].to_i || 10
UI.message("Waiting #{boot_sleep} seconds for device to fully boot before overriding status bar... Set 'SNAPSHOT_SIMULATOR_WAIT_FOR_BOOT_TIMEOUT' environment variable to adjust timeout")
sleep(boot_sleep) if boot_sleep > 0
UI.message("Overriding Status Bar")
if arguments.nil? || arguments.empty?
# The time needs to be passed as ISO8601 so the simulator formats it correctly
time = Time.new(2007, 1, 9, 9, 41, 0)
# If you don't override the operator name, you'll get "Carrier" in the status bar on no-notch devices such as iPhone 8. Pass an empty string to blank it out.
arguments = "--time #{time.iso8601} --dataNetwork wifi --wifiMode active --wifiBars 3 --cellularMode active --operatorName '' --cellularBars 4 --batteryState charged --batteryLevel 100"
end
Helper.backticks("xcrun simctl status_bar #{device_udid} override #{arguments} &> /dev/null")
end
def clear_status_bar(device_type)
device_udid = TestCommandGenerator.device_udid(device_type)
UI.message("Clearing Status Bar Override")
Helper.backticks("xcrun simctl status_bar #{device_udid} clear &> /dev/null")
end
def uninstall_app(device_type)
launcher_config.app_identifier ||= UI.input("App Identifier: ")
device_udid = TestCommandGenerator.device_udid(device_type)
FastlaneCore::Simulator.uninstall_app(launcher_config.app_identifier, device_type, device_udid)
end
def erase_simulator(device_type)
UI.verbose("Erasing #{device_type}...")
device_udid = TestCommandGenerator.device_udid(device_type)
UI.important("Erasing #{device_type}...")
`xcrun simctl erase #{device_udid} &> /dev/null`
end
def localize_simulator(device_type, language, locale)
device_udid = TestCommandGenerator.device_udid(device_type)
if device_udid
locale ||= language.sub("-", "_")
plist = {
AppleLocale: locale,
AppleLanguages: [language]
}
UI.message("Localizing #{device_type} (AppleLocale=#{locale} AppleLanguages=[#{language}])")
plist_path = "#{ENV['HOME']}/Library/Developer/CoreSimulator/Devices/#{device_udid}/data/Library/Preferences/.GlobalPreferences.plist"
File.write(plist_path, Plist::Emit.dump(plist))
end
end
def interface_style(device_type, dark_mode)
device_udid = TestCommandGenerator.device_udid(device_type)
if device_udid
plist = {
UserInterfaceStyleMode: (dark_mode ? 2 : 1)
}
UI.message("Setting interface style #{device_type} (UserInterfaceStyleMode=#{dark_mode})")
plist_path = "#{ENV['HOME']}/Library/Developer/CoreSimulator/Devices/#{device_udid}/data/Library/Preferences/com.apple.uikitservices.userInterfaceStyleMode.plist"
File.write(plist_path, Plist::Emit.dump(plist))
end
end
def disable_slide_to_type(device_type)
device_udid = TestCommandGenerator.device_udid(device_type)
if device_udid
UI.message("Disabling slide to type on #{device_type}")
FastlaneCore::Simulator.disable_slide_to_type(udid: device_udid)
end
end
def copy_simulator_logs(device_names, language, locale, launch_arguments)
return unless launcher_config.output_simulator_logs
detected_language = locale || language
language_folder = File.join(launcher_config.output_directory, detected_language)
device_names.each do |device_name|
device = TestCommandGeneratorBase.find_device(device_name)
components = [launch_arguments].delete_if { |a| a.to_s.length == 0 }
UI.header("Collecting system logs #{device_name} - #{language}")
log_identity = Digest::MD5.hexdigest(components.join("-"))
FastlaneCore::Simulator.copy_logs(device, log_identity, language_folder, @device_boot_datetime)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/fixes/simulator_zoom_fix.rb | snapshot/lib/snapshot/fixes/simulator_zoom_fix.rb | require_relative '../module'
module Snapshot
module Fixes
# This fix is needed due to a bug in UI Tests that creates invalid screenshots when the
# simulator is not scaled to a 100%
# Issue: https://github.com/fastlane/fastlane/issues/2578
# Radar: https://openradar.appspot.com/radar?id=6127019184095232
class SimulatorZoomFix
def self.patch
UI.message("Patching simulators '#{config_path}' to scale to 100%")
FastlaneCore::DeviceManager.simulators.each do |simulator|
simulator_name = simulator.name.tr("\s", "-")
key = "SimulatorWindowLastScale-com.apple.CoreSimulator.SimDeviceType.#{simulator_name}"
Helper.backticks("defaults write '#{config_path}' '#{key}' '1.0'", print: FastlaneCore::Globals.verbose?)
end
end
def self.config_path
File.join(File.expand_path("~"), "Library", "Preferences", "com.apple.iphonesimulator.plist")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/fixes/hardware_keyboard_fix.rb | snapshot/lib/snapshot/fixes/hardware_keyboard_fix.rb | require_relative '../module'
module Snapshot
module Fixes
# Having "Connect Hardware Keyboard" enabled causes issues with entering text in secure textfields
# Fixes https://github.com/fastlane/fastlane/issues/2494
class HardwareKeyboardFix
def self.patch
UI.verbose("Patching simulator to work with secure text fields")
Helper.backticks("defaults write com.apple.iphonesimulator ConnectHardwareKeyboard 0", print: FastlaneCore::Globals.verbose?)
# For > Xcode 9
# https://stackoverflow.com/questions/38010494/is-it-possible-to-toggle-software-keyboard-via-the-code-in-ui-test/47820883#47820883
Helper.backticks("/usr/libexec/PlistBuddy "\
"-c \"Print :DevicePreferences\" ~/Library/Preferences/com.apple.iphonesimulator.plist | "\
"perl -lne 'print $1 if /^ (\\S*) =/' | while read -r a; do /usr/libexec/PlistBuddy "\
"-c \"Set :DevicePreferences:$a:ConnectHardwareKeyboard false\" "\
"~/Library/Preferences/com.apple.iphonesimulator.plist "\
"|| /usr/libexec/PlistBuddy "\
"-c \"Add :DevicePreferences:$a:ConnectHardwareKeyboard bool false\" "\
"~/Library/Preferences/com.apple.iphonesimulator.plist; done", print: FastlaneCore::Globals.verbose?)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/snapshot/lib/snapshot/fixes/simulator_shared_pasteboard.rb | snapshot/lib/snapshot/fixes/simulator_shared_pasteboard.rb | require_relative '../module'
module Snapshot
module Fixes
# Becoming first responder can trigger Pasteboard sync, which can stall and crash the simulator
# See https://twitter.com/steipete/status/1227551552317140992
class SharedPasteboardFix
def self.patch
UI.verbose("Patching simulator to disable Pasteboard automatic sync")
Helper.backticks("defaults write com.apple.iphonesimulator PasteboardAutomaticSync -bool false", print: FastlaneCore::Globals.verbose?)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/actions/plugin_scores.rb | fastlane/actions/plugin_scores.rb | module Fastlane
module Actions
class PluginScoresAction < Action
def self.run(params)
require_relative '../helper/plugin_scores_helper.rb'
require "erb"
plugins = fetch_plugins(params[:cache_path]).sort_by { |v| v.data[:overall_score] }.reverse
result = "<!--\nAuto generated, please only modify https://github.com/fastlane/fastlane/blob/master/fastlane/actions/plugin_scores.rb\n-->\n"
result += "{!docs/includes/setup-fastlane-header.md!}\n"
result += "# Available Plugins\n\n\n"
result += plugins.collect do |current_plugin|
@plugin = current_plugin
result = ERB.new(File.read(params[:template_path]), trim_mode: '-').result(binding) # https://web.archive.org/web/20160430190141/www.rrn.dk/rubys-erb-templating-system
end.join("\n")
File.write(File.join("docs", params[:output_path]), result)
end
def self.fetch_plugins(cache_path)
require 'open-uri'
page = 1
plugins = []
loop do
url = "https://rubygems.org/api/v1/search.json?query=fastlane-plugin-&page=#{page}"
puts("RubyGems API Request: #{url}")
results = JSON.parse(URI.open(url).read)
break if results.count == 0
plugins += results.collect do |current|
next if self.hidden_plugins.include?(current['name'])
Fastlane::Helper::PluginScoresHelper::FastlanePluginScore.new(current, cache_path)
end.compact
page += 1
end
return plugins
end
# Metadata
def self.available_options
[
FastlaneCore::ConfigItem.new(key: :output_path),
FastlaneCore::ConfigItem.new(key: :template_path),
FastlaneCore::ConfigItem.new(key: :cache_path)
]
end
def self.authors
["KrauseFx"]
end
def self.is_supported?(platform)
true
end
def self.category
:misc
end
# Those are plugins that are now part of fastlane core actions, so we don't want to show them in the directory
def self.hidden_plugins
[
"fastlane-plugin-update_project_codesigning"
]
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/actions/test_sample_code.rb | fastlane/actions/test_sample_code.rb | module Fastlane
module Actions
class TestSampleCodeAction < Action
def self.run(params)
content = params[:content] || File.read(params[:path])
fill_in_env_variables
errors = []
content.scan(/```ruby\n(((.|\n)(?!```))*)\n```/).each do |current_match|
current_match = current_match.first # we only expect one match
next if current_match.include?("sh(") # we don't want to run any shell scripts
UI.verbose("parsing: #{current_match}")
begin
begin
# rubocop:disable Security/Eval
eval(current_match)
# rubocop:enable Security/Eval
rescue SyntaxError => ex
UI.user_error!("Syntax error in code sample:\n#{current_match}\n#{ex}")
rescue => ex
UI.user_error!("Error found in code sample:\n#{current_match}\n#{ex}")
end
rescue => ex
errors << ex
end
end
UI.error("Found errors in the documentation, more information below") unless errors.empty?
errors.each do |ex|
UI.error(ex)
end
ENV.delete("CI")
UI.user_error!("Found #{errors.count} errors in the documentation") unless errors.empty?
end
# Is used to look if the method is implemented as an action
def self.method_missing(method_sym, *arguments, &_block)
return if denylist.include?(method_sym)
class_ref = self.runner.class_reference_from_action_name(method_sym)
unless class_ref
alias_found = self.runner.find_alias(method_sym.to_s)
if alias_found
class_ref = self.runner.class_reference_from_action_name(alias_found.to_sym)
end
end
UI.user_error!("Could not find method or action named '#{method_sym}'") if class_ref.nil?
available_options = class_ref.available_options
if available_options.kind_of?(Array) && available_options.first && available_options.first.kind_of?(FastlaneCore::ConfigItem)
parameters = arguments.shift || []
parameters.each do |current_argument, value|
UI.verbose("Verifying '#{value}' for option '#{current_argument}' for action '#{method_sym}'")
config_item = available_options.find { |a| a.key == current_argument }
UI.user_error!("Unknown parameter '#{current_argument}' for action '#{method_sym}'") if config_item.nil?
if value.nil? && config_item.optional
next
end
if config_item.data_type == Fastlane::Boolean
config_item.ensure_boolean_type_passes_validation(value)
elsif config_item.data_type == Array
config_item.ensure_array_type_passes_validation(value)
else
config_item.ensure_generic_type_passes_validation(value)
end
end
else
UI.verbose("Legacy parameter technique for action '#{method_sym}'")
end
return class_ref.sample_return_value # optional value that can be set by the action to make code samples work
end
# If the action name is x, don't run the verification
# This will still verify the syntax though
# The actions listed here are still legacy actions, so
# they don't use the fastlane configuration system
def self.denylist
[
:import,
:xcode_select,
:frameit,
:refresh_dsyms,
:lane,
:before_all,
:verify_xcode,
:error
]
end
# Metadata
def self.available_options
[
FastlaneCore::ConfigItem.new(key: :path),
FastlaneCore::ConfigItem.new(key: :content)
]
end
def self.authors
["KrauseFx"]
end
def self.is_supported?(platform)
true
end
def self.fill_in_env_variables
ENV["CI"] = 1.to_s
ENV["GITHUB_TOKEN"] = "123"
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/unused_options_spec.rb | fastlane/spec/unused_options_spec.rb | describe Fastlane do
describe Fastlane::Action do
describe "No unused options" do
let(:all_exceptions) do
%w(
pilot
appstore
cert
deliver
gym
match
pem
produce
scan
sigh
snapshot
precheck
supply
testflight
mailgun
testfairy
ipa
import_from_git
hockey
deploygate
crashlytics
artifactory
appledoc
slather
screengrab
download_dsyms
notification
frameit
set_changelog
register_device
register_devices
latest_testflight_build_number
app_store_build_number
sh
swiftlint
plugin_scores
google_play_track_version_codes
google_play_track_release_names
modify_services
build_app
build_android_app
build_ios_app
build_mac_app
capture_screenshots
capture_android_screenshots
capture_ios_screenshots
check_app_store_metadata
get_certificates
create_app_online
frame_screenshots
get_provisioning_profile
get_push_certificate
run_tests
submit_build_to_app_store
sync_code_signing
upload_to_app_store
upload_to_play_store
upload_to_play_store_internal_app_sharing
upload_to_testflight
download_universal_apk_from_google_play
puts
println
echo
xcov
create_app_on_managed_play_store
download_from_play_store
validate_play_store_json_key
update_fastlane
s3
match_nuke
trainer
)
end
Fastlane::ActionsList.all_actions do |action, name|
next unless action.available_options.kind_of?(Array)
next unless action.available_options.last.kind_of?(FastlaneCore::ConfigItem)
it "No unused parameters in '#{name}'" do
next if all_exceptions.include?(name)
content = File.read(File.join("fastlane", "lib", "fastlane", "actions", name + ".rb"))
action.available_options.each do |option|
unless content.include?("[:#{option.key}]")
UI.user_error!("Action '#{name}' doesn't use the option :#{option.key}")
end
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/fastlane/spec/docs_generator_spec.rb | fastlane/spec/docs_generator_spec.rb | require 'fastlane/documentation/docs_generator'
describe Fastlane do
describe Fastlane::DocsGenerator do
it "generates new markdown docs" do
output_path = "/tmp/documentation.md"
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileGrouped')
Fastlane::DocsGenerator.run(ff, output_path)
output = File.read(output_path)
expect(output).to include('installation instructions')
expect(output).to include('# Available Actions')
expect(output).to include('### test')
expect(output).to include('# iOS')
expect(output).to include('fastlane test')
expect(output).to include('## mac')
expect(output).to include('----')
expect(output).to include('Upload something to Google')
expect(output).to include('fastlane mac beta')
expect(output).to include('https://fastlane.tools')
end
it "generates new markdown docs but skips empty platforms" do
output_path = "/tmp/documentation.md"
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfilePlatformDocumentation')
Fastlane::DocsGenerator.run(ff, output_path)
output = File.read(output_path)
expect(output).to include('installation instructions')
expect(output).to include('# Available Actions')
expect(output).to include('## Android')
expect(output).to include('### android lane')
expect(output).to include('fastlane android lane')
expect(output).to include("I'm a lane")
expect(output).not_to(include('## iOS'))
expect(output).not_to(include('## Mac'))
expect(output).not_to(include('mac_lane'))
expect(output).not_to(include("I'm a mac private_lane"))
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/actions_list_spec.rb | fastlane/spec/actions_list_spec.rb | require 'fastlane/documentation/actions_list'
describe Fastlane do
describe "Action List" do
it "doesn't throw an exception" do
Fastlane::ActionsList.run(filter: nil)
end
it "doesn't throw an exception with filter" do
Fastlane::ActionsList.run(filter: 'deliver')
end
it "shows all available actions if action can't be found" do
Fastlane::ActionsList.run(filter: 'nonExistingHere')
end
it "returns all available actions with the type `Class`" do
actions = []
Fastlane::ActionsList.all_actions do |a|
actions << a
expect(a.class).to eq(Class)
end
expect(actions.count).to be > 80
end
it "allows filtering of the platforms" do
count = 0
Fastlane::ActionsList.all_actions("nothing special") { count += 1 }
expect(count).to be > 40
expect(count).to be < 120
end
describe "Provide action details" do
Fastlane::ActionsList.all_actions do |action, name|
it "Shows the details for action '#{name}'" do
Fastlane::ActionsList.show_details(filter: name)
end
end
end
describe "with a class in the Actions namespace that does not extend action" do
it "trying to show its details presents a helpful error message" do
require_relative 'fixtures/broken_actions/broken_action.rb'
expect(UI).to receive(:user_error!).with(/be a subclass/).and_raise("boom")
expect do
Fastlane::ActionsList.show_details(filter: 'broken')
end.to raise_error("boom")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/action_spec.rb | fastlane/spec/action_spec.rb | describe Fastlane do
describe Fastlane::Action do
describe "#action_name" do
it "converts the :: format to a readable one" do
expect(Fastlane::Actions::IpaAction.action_name).to eq('ipa')
expect(Fastlane::Actions::IncrementBuildNumberAction.action_name).to eq('increment_build_number')
end
it "only removes the last occurrence of Action" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
expect(Fastlane::Actions::ActionFromActionAction.action_name).to eq('action_from_action')
end
end
describe "Easy access to the lane context" do
it "redirects to the correct class and method" do
Fastlane::Actions.lane_context[:something] = 1
expect(Fastlane::Action.lane_context).to eq({ something: 1 })
end
end
describe "#step_text" do
it "allows custom step_text with no parameters in method signature" do
expect(Fastlane::UI).to receive(:header).with("Step: Custom Step Text")
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
result = Fastlane::FastFile.new.parse("lane :test do
step_text_custom_no_params
end").runner.execute(:test)
end
it "allows nil step_text with no parameters in method signature" do
expect(Fastlane::UI).to_not(receive(:header))
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
result = Fastlane::FastFile.new.parse("lane :test do
step_text_none_no_params
end").runner.execute(:test)
end
it "allows custom step_text with parameters in method signature" do
task = "Some Task Param"
expect(Fastlane::UI).to receive(:header).with("Step: Doing #{task}")
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
result = Fastlane::FastFile.new.parse("lane :test do
step_text_custom_with_params(task: '#{task}')
end").runner.execute(:test)
end
end
describe "can call alias action" do
it "redirects to the correct class and method" do
result = Fastlane::FastFile.new.parse("lane :test do
println(message:\"alias\")
end").runner.execute(:test)
end
it "alias does not crash with no param" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
expect(UI).to receive(:important).with("modified")
result = Fastlane::FastFile.new.parse("lane :test do
somealias
end").runner.execute(:test)
end
it "alias can override option" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
expect(UI).to receive(:important).with("modified")
result = Fastlane::FastFile.new.parse("lane :test do
somealias(example: \"alias\", example_two: 'alias2')
end").runner.execute(:test)
end
it "alias can override option with single param" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
expect(UI).to receive(:important).with("modified")
result = Fastlane::FastFile.new.parse("lane :test do
someshortalias('PARAM')
end").runner.execute(:test)
end
it "alias can override option with no param" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
expect(UI).to receive(:important).with("modified")
result = Fastlane::FastFile.new.parse("lane :test do
somealias_no_param('PARAM')
end").runner.execute(:test)
end
it "alias does not crash - when 'alias_used' not defined" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
expect(UI).to receive(:important).with("run")
result = Fastlane::FastFile.new.parse("lane :test do
alias_no_used_handler_sample_alias('PARAM')
end").runner.execute(:test)
end
end
describe "Call another action from an action" do
it "allows the user to call it using `other_action.rocket`" do
allow(FastlaneCore::FastlaneFolder).to receive(:path).and_return(nil)
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileActionFromAction')
Fastlane::Actions.executed_actions.clear
response = {
rocket: "🚀",
pwd: Dir.pwd
}
expect(ff.runner.execute(:something, :ios)).to eq(response)
expect(Fastlane::Actions.executed_actions.map { |a| a[:name] }).to eq(['action_from_action'])
end
it "shows only actions called from Fastfile" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileActionFromActionWithOtherAction')
Fastlane::Actions.executed_actions.clear
ff.runner.execute(:something, :ios)
expect(Fastlane::Actions.executed_actions.map { |a| a[:name] }).to eq(['action_from_action', 'example_action'])
end
it "shows an appropriate error message when trying to directly call an action" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileActionFromActionInvalid')
expect do
ff.runner.execute(:something, :ios)
end.to raise_error("To call another action from an action use `other_action.rocket` instead")
end
end
describe "Action.sh" do
it "delegates to Actions.sh_control_output" do
mock_status = double(:status, exitstatus: 0)
expect(Fastlane::Actions).to receive(:sh_control_output).with("ls", "-la").and_yield(mock_status, "Command output")
Fastlane::Action.sh("ls", "-la") do |status, result|
expect(status.exitstatus).to eq(0)
expect(result).to eq("Command 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/fastlane/spec/action_metadata_spec.rb | fastlane/spec/action_metadata_spec.rb | require 'fastlane/documentation/actions_list'
describe Fastlane::Action do
Fastlane::ActionsList.all_actions do |action, name|
describe name do
it "`fastlane_class` and `action` are matching" do
# `to_s.gsub(/::.*/, '')` to convert
# "Fastlane::Actions::AdbDevicesAction"
# to
# "AdbDevicesAction"
#
expect(name.fastlane_class + "Action").to eq(action.to_s.gsub(/^.*::/, ''))
end
it "file name follows our convention and matches the class name" do
exceptions = %w(plugin_scores xcarchive xcbuild xcclean xcexport xctest)
action_path = File.join(Dir.pwd, "fastlane/lib/fastlane/actions/#{name}.rb")
unless exceptions.include?(name)
expect(File.exist?(action_path)).to eq(true)
end
end
it "contains a valid category" do
expect(action.category).to_not(be_nil)
expect(action.category).to be_kind_of(Symbol)
expect(Fastlane::Action::AVAILABLE_CATEGORIES).to include(action.category), "Unknown action category '#{action.category}', must be one of #{Fastlane::Action::AVAILABLE_CATEGORIES.join(', ')}"
end
it "is a subclass of Action" do
expect(action.ancestors.include?(Fastlane::Action)).to be_truthy, "Please add `Action` as a superclass for action '#{name}'"
end
it "description" do
expect(action.description.length).to be <= 80, "Provided description for '#{name}'-action is too long"
expect(action.description.length).to be > 5, "Provided description for '#{name}'-action is too short"
expect(action.description.strip.end_with?('.')).to eq(false), "The description of '#{name}' shouldn't end with a `.`"
end
it "implements is_supported?" do
action.is_supported?(nil) # this will raise an exception if the method is not implemented
end
it "defines valid authors" do
authors = Array(action.author || action.authors)
expect(authors.count).to be >= 1, "Action '#{name}' must have at least one author"
authors.each do |author|
expect(author).to_not(start_with("@"))
end
end
it "available_options" do
if action.available_options
expect(action.available_options).to be_instance_of(Array), "'available_options' for action '#{name}' must be an array"
end
end
it "output" do
if action.output
expect(action.output).to be_instance_of(Array), "'output' for action '#{name}' must be an array"
end
end
it "details" do
if action.details
expect(action.details).to be_instance_of(String), "'details' for action '#{name}' must be a String"
end
end
it "deprecated_notes" do
if action.deprecated_notes
expect(action.deprecated_notes).to be_instance_of(String), "'deprecated_notes' for action '#{name}' must be a String"
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/actions_helper_spec.rb | fastlane/spec/actions_helper_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "#execute_action" do
let(:step_name) { "My Step" }
it "stores the action properly" do
Fastlane::Actions.execute_action(step_name) {}
result = Fastlane::Actions.executed_actions.last
expect(result[:name]).to eq(step_name)
expect(result[:error]).to eq(nil)
end
it "stores the action properly when an exception occurred" do
expect do
Fastlane::Actions.execute_action(step_name) do
UI.user_error!("Some error")
end
end.to raise_error("Some error")
result = Fastlane::Actions.executed_actions.last
expect(result[:name]).to eq(step_name)
expect(result[:error]).to include("Some error")
expect(result[:error]).to include("actions_helper.rb")
end
end
it "#action_class_ref" do
expect(Fastlane::Actions.action_class_ref("gym")).to eq(Fastlane::Actions::GymAction)
expect(Fastlane::Actions.action_class_ref(:cocoapods)).to eq(Fastlane::Actions::CocoapodsAction)
expect(Fastlane::Actions.action_class_ref('notExistentObv')).to eq(nil)
end
it "#load_default_actions" do
expect(Fastlane::Actions.load_default_actions.count).to be > 6
end
describe "#load_external_actions" do
it "can load custom paths" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
Fastlane::Actions::ExampleActionAction.run(nil)
Fastlane::Actions::ExampleActionSecondAction.run(nil)
Fastlane::Actions::ArchiveAction.run(nil)
end
it "throws an error if plugin is damaged" do
expect(UI).to receive(:user_error!).with("Action 'broken_action' is damaged!", { show_github_issues: true })
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/broken_actions")
end
it "throws errors when syntax is incorrect" do
content = File.read('./fastlane/spec/fixtures/broken_files/broken_file.rb', encoding: 'utf-8')
expect(UI).to receive(:content_error).with(content, '7') # syntax error, unexpected ':', expecting '}'
# in ruby < 3.2, the SyntaxError string representation contains a second error
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('3.2')
expect(UI).to receive(:content_error).with(content, '8') # syntax error, unexpected ':', expecting `end'
end
expect(UI).to receive(:user_error!).with("Syntax error in broken_file.rb")
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/broken_files")
end
end
describe "#deprecated_actions" do
it "is class action" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
require_relative './fixtures/broken_actions/broken_action.rb'
# An action
example_action_ref = Fastlane::Actions.action_class_ref("example_action")
expect(Fastlane::Actions.is_class_action?(example_action_ref)).to eq(true)
# Not an action
broken_action_ref = Fastlane::Actions::BrokenAction
expect(Fastlane::Actions.is_class_action?(broken_action_ref)).to eq(false)
# Nil
expect(Fastlane::Actions.is_class_action?(nil)).to eq(false)
end
it "is action deprecated" do
Fastlane::Actions.load_external_actions("./fastlane/spec/fixtures/actions")
require_relative './fixtures/broken_actions/broken_action.rb'
require_relative './fixtures/deprecated_actions/deprecated_action.rb'
# An action (not deprecated)
example_action_ref = Fastlane::Actions.action_class_ref("example_action")
expect(Fastlane::Actions.is_deprecated?(example_action_ref)).to eq(false)
# An action (deprecated)
deprecated_action_ref = Fastlane::Actions.action_class_ref("deprecated_action")
expect(Fastlane::Actions.is_deprecated?(deprecated_action_ref)).to eq(true)
# Not an action
broken_action_ref = Fastlane::Actions::BrokenAction
expect(Fastlane::Actions.is_deprecated?(broken_action_ref)).to eq(false)
# Nil
expect(Fastlane::Actions.is_deprecated?(nil)).to eq(false)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/action_collector_spec.rb | fastlane/spec/action_collector_spec.rb | describe Fastlane::ActionCollector do
before(:all) { ENV.delete("FASTLANE_OPT_OUT_USAGE") }
let(:collector) { Fastlane::ActionCollector.new }
describe "#determine_version" do
it "accesses the version number of the other tools" do
expect(collector.determine_version(:gym)).to eq(Fastlane::VERSION)
expect(collector.determine_version(:sigh)).to eq(Fastlane::VERSION)
end
it "fetches the version of the plugin, if action is part of a plugin" do
module Fastlane::MyPlugin
VERSION = '1.2.3'
end
expect(collector.determine_version("fastlane-plugin-my_plugin/xcversion")).to eq('1.2.3')
end
it "returns 'undefined' if plugin version information is not available" do
expect(collector.determine_version("fastlane-plugin-nonexistent/action_name")).to eq('undefined')
end
it "falls back to the fastlane version number" do
expect(collector.determine_version(:fastlane)).to eq(Fastlane::VERSION)
expect(collector.determine_version(:xcode_install)).to eq(Fastlane::VERSION)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/lane_manager_spec.rb | fastlane/spec/lane_manager_spec.rb | describe Fastlane do
describe Fastlane::LaneManager do
describe "#init" do
it "raises an error on invalid platform" do
expect do
Fastlane::LaneManager.cruise_lane(123, nil)
end.to raise_error("platform must be a string")
end
it "raises an error on invalid lane" do
expect do
Fastlane::LaneManager.cruise_lane(nil, 123)
end.to raise_error("lane must be a string")
end
describe "successful init" do
before do
allow(FastlaneCore::FastlaneFolder).to receive(:path).and_return(File.absolute_path('./fastlane/spec/fixtures/fastfiles/'))
end
it "Successfully handles exceptions" do
expect do
ff = Fastlane::LaneManager.cruise_lane('ios', 'crashy')
end.to raise_error('my exception')
end
it "Uses the default platform if given" do
ff = Fastlane::LaneManager.cruise_lane(nil, 'empty') # look, without `ios`
lanes = ff.runner.lanes
expect(lanes[nil][:test].description).to eq([])
expect(lanes[:ios][:crashy].description).to eq(["This action does nothing", "but crash"])
expect(lanes[:ios][:empty].description).to eq([])
end
it "Supports running a lane without a platform even when there is a default_platform" do
path = "/tmp/fastlane/tests.txt"
File.delete(path) if File.exist?(path)
expect(File.exist?(path)).to eq(false)
ff = Fastlane::LaneManager.cruise_lane(nil, 'test')
expect(File.exist?(path)).to eq(true)
expect(ff.runner.current_lane).to eq(:test)
expect(ff.runner.current_platform).to eq(nil)
end
it "Supports running a lane with custom Fastfile path" do
path = "./fastlane/spec/fixtures/fastfiles/FastfileCruiseLane"
ff = Fastlane::LaneManager.cruise_lane(nil, 'test', nil, path)
lanes = ff.runner.lanes
expect(lanes[nil][:test].description).to eq(["test description for cruise lanes"])
expect(lanes[:ios][:apple].description).to eq([])
expect(lanes[:android][:robot].description).to eq([])
end
it "Does output a summary table when FASTLANE_SKIP_ACTION_SUMMARY ENV variable is not set" do
ENV["FASTLANE_SKIP_ACTION_SUMMARY"] = nil
expect(Terminal::Table).to(receive(:new).with(title: "fastlane summary".green, headings: anything, rows: anything))
ff = Fastlane::LaneManager.cruise_lane(nil, 'test')
end
it "Does not output summary table when FASTLANE_SKIP_ACTION_SUMMARY ENV variable is set" do
ENV["FASTLANE_SKIP_ACTION_SUMMARY"] = "true"
expect(Terminal::Table).to_not(receive(:new).with(title: "fastlane summary".green, headings: anything, rows: anything))
ff = Fastlane::LaneManager.cruise_lane(nil, 'test')
ENV["FASTLANE_SKIP_ACTION_SUMMARY"] = nil
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/supported_platforms.rb | fastlane/spec/supported_platforms.rb | describe Fastlane do
describe Fastlane::Action do
describe "#all" do
it "Contains 3 default supported platforms" do
expect(Fastlane::SupportedPlatforms.all.count).to eq(3)
end
end
describe "#extra=" do
after :each do
Fastlane::SupportedPlatforms.extra = []
end
it "allows to add new platforms the list of supported ones" do
expect(FastlaneCore::UI).to receive(:important).with("Setting '[:abcdef]' as extra SupportedPlatforms")
Fastlane::SupportedPlatforms.extra = [:abcdef]
expect(Fastlane::SupportedPlatforms.all).to include(:abcdef)
end
it "doesn't break if you pass nil" do
expect(FastlaneCore::UI).to receive(:important).with("Setting '[]' as extra SupportedPlatforms")
Fastlane::SupportedPlatforms.extra = nil
expect(Fastlane::SupportedPlatforms.all.count).to eq(3)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/lane_list_spec.rb | fastlane/spec/lane_list_spec.rb | require 'fastlane/lane_list'
describe Fastlane do
describe Fastlane::LaneList do
it "#generate" do
result = Fastlane::LaneList.generate('./fastlane/spec/fixtures/fastfiles/FastfileGrouped')
expect(result).to include("fastlane ios beta")
expect(result).to include("Build and upload a new build to Apple")
expect(result).to include("general")
end
it "#generate_json" do
result = Fastlane::LaneList.generate_json('./fastlane/spec/fixtures/fastfiles/FastfileGrouped')
expect(result).to eq({
nil => {
test: { description: "Run all the tests" },
anotherroot: { description: "" }
},
:mac => {
beta: { description: "Build and upload a new build to Apple TestFlight\nThis action will also do a build version bump and push it to git.\nThis will **not** send an email to all testers, it will only be uploaded to the new TestFlight." }
},
:ios => {
beta: { description: "Submit a new version to the App Store" },
release: { description: "" }
},
:android => {
beta: { description: "Upload something to Google" },
witherror: { description: "" },
unsupported_action: { description: "" }
}
})
end
it "generates empty JSON if there is no Fastfile" do
result = Fastlane::LaneList.generate_json(nil)
expect(result).to eq({})
end
describe "#lane_name_from_swift_line" do
let(:testLane) { "func testLane() {" }
let(:testLaneWithOptions) { "func testLane(withOptions: [String: String]?) {" }
let(:testNoLane) { "func test() {" }
let(:testNoLaneWithOptions) { "func test(withOptions: [String: String]?) {" }
it "finds lane name without options" do
name = Fastlane::LaneList.lane_name_from_swift_line(potential_lane_line: testLane)
expect(name).to eq("testLane")
end
it "finds lane name with options" do
name = Fastlane::LaneList.lane_name_from_swift_line(potential_lane_line: testLaneWithOptions)
expect(name).to eq("testLane")
end
it "doesn't find lane name without options" do
name = Fastlane::LaneList.lane_name_from_swift_line(potential_lane_line: testNoLane)
expect(name).to eq(nil)
end
it "doesn't find lane name with options" do
name = Fastlane::LaneList.lane_name_from_swift_line(potential_lane_line: testNoLaneWithOptions)
expect(name).to eq(nil)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/private_public_fastfile_spec.rb | fastlane/spec/private_public_fastfile_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "Public/Private lanes" do
let(:path) { './fastlane/spec/fixtures/fastfiles/FastfilePrivatePublic' }
before do
FileUtils.rm_rf('/tmp/fastlane/')
@ff = Fastlane::FastFile.new(path)
end
it "raise an exception when calling a private lane" do
expect do
@ff.runner.execute('private_helper')
end.to raise_error("You can't call the private lane 'private_helper' directly")
end
it "still supports calling public lanes" do
result = @ff.runner.execute('public')
expect(result).to eq("publicResult")
end
it "supports calling private lanes from public lanes" do
result = @ff.runner.execute('smooth')
expect(result).to eq("success")
end
it "doesn't expose the private lanes in `fastlane lanes`" do
require 'fastlane/lane_list'
result = Fastlane::LaneList.generate(path)
expect(result).to include("such smooth")
expect(result).to_not(include("private call"))
end
it "doesn't expose the private lanes in `fastlane docs`" do
output_path = "/tmp/documentation.md"
ff = Fastlane::FastFile.new(path)
Fastlane::DocsGenerator.run(ff, output_path)
output = File.read(output_path)
expect(output).to include('installation instructions')
expect(output).to include('such smooth')
expect(output).to_not(include('private'))
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/env_spec.rb | fastlane/spec/env_spec.rb | require "fastlane/environment_printer"
require "fastlane/cli_tools_distributor"
describe Fastlane do
describe Fastlane::EnvironmentPrinter do
before do
stub_request(:get, %r{https://rubygems\.org\/api\/v1\/gems\/.*}).
to_return(status: 200, body: '{"version": "0.16.2"}', headers: {})
end
let(:fastlane_files) { Fastlane::EnvironmentPrinter.print_fastlane_files }
it "contains the key words" do
expect(fastlane_files).to include("fastlane files")
expect(fastlane_files).to include("Fastfile")
expect(fastlane_files).to include("Appfile")
end
let(:env) { Fastlane::EnvironmentPrinter.get }
it "contains the key words" do
expect(env).to include("fastlane gems")
expect(env).to include("generated on")
end
it "prints out the loaded fastlane plugins" do
expect(env).to include("Loaded fastlane plugins")
end
it "prints out the loaded gem dependencies" do
expect(env).to include("Loaded gems")
expect(env).to include("addressable")
expect(env).to include("xcpretty")
end
it "contains main information about the stack", requires_xcode: true do
expect(env).to include("Bundler?")
expect(env).to include("Xcode Path")
expect(env).to include("Xcode Version")
expect(env).to include("OpenSSL")
end
it "anonymizes a path containing the user’s home" do
expect(Fastlane::EnvironmentPrinter.anonymized_path('/Users/john/.fastlane/bin/bundle/bin/fastlane', '/Users/john')).to eq('~/.fastlane/bin/bundle/bin/fastlane')
expect(Fastlane::EnvironmentPrinter.anonymized_path('/Users/john', '/Users/john')).to eq('~')
expect(Fastlane::EnvironmentPrinter.anonymized_path('/Users/john/', '/Users/john')).to eq('~/')
expect(Fastlane::EnvironmentPrinter.anonymized_path('/workspace/project/test', '/work')).to eq('/workspace/project/test')
end
context 'FastlaneCore::Helper.xcode_version cannot be obtained' do
before do
allow(FastlaneCore::Helper).to receive(:xcode_version).and_raise("Boom!")
end
it 'contains stack information other than Xcode Version', requires_xcode: true do
expect(env).to include("Bundler?")
expect(env).to include("Xcode Path")
expect(env).not_to(include("Xcode Version"))
expect(env).to include("OpenSSL")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/erb_template_helper_spec.rb | fastlane/spec/erb_template_helper_spec.rb | describe Fastlane do
describe Fastlane::ErbTemplateHelper do
describe "load_template" do
it "raises an error if file does not exist" do
expect do
Fastlane::ErbTemplateHelper.load('invalid_name')
end.to raise_exception("Could not find template at path '#{Fastlane::ROOT}/lib/assets/invalid_name.erb'")
end
it "should load file if exists" do
f = Fastlane::ErbTemplateHelper.load('s3_html_template')
expect(f).not_to(be_empty)
end
end
describe "render_template" do
it "renders hash values in HTML template" do
template = File.read("./fastlane/spec/fixtures/templates/dummy_html_template.erb")
rendered_template = Fastlane::ErbTemplateHelper.render(template, {
template_name: "name"
}).delete!("\n")
expect(rendered_template).to eq("<h1>name</h1>")
end
it "renders with defined trim_mode" do
template = File.read("./fastlane/spec/fixtures/templates/trim_mode_template.erb")
rendered_template = Fastlane::ErbTemplateHelper.render(template, {}, '-')
expect(rendered_template).to eq("line\n")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/tools_spec.rb | fastlane/spec/tools_spec.rb | describe Fastlane do
describe "Fastlane::TOOLS" do
it "lists all the fastlane tools" do
expect(Fastlane::TOOLS.count).to be >= 15
end
it "contains symbols for each of the tools" do
Fastlane::TOOLS.each do |current|
expect(current).to be_kind_of(Symbol)
end
end
it "warns the user when a lane is called like a tool" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/Fastfile1')
expect(UI).to receive(:error).with("------------------------------------------------")
expect(UI).to receive(:error).with("Lane name 'gym' should not be used because it is the name of a fastlane tool")
expect(UI).to receive(:error).with("It is recommended to not use 'gym' as the name of your lane")
expect(UI).to receive(:error).with("------------------------------------------------")
ff.lane(:gym) do
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/lane_manager_base_spec.rb | fastlane/spec/lane_manager_base_spec.rb | describe Fastlane do
describe Fastlane::LaneManagerBase do
describe "#print_lane_context" do
it "prints lane context" do
Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::LANE_NAME] = "test"
cleaned_row_data = [[:LANE_NAME, "test"]]
table_data = FastlaneCore::PrintTable.transform_output(cleaned_row_data)
expect(FastlaneCore::PrintTable).to receive(:transform_output).with(cleaned_row_data).and_call_original
expect(Terminal::Table).to receive(:new).with({
title: "Lane Context".yellow,
rows: table_data
})
Fastlane::LaneManagerBase.print_lane_context
end
it "prints lane context" do
Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::LANE_NAME] = "test"
expect(UI).to receive(:important).with('Lane Context:'.yellow)
expect(UI).to receive(:message).with(Fastlane::Actions.lane_context)
FastlaneSpec::Env.with_verbose(true) do
Fastlane::LaneManagerBase.print_lane_context
end
end
it "doesn't crash when lane_context contains non unicode text" do
Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::LANE_NAME] = "test\xAE"
Fastlane::LaneManagerBase.print_lane_context
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/cli_tools_distributor_spec.rb | fastlane/spec/cli_tools_distributor_spec.rb | require 'fastlane/cli_tools_distributor'
describe Fastlane::CLIToolsDistributor do
around do |example|
# FASTLANE_SKIP_UPDATE_CHECK: prevent the update checker to run and clutter the output
# (Fastlane::PluginUpdateManager.start_looking_for_updates() will return)
# FASTLANE_DISABLE_ANIMATION: prevent the spinner in Fastlane::CLIToolsDistributor.take_off
FastlaneSpec::Env.with_env_values('FASTLANE_SKIP_UPDATE_CHECK': 'a_truthy_value', 'FASTLANE_DISABLE_ANIMATION': 'true') do
example.run
end
end
describe "command handling" do
it "runs the lane instead of the tool when there is a conflict" do
FastlaneSpec::Env.with_ARGV(["sigh"]) do
require 'fastlane/commands_generator'
expect(FastlaneCore::FastlaneFolder).to receive(:fastfile_path).and_return("./fastlane/spec/fixtures/fastfiles/FastfileUseToolNameAsLane").at_least(:once)
expect(Fastlane::CommandsGenerator).to receive(:start).and_return(nil)
Fastlane::CLIToolsDistributor.take_off
end
end
it "runs a separate tool when the tool is available and the name is not used in a lane" do
FastlaneSpec::Env.with_ARGV(["gym"]) do
require 'gym/options'
require 'gym/commands_generator'
expect(FastlaneCore::FastlaneFolder).to receive(:fastfile_path).and_return("./fastlane/spec/fixtures/fastfiles/FastfileUseToolNameAsLane").at_least(:once)
expect(Gym::CommandsGenerator).to receive(:start).and_return(nil)
Fastlane::CLIToolsDistributor.take_off
end
end
it "runs a separate aliased tool when the tool is available and the name is not used in a lane" do
FastlaneSpec::Env.with_ARGV(["build_app"]) do
require 'gym/options'
require 'gym/commands_generator'
expect(FastlaneCore::FastlaneFolder).to receive(:fastfile_path).and_return("./fastlane/spec/fixtures/fastfiles/FastfileUseToolNameAsLane").at_least(:once)
expect(Gym::CommandsGenerator).to receive(:start).and_return(nil)
Fastlane::CLIToolsDistributor.take_off
end
end
end
describe "update checking" do
it "checks for updates when running a lane" do
FastlaneSpec::Env.with_ARGV(["sigh"]) do
require 'fastlane/commands_generator'
expect(FastlaneCore::FastlaneFolder).to receive(:fastfile_path).and_return("./fastlane/spec/fixtures/fastfiles/FastfileUseToolNameAsLane").at_least(:once)
expect(FastlaneCore::UpdateChecker).to receive(:start_looking_for_update).with('fastlane')
expect(Fastlane::CommandsGenerator).to receive(:start).and_return(nil)
expect(FastlaneCore::UpdateChecker).to receive(:show_update_status).with('fastlane', Fastlane::VERSION)
Fastlane::CLIToolsDistributor.take_off
end
end
it "checks for updates when running a tool" do
FastlaneSpec::Env.with_ARGV(["gym"]) do
require 'gym/options'
require 'gym/commands_generator'
expect(FastlaneCore::FastlaneFolder).to receive(:fastfile_path).and_return("./fastlane/spec/fixtures/fastfiles/FastfileUseToolNameAsLane").at_least(:once)
expect(FastlaneCore::UpdateChecker).to receive(:start_looking_for_update).with('fastlane')
expect(Gym::CommandsGenerator).to receive(:start).and_return(nil)
expect(FastlaneCore::UpdateChecker).to receive(:show_update_status).with('fastlane', Fastlane::VERSION)
Fastlane::CLIToolsDistributor.take_off
end
end
it "checks for updates even if the lane has an error" do
FastlaneSpec::Env.with_ARGV(["beta"]) do
expect(FastlaneCore::FastlaneFolder).to receive(:fastfile_path).and_return("./fastlane/spec/fixtures/fastfiles/FastfileErrorInError").at_least(:once)
expect(FastlaneCore::UpdateChecker).to receive(:start_looking_for_update).with('fastlane')
expect(FastlaneCore::UpdateChecker).to receive(:show_update_status).with('fastlane', Fastlane::VERSION)
expect_any_instance_of(Commander::Runner).to receive(:abort).with("\n[!] Original error".red).and_raise(SystemExit) # mute console output from `abort`
expect do
Fastlane::CLIToolsDistributor.take_off
end.to raise_error(SystemExit)
end
end
end
describe "dotenv loading" do
require 'fastlane/helper/dotenv_helper'
it "passes --env option into DotenvHelper" do
FastlaneSpec::Env.with_ARGV(["lanes", "--env", "one"]) do
expect(Fastlane::Helper::DotenvHelper).to receive(:load_dot_env).with('one')
Fastlane::CLIToolsDistributor.take_off
end
end
it "strips --env option" do
FastlaneSpec::Env.with_ARGV(["lanes", "--env", "one,two"]) do
expect(Fastlane::Helper::DotenvHelper).to receive(:load_dot_env).with('one,two')
Fastlane::CLIToolsDistributor.take_off
expect(ARGV).to eq(["lanes"])
end
end
it "ignores --env missing a value" do
FastlaneSpec::Env.with_ARGV(["lanes", "--env"]) do
expect(Fastlane::Helper::DotenvHelper).to receive(:load_dot_env).with(nil)
Fastlane::CLIToolsDistributor.take_off
end
end
end
describe "map_aliased_tools" do
before do
require 'fastlane'
end
it "returns nil when tool_name is nil" do
expect(Fastlane::CLIToolsDistributor.map_aliased_tools(nil)).to eq(nil)
end
Fastlane::TOOL_ALIASES.each do |key, value|
it "returns #{value} when tool_name is #{key}" do
expect(Fastlane::CLIToolsDistributor.map_aliased_tools(key)).to eq(value)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/gradle_helper_spec.rb | fastlane/spec/gradle_helper_spec.rb | describe Fastlane::Helper::GradleHelper do
describe 'parameter handling' do
it 'stores a shell-escaped version of the gradle_path when constructed' do
gradle_path = '/fake gradle/path'
helper = Fastlane::Helper::GradleHelper.new(gradle_path: gradle_path)
expect(helper.gradle_path).to eq(gradle_path)
expect(helper.escaped_gradle_path).to eq(gradle_path.shellescape)
end
it 'updates a shell-escaped version of the gradle_path when modified' do
gradle_path = '/fake gradle/path'
helper = Fastlane::Helper::GradleHelper.new(gradle_path: '/different/when/constructed')
helper.gradle_path = gradle_path
expect(helper.gradle_path).to eq(gradle_path)
expect(helper.escaped_gradle_path).to eq(gradle_path.shellescape)
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/swift_fastlane_function_spec.rb | fastlane/spec/swift_fastlane_function_spec.rb | describe Fastlane do
describe Fastlane::SwiftFunction do
describe 'swift_parameter_documentation' do
it 'generates nil for functions with 0 parameters' do
swift_function = Fastlane::SwiftFunction.new
output = swift_function.swift_parameter_documentation
expect(output).to be_nil
end
it 'generates parameter documentation for functions with 1 parameter' do
swift_function = Fastlane::SwiftFunction.new(keys: ['param_one'], key_descriptions: ['desc for param one'])
result = swift_function.swift_parameter_documentation
expect(result).to eq(' - parameter paramOne: desc for param one')
end
it 'generates parameter documentation for functions with many parameters' do
swift_function = Fastlane::SwiftFunction.new(keys: ['param_one', 'param_two'], key_descriptions: ['desc for param one', 'desc for param two'])
result = swift_function.swift_parameter_documentation
expected = " - parameters:\n"\
" - paramOne: desc for param one\n"\
' - paramTwo: desc for param two'
expect(result).to eq(expected)
end
end
describe 'swift_return_value_documentation' do
it 'generates nil for functions with no return value' do
swift_function = Fastlane::SwiftFunction.new
result = swift_function.swift_return_value_documentation
expect(result).to be_nil
end
it 'generates documentation for the return value' do
swift_function = Fastlane::SwiftFunction.new(return_value: 'description of return value')
result = swift_function.swift_return_value_documentation
expect(result).to eq(" - returns: description of return value")
end
it 'generates documentation for the return value with a sample return value' do
swift_function = Fastlane::SwiftFunction.new(return_value: 'description of return value', sample_return_value: '[]')
result = swift_function.swift_return_value_documentation
expect(result).to eq(" - returns: description of return value. Example: []")
end
end
describe 'swift_documentation' do
it 'generates empty string for functions with no parameters and no function details and no function description' do
swift_function = Fastlane::SwiftFunction.new
result = swift_function.swift_documentation
expect(result).to be_empty
end
it 'generates documentation for functions with a parameter but no function details and no function description' do
swift_function = Fastlane::SwiftFunction.new(keys: ['param_one'], key_descriptions: ['desc for param one'])
result = swift_function.swift_documentation
expected = "/**\n"\
" - parameter paramOne: desc for param one\n"\
"*/\n"
expect(result).to eq(expected)
end
it 'generates documentation for functions with function details but no parameters and no function description' do
swift_function = Fastlane::SwiftFunction.new(action_details: 'details')
result = swift_function.swift_documentation
expected = "/**\n"\
" details\n"\
"*/\n"
expect(result).to eq(expected)
end
it 'generates documentation for functions with a function description but no parameters and no function details' do
swift_function = Fastlane::SwiftFunction.new(action_description: 'description')
result = swift_function.swift_documentation
expected = "/**\n"\
" description\n"\
"*/\n"
expect(result).to eq(expected)
end
it 'generates documentation for functions with function details and a parameter but no function description' do
swift_function = Fastlane::SwiftFunction.new(action_details: 'details', keys: ['param_one'], key_descriptions: ['desc for param one'])
result = swift_function.swift_documentation
expected = "/**\n"\
" - parameter paramOne: desc for param one\n"\
"\n"\
" details\n"\
"*/\n"
expect(result).to eq(expected)
end
it 'generates documentation for functions with function details, a parameter, and a function description' do
swift_function = Fastlane::SwiftFunction.new(action_details: 'details', action_description: "description", keys: ['param_one'], key_descriptions: ['desc for param one'])
result = swift_function.swift_documentation
expected = "/**\n"\
" description\n"\
"\n"\
" - parameter paramOne: desc for param one\n"\
"\n"\
" details\n"\
"*/\n"
expect(result).to eq(expected)
end
it 'generates documentation for functions with a parameter and a return value' do
swift_function = Fastlane::SwiftFunction.new(keys: ['param_one'], key_descriptions: ['desc for param one'], return_value: 'return value')
result = swift_function.swift_documentation
expected = "/**\n"\
" - parameter paramOne: desc for param one\n"\
"\n"\
" - returns: return value\n"\
"*/\n"
expect(result).to eq(expected)
end
end
end
describe Fastlane::ToolSwiftFunction do
describe 'swift_vars' do
it 'generates empty array for protocols without parameters' do
swift_function = Fastlane::ToolSwiftFunction.new
result = swift_function.swift_vars
expect(result).to be_empty
end
it 'generates var without documentation' do
swift_function = Fastlane::ToolSwiftFunction.new(
keys: ['param_one'],
key_default_values: [''],
key_descriptions: [],
key_optionality_values: [],
key_type_overrides: []
)
result = swift_function.swift_vars
expect(result).to eq(["\n var paramOne: String { get }"])
end
it 'generates var with documentation' do
swift_function = Fastlane::ToolSwiftFunction.new(
keys: ['param_one'],
key_default_values: [''],
key_descriptions: ['key description'],
key_optionality_values: [],
key_type_overrides: []
)
result = swift_function.swift_vars
expect(result).to eq(["\n /// key description\n var paramOne: String { get }"])
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/junit_spec.rb | fastlane/spec/junit_spec.rb | describe Fastlane do
describe Fastlane::JUnitGenerator do
describe "#generate" do
it "properly generates a valid JUnit XML File" do
time = 25
step = {
name: "My Step Name",
error: nil,
time: time,
started: Time.now - 100
}
error_step = {
name: "error step",
error: "Some error text",
time: time,
started: Time.now - 50
}
results = []
99.times do
results << step
end
results << error_step
path = Fastlane::JUnitGenerator.generate(results)
expect(path).to end_with("report.xml")
content = File.read(path)
expect(content).to include("00: My Step Name")
expect(content).to include("98: My Step Name")
expect(content).to include("99: error step")
expect(content).to include("Some error text")
File.delete(path)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/one_off_spec.rb | fastlane/spec/one_off_spec.rb | require 'fastlane/one_off'
describe Fastlane do
describe Fastlane::OneOff do
describe "Valid parameters" do
before do
@runner = "runner"
expect(Fastlane::Runner).to receive(:new).and_return(@runner)
end
it "calls load_actions to load all built-in actions" do
action = 'increment_build_number'
expect(Fastlane).to receive(:load_actions)
expect(@runner).to receive(:execute_action).with(
action, Fastlane::Actions::IncrementBuildNumberAction, [{}], { custom_dir: "." }
)
Fastlane::OneOff.execute(args: [action])
end
it "works with no parameters" do
action = 'increment_build_number'
expect(@runner).to receive(:execute_action).with(
action, Fastlane::Actions::IncrementBuildNumberAction, [{}], { custom_dir: "." }
)
Fastlane::OneOff.execute(args: [action])
end
it "automatically converts the parameters" do
action = 'slack'
expect(@runner).to receive(:execute_action).with(
action, Fastlane::Actions::SlackAction, [{ message: "something" }], { custom_dir: "." }
)
Fastlane::OneOff.execute(args: [action, "message:something"])
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/command_line_handler_spec.rb | fastlane/spec/command_line_handler_spec.rb | describe Fastlane do
describe Fastlane::CommandLineHandler do
it "properly handles default calls" do
expect(Fastlane::LaneManager).to receive(:cruise_lane).with("ios", "deploy", {})
Fastlane::CommandLineHandler.handle(["ios", "deploy"], {})
end
it "properly handles calls with custom parameters" do
expect(Fastlane::LaneManager).to receive(:cruise_lane).with("ios", "deploy",
{ key: "value", build_number: '123' })
Fastlane::CommandLineHandler.handle(["ios", "deploy", "key:value", "build_number:123"], {})
end
it "properly converts boolean values to real boolean variables" do
expect(Fastlane::LaneManager).to receive(:cruise_lane).with("ios", "deploy",
{ key: true, key2: false })
Fastlane::CommandLineHandler.handle(["ios", "deploy", "key:true", "key2:false"], {})
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/runner_spec.rb | fastlane/spec/runner_spec.rb | describe Fastlane do
describe Fastlane::Runner do
describe "#available_lanes" do
before do
@ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileGrouped')
end
it "lists all available lanes" do
expect(@ff.runner.available_lanes).to eq(["test", "anotherroot", "mac beta", "ios beta", "ios release", "android beta", "android witherror", "android unsupported_action"])
end
it "allows filtering of results" do
expect(@ff.runner.available_lanes('android')).to eq(["android beta", "android witherror", "android unsupported_action"])
end
it "returns an empty array if invalid input is given" do
expect(@ff.runner.available_lanes('asdfasdfasdf')).to eq([])
end
it "doesn't show private lanes" do
expect(@ff.runner.available_lanes).to_not(include('android such_private'))
end
describe "step_name override" do
it "handle overriding of step_name" do
allow(Fastlane::Actions).to receive(:execute_action).with('Let it Frame')
@ff.runner.execute_action(:frameit, Fastlane::Actions::FrameitAction, [{ step_name: "Let it Frame" }])
end
it "rely on step_text when no step_name given" do
allow(Fastlane::Actions).to receive(:execute_action).with('frameit')
@ff.runner.execute_action(:frameit, Fastlane::Actions::FrameitAction, [{}])
end
end
end
describe "#execute" do
before do
@ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileLaneKeywordParams')
end
context 'when a lane does not expect any parameter' do
it 'accepts calling the lane with no parameter' do
result = @ff.runner.execute(:lane_no_param, :ios)
expect(result).to eq('No parameter')
end
it 'accepts calling the lane with arbitrary (unused) parameter' do
result = @ff.runner.execute(:lane_no_param, :ios, { unused1: 42, unused2: true })
expect(result).to eq('No parameter')
end
end
context 'when a lane expects its parameters as a Hash' do
it 'accepts calling the lane with no parameter at all' do
result = @ff.runner.execute(:lane_hash_param, :ios)
expect(result).to eq('name: nil; version: nil; interactive: nil')
end
it 'accepts calling the lane with less parameters than used by the lane' do
result = @ff.runner.execute(:lane_hash_param, :ios, { version: '12.3' })
expect(result).to eq('name: nil; version: "12.3"; interactive: nil')
end
it 'accepts calling the lane with more parameters than used by the lane' do
result = @ff.runner.execute(:lane_hash_param, :ios, { name: 'test', version: '12.3', interactive: true, unused: 42 })
expect(result).to eq('name: "test"; version: "12.3"; interactive: true')
end
end
context 'when a lane expects its parameters as keywords' do
def keywords_error_message(error, *kwlist)
# Depending on Ruby versions, the keyword names appear with or without a `:` in error messages, hence the `:?` Regexp
list = kwlist.map { |kw| ":?#{kw}" }.join(', ')
/#{Regexp.escape(error)}: #{list}/
end
it 'fails when calling the lane with required parameters not being passed' do
expect do
@ff.runner.execute(:lane_kw_params, :ios)
end.to raise_error(ArgumentError, keywords_error_message('missing keywords', :name, :version))
end
it 'fails when calling the lane with some missing parameters' do
expect do
@ff.runner.execute(:lane_kw_params, :ios, { name: 'test', interactive: true })
end.to raise_error(ArgumentError, keywords_error_message('missing keyword', :version))
end
it 'fails when calling the lane with extra parameters' do
expect do
@ff.runner.execute(:lane_kw_params, :ios, { name: 'test', version: '12.3', interactive: true, unexpected: 42 })
end.to raise_error(ArgumentError, keywords_error_message('unknown keyword', :unexpected))
end
it 'takes all parameters into account when all are passed explicitly' do
result = @ff.runner.execute(:lane_kw_params, :ios, { name: 'test', version: "12.3", interactive: false })
expect(result).to eq('name: "test"; version: "12.3"; interactive: false')
end
it 'uses default values of parameters not provided explicitly' do
result = @ff.runner.execute(:lane_kw_params, :ios, { name: 'test', version: "12.3" })
expect(result).to eq('name: "test"; version: "12.3"; interactive: true')
end
it 'allows parameters to be provided in arbitrary order' do
result = @ff.runner.execute(:lane_kw_params, :ios, { version: "12.3", interactive: true, name: 'test' })
expect(result).to eq('name: "test"; version: "12.3"; interactive: true')
end
it 'allows a required parameter to receive a nil value' do
result = @ff.runner.execute(:lane_kw_params, :ios, { name: nil, version: "12.3", interactive: true })
expect(result).to eq('name: nil; version: "12.3"; interactive: true')
end
it 'allows a default value to be overridden with a nil value' do
result = @ff.runner.execute(:lane_kw_params, :ios, { name: 'test', version: "12.3", interactive: nil })
expect(result).to eq('name: "test"; version: "12.3"; interactive: nil')
end
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/fast_file_spec.rb | fastlane/spec/fast_file_spec.rb | describe Fastlane do
describe Fastlane::FastFile do
describe "#initialize" do
it "raises an error if file does not exist" do
expect do
Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/fastfileNotHere')
end.to raise_exception("Could not find Fastfile at path './fastlane/spec/fixtures/fastfiles/fastfileNotHere'")
end
it "raises an error if unknown method is called" do
expect do
Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileInvalid')
end.to raise_exception("Could not find action, lane or variable 'laneasdf'. Check out the documentation for more details: https://docs.fastlane.tools/actions")
end
it "prints a warning if an uninstalled library is required" do
expect_any_instance_of(Fastlane::FastFile).to receive(:parse)
expect(UI).to receive(:important).with("You have required a gem, if this is a third party gem, please use `fastlane_require 'some_remote_gem'` to ensure the gem is installed locally.")
Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileRequireUninstalledGem')
end
it "does not print a warning if required library is installed" do
expect_any_instance_of(Fastlane::FastFile).to receive(:parse)
expect(UI).not_to(receive(:important))
Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileRequireInstalledGem')
end
end
describe "#sh" do
before do
@ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileGrouped')
end
context "with command argument" do
it "passes command as string with default log and error_callback" do
expect(Fastlane::Actions).to receive(:execute_action).with("git commit").and_call_original
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git commit", log: true, error_callback: nil)
@ff.sh("git commit")
end
it "passes command as string and log with default error_callback" do
expect(Fastlane::Actions).to receive(:execute_action).with("git commit").and_call_original
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git commit", log: true, error_callback: nil)
@ff.sh("git commit", log: true)
end
it "passes command as string, step_name, and log false with default error_callback" do
expect(Fastlane::Actions).to receive(:execute_action).with("some_name").and_call_original
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git commit", log: false, error_callback: nil)
@ff.sh("git commit", step_name: "some_name", log: false)
end
it "passes command as string, step_name, and log true with default error_callback" do
expect(Fastlane::Actions).to receive(:execute_action).with("some_name").and_call_original
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git commit", log: true, error_callback: nil)
@ff.sh("git commit", step_name: "some_name", log: true)
end
it "passes command as array with default log and error_callback" do
expect(Fastlane::Actions).to receive(:execute_action).with("git commit").and_call_original
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git", "commit", log: true, error_callback: nil)
@ff.sh("git", "commit")
end
it "passes command as array with default log and error_callback" do
expect(Fastlane::Actions).to receive(:execute_action).with("git commit").and_call_original
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git", "commit", log: true, error_callback: nil)
@ff.sh("git", "commit")
end
it "yields the status, result and command" do
expect(Fastlane::Actions).to receive(:execute_action).with("git commit").and_call_original
proc = proc {}
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git", "commit", log: true, error_callback: nil) do |*args, &block|
expect(proc).to be(block)
end
@ff.sh("git", "commit", &proc)
end
end
context "with named command keyword" do
it "passes command as string with default log and error_callback" do
expect(Fastlane::Actions).to receive(:execute_action).with("git commit").and_call_original
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git commit", log: true, error_callback: nil)
@ff.sh(command: "git commit")
end
it "passes command as string and log with default error_callback" do
expect(Fastlane::Actions).to receive(:execute_action).with("shell command").and_call_original
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git commit", log: false, error_callback: nil)
@ff.sh(command: "git commit", log: false)
end
it "passes command as array with default log and error_callback" do
expect(Fastlane::Actions).to receive(:execute_action).with("git commit").and_call_original
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git", "commit", log: true, error_callback: nil)
@ff.sh(command: ["git", "commit"])
end
it "yields the status, result and command" do
expect(Fastlane::Actions).to receive(:execute_action).with("git commit").and_call_original
proc = proc {}
expect(Fastlane::Actions).to receive(:sh_no_action)
.with("git", "commit", log: true, error_callback: nil) do |*args, &block|
expect(proc).to be(block)
end
@ff.sh(command: ["git", "commit"], &proc)
end
it "raises error if no :command keyboard" do
expect do
@ff.sh(log: true)
end.to raise_error(ArgumentError)
end
end
end
describe "#is_platform_block?" do
before do
@ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileGrouped')
end
it "return true if it's a platform" do
expect(@ff.is_platform_block?('mac')).to eq(true)
end
it "return true if it's a platform" do
expect(@ff.is_platform_block?('test')).to eq(false)
end
it "raises an exception if key doesn't exist at all" do
expect(UI).to receive(:user_error!).with("Could not find 'asdf'. Available lanes: test, anotherroot, mac beta, ios beta, ios release, android beta, android witherror, android unsupported_action")
@ff.is_platform_block?("asdf")
end
it "has an alias for `update`, if there is no lane called `update`" do
expect(Fastlane::OneOff).to receive(:run).with({ action: "update_fastlane", parameters: {} })
@ff.is_platform_block?("update")
end
end
describe "#lane_name" do
before do
@ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/Fastfile1')
end
it "raises an error if block is missing" do
expect(UI).to receive(:user_error!).with("You have to pass a block using 'do' for lane 'my_name'. Make sure you read the docs on GitHub.")
@ff.lane(:my_name)
end
it "takes the block and lane name" do
@ff.lane(:my_name) do
end
end
it "raises an error if name contains spaces" do
expect(UI).to receive(:user_error!).with("lane name must not contain any spaces")
@ff.lane(:"my name") do
end
end
it "raises an error if the name is on a deny list" do
expect(UI).to receive(:user_error!).with("Lane name 'run' is invalid")
@ff.lane(:run) do
end
end
it "raises an error if name is not a symbol" do
expect(UI).to receive(:user_error!).with("lane name must start with :")
@ff.lane("string") do
end
end
end
describe "Grouped fastlane for different platforms" do
before do
FileUtils.rm_rf('/tmp/fastlane/')
@ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileGrouped')
end
it "calls a block for a given platform (mac - beta)" do
@ff.runner.execute('beta', 'mac')
expect(File.exist?('/tmp/fastlane/mac_beta.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/before_all_android.txt')).to eq(false)
expect(File.exist?('/tmp/fastlane/before_all.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/before_each_beta.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/after_each_beta.txt')).to eq(true)
expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::LANE_NAME]).to eq("mac beta")
end
it "calls a block for a given platform (android - beta)" do
@ff.runner.execute('beta', 'android')
expect(File.exist?('/tmp/fastlane/android_beta.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/before_all_android.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/after_all_android.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/before_all.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/before_each_beta.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/after_each_beta.txt')).to eq(true)
expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::LANE_NAME]).to eq("android beta")
end
it "calls all error blocks if multiple are given (android - witherror)" do
expect do
@ff.runner.execute('witherror', 'android')
end.to raise_error('my exception')
expect(File.exist?('/tmp/fastlane/before_all_android.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/after_all_android.txt')).to eq(false)
expect(File.exist?('/tmp/fastlane/android_error.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/error.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/before_all.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/before_each_witherror.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/after_each_witherror.txt')).to eq(false)
expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::PLATFORM_NAME]).to eq(:android)
end
it "allows calls without a platform (nil - anotherroot)" do
@ff.runner.execute('anotherroot')
expect(File.exist?('/tmp/fastlane/before_all_android.txt')).to eq(false)
expect(File.exist?('/tmp/fastlane/after_all_android.txt')).to eq(false)
expect(File.exist?('/tmp/fastlane/android_error.txt')).to eq(false)
expect(File.exist?('/tmp/fastlane/error.txt')).to eq(false)
expect(File.exist?('/tmp/fastlane/before_all.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/another_root.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/before_each_anotherroot.txt')).to eq(true)
expect(File.exist?('/tmp/fastlane/after_each_anotherroot.txt')).to eq(true)
expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::LANE_NAME]).to eq("anotherroot")
expect(Fastlane::Actions.lane_context[Fastlane::Actions::SharedValues::PLATFORM_NAME]).to eq(nil)
end
it "logs a warning if and unsupported action is called on an non officially supported platform" do
expect(FastlaneCore::UI).to receive(:important).with("Action 'team_name' isn't known to support operating system 'android'.")
@ff.runner.execute('unsupported_action', 'android')
end
end
describe "Different Fastfiles" do
it "execute different envs" do
FileUtils.rm_rf('/tmp/fastlane/')
FileUtils.mkdir_p('/tmp/fastlane/')
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/Fastfile1')
ff.runner.execute(:deploy)
expect(File.exist?('/tmp/fastlane/before_all')).to eq(true)
expect(File.exist?('/tmp/fastlane/deploy')).to eq(true)
expect(File.exist?('/tmp/fastlane/test')).to eq(false)
expect(File.exist?('/tmp/fastlane/after_all')).to eq(true)
expect(File.read("/tmp/fastlane/after_all")).to eq("deploy")
ff.runner.execute(:test)
expect(File.exist?('/tmp/fastlane/test')).to eq(true)
end
it "prints a warning if a lane is called like an action" do
expect(UI).to receive(:error).with("------------------------------------------------")
expect(UI).to receive(:error).with("Name of the lane 'cocoapods' is already taken by the action named 'cocoapods'")
expect(UI).to receive(:error).with("------------------------------------------------")
Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileLaneNameEqualsActionName')
end
it "prefers a lane over a built-in action" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileLaneNameEqualsActionName')
result = ff.runner.execute(:test_lane)
expect(result).to eq("laneResult")
end
it "allows calling a lane directly even with a default_platform" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileGrouped')
result = ff.runner.execute(:test)
expect(result.to_i).to be > 10
end
it "Parameters are also passed to the before_all, after_all" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileConfigs')
time = Time.now.to_i.to_s
ff.runner.execute(:something, nil, { value: time })
expect(File.read("/tmp/before_all.txt")).to eq(time)
expect(File.read("/tmp/after_all.txt")).to eq(time)
File.delete("/tmp/before_all.txt")
File.delete("/tmp/after_all.txt")
end
it "allows the user to invent a new platform" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileNewPlatform')
expect do
ff.runner.execute(:crash, :windows)
end.to raise_error(":windows crash")
end
it "allows the user to set the platform in their Fastfile", focus: true do
expect(UI).to receive(:important).with("Setting '[:windows, :neogeo]' as extra SupportedPlatforms")
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileAddNewPlatform')
expect(UI).to receive(:message).with("echo :windows")
ff.runner.execute(:echo_lane, :windows)
end
it "before_each and after_each are called every time" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileLaneBlocks')
ff.runner.execute(:run_ios, :ios)
expect(File.exist?('/tmp/fastlane/before_all')).to eq(true)
expect(File.exist?('/tmp/fastlane/after_all')).to eq(true)
before_each = File.read("/tmp/fastlane/before_each")
after_each = File.read("/tmp/fastlane/after_each")
%w(run lane1 lane2).each do |lane|
expect(before_each).to include(lane)
expect(after_each).to include(lane)
end
File.delete("/tmp/fastlane/before_each")
File.delete("/tmp/fastlane/after_each")
File.delete("/tmp/fastlane/before_all")
File.delete("/tmp/fastlane/after_all")
end
it "Parameters are also passed to the error block" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileConfigs')
time = Time.now.to_i.to_s
expect do
ff.runner.execute(:crash, nil, { value: time })
end.to raise_error("Wups") # since we cause a crash
expect(File.read("/tmp/error.txt")).to eq(time)
File.delete("/tmp/error.txt")
end
it "Exception in error block are swallowed and shown, and original exception is re-raised" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileErrorInError')
expect(FastlaneCore::UI).to receive(:error).with("An error occurred while executing the `error` block:")
expect(FastlaneCore::UI).to receive(:error).with("Error in error")
expect do
ff.runner.execute(:beta, nil, {})
end.to raise_error("Original error")
end
describe "supports switching lanes" do
it "use case 1: passing parameters to another lane and getting the result" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/SwitcherFastfile')
ff.runner.execute(:lane1, :ios)
expect(File.read("/tmp/deliver_result.txt")).to eq("Lane 2 + parameter")
end
it "use case 2: passing no parameter to a lane that takes parameters" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/SwitcherFastfile')
ff.runner.execute(:lane3, :ios)
expect(File.read("/tmp/deliver_result.txt")).to eq("Lane 2 + ")
end
it "use case 3: Calling a lane directly which takes parameters" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/SwitcherFastfile')
ff.runner.execute(:lane4, :ios)
expect(File.read("/tmp/deliver_result.txt")).to eq("{}")
end
it "use case 4: Passing parameters to another lane" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/SwitcherFastfile')
ff.runner.execute(:lane5, :ios)
expected_value = if Gem::Version.create('3.4.0') <= Gem::Version.create(RUBY_VERSION)
"{key: :value}"
else
"{:key=>:value}"
end
expect(File.read("/tmp/deliver_result.txt")).to eq(expected_value)
end
it "use case 5: Calling a method outside of the current platform" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/SwitcherFastfile')
ff.runner.execute(:call_general_lane, :ios)
expected_value = if Gem::Version.create('3.4.0') <= Gem::Version.create(RUBY_VERSION)
"{random: :value}"
else
"{:random=>:value}"
end
expect(File.read("/tmp/deliver_result.txt")).to eq(expected_value)
end
it "calling a lane that doesn't exist" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/SwitcherFastfile')
expect do
ff.runner.execute(:invalid, :ios)
end.to raise_error("Could not find action, lane or variable 'wrong_platform'. Check out the documentation for more details: https://docs.fastlane.tools/actions")
end
it "raises an exception when not passing a hash" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/SwitcherFastfile')
expect do
ff.runner.execute(:invalid_parameters, :ios)
end.to raise_error("Parameters for a lane must always be a hash")
end
end
it "collects the lane description for documentation" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/Fastfile1')
ff.runner.execute(:deploy)
expect(ff.runner.lanes[nil][:deploy].description).to eq(["My Deploy", "description"])
expect(ff.runner.lanes[:mac][:specific].description).to eq(["look at my mac, my mac is amazing"])
end
it "execute different envs with lane in before block" do
FileUtils.rm_rf('/tmp/fastlane/')
FileUtils.mkdir_p('/tmp/fastlane/')
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/Fastfile2')
ff.runner.execute(:deploy)
expect(File.exist?('/tmp/fastlane/before_all_deploy')).to eq(true)
expect(File.exist?('/tmp/fastlane/deploy')).to eq(true)
expect(File.exist?('/tmp/fastlane/test')).to eq(false)
expect(File.exist?('/tmp/fastlane/after_all')).to eq(true)
expect(File.read("/tmp/fastlane/after_all")).to eq("deploy")
ff.runner.execute(:test)
expect(File.exist?('/tmp/fastlane/test')).to eq(true)
end
it "automatically converts invalid quotations" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileInvalidQuotation')
# No exception :)
end
it "properly shows an error message when there is a syntax error in the Fastfile" do
allow(FastlaneCore::FastlaneFolder).to receive(:path).and_return(nil)
expect(UI).to receive(:content_error).with(<<-RUBY.chomp, "17")
# empty lines to test the line parsing as well
lane :beta do
sigh(app_identifier: "hi"
end
RUBY
expected_message = if Gem::Version.create('3.4.0') <= Gem::Version.create(RUBY_VERSION)
%r{Syntax error in your Fastfile on line 17: fastlane/spec/fixtures/fastfiles/FastfileSyntaxError:17: syntax error found}
else
%r{Syntax error in your Fastfile on line 17: fastlane/spec/fixtures/fastfiles/FastfileSyntaxError:17: syntax error, unexpected (keyword_end|end|`end'), expecting '\)'}
end
expect(UI).to receive(:user_error!).with(expected_message)
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileSyntaxError')
end
it "properly shows an error message when there is a syntax error in the Fastfile from string" do
# ruby error message differs in 2.5 and earlier. We use a matcher
expected_arg = if Gem::Version.create('3.4.0') <= Gem::Version.create(RUBY_VERSION)
"2"
else
"3"
end
expect(UI).to receive(:content_error).with(<<-RUBY.chomp, expected_arg)
lane :test do
cases = [:abc,
end
RUBY
expected_message = if Gem::Version.create('3.4.0') <= Gem::Version.create(RUBY_VERSION)
/Syntax error in your Fastfile on line 2: \(eval\):2: syntax errors found.*/
else
/Syntax error in your Fastfile on line 3: \(eval\):3: syntax error, unexpected (keyword_end|end|`end'), expecting '\]'\n end\n.*/
end
expect(UI).to receive(:user_error!).with(expected_message)
ff = Fastlane::FastFile.new.parse(<<-RUBY.chomp)
lane :test do
cases = [:abc,
end
RUBY
end
it "properly shows an error message when there is a syntax error in the imported Fastfile" do
allow(FastlaneCore::FastlaneFolder).to receive(:path).and_return(nil)
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/Fastfile')
expect(UI).to receive(:content_error).with(<<-RUBY.chomp, "17")
# empty lines to test the line parsing as well
lane :beta do
sigh(app_identifier: "hi"
end
RUBY
expected_message = if Gem::Version.create('3.4.0') <= Gem::Version.create(RUBY_VERSION)
%r{Syntax error in your Fastfile on line 17: fastlane/spec/fixtures/fastfiles/FastfileSyntaxError:17: syntax error found}
else
%r{Syntax error in your Fastfile on line 17: fastlane/spec/fixtures/fastfiles/FastfileSyntaxError:17: syntax error, unexpected (keyword_end|end|`end'), expecting '\)'}
end
expect(UI).to receive(:user_error!).with(expected_message)
ff.import('./FastfileSyntaxError')
end
it "imports actions associated with a Fastfile before their Fastfile" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/Fastfile')
expect do
ff.import('./import1/Fastfile')
end.not_to(raise_error)
end
it "raises an error if lane is not available" do
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/Fastfile1')
expect do
ff.runner.execute(:not_here)
end.to raise_exception("Could not find lane 'not_here'. Available lanes: test, deploy, error_causing_lane, mac specific")
end
it "raises an error if the lane name contains spaces" do
expect(UI).to receive(:user_error!).with("lane name must not contain any spaces")
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/FastfileInvalidName')
end
it "runs pod install" do
allow(FastlaneCore::FastlaneFolder).to receive(:path).and_return(nil)
expect(Fastlane::Actions).to receive(:verify_gem!).with("cocoapods")
result = Fastlane::FastFile.new.parse("lane :test do
cocoapods
end").runner.execute(:test)
expect(result).to eq("bundle exec pod install")
end
it "calls the error block when an error occurs" do
FileUtils.rm_rf('/tmp/fastlane/')
FileUtils.mkdir_p('/tmp/fastlane/')
ff = Fastlane::FastFile.new('./fastlane/spec/fixtures/fastfiles/Fastfile1')
expect do
ff.runner.execute(:error_causing_lane)
end.to raise_exception("divided by 0")
expect(File.exist?('/tmp/fastlane/before_all')).to eq(true)
expect(File.exist?('/tmp/fastlane/deploy')).to eq(false)
expect(File.exist?('/tmp/fastlane/test')).to eq(false)
expect(File.exist?('/tmp/fastlane/after_all')).to eq(false)
expect(File.exist?('/tmp/fastlane/error')).to eq(true)
expect(File.read("/tmp/fastlane/error")).to eq("error_causing_lane")
end
it "raises an error if one lane is defined multiple times" do
expect do
Fastlane::FastFile.new.parse("lane :test do
end
lane :test do
end")
end.to raise_exception("Lane 'test' was defined multiple times!")
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/spec_helper_spec.rb | fastlane/spec/spec_helper_spec.rb | describe FastlaneSpec::Env do
# rubocop:disable Naming/VariableName
describe "#with_ARGV" do
it "temporarily overrides the ARGV values under normal usage" do
current_ARGV = ARGV.dup
temp_ARGV = ['temp_inside']
block_ARGV = nil
FastlaneSpec::Env.with_ARGV(temp_ARGV) do
block_ARGV = ARGV.dup
end
expect(block_ARGV).to eq(temp_ARGV)
expect(ARGV).to eq(current_ARGV)
end
it "restores ARGV values even if fails in block" do
current_ARGV = ARGV.dup
begin
FastlaneSpec::Env.with_ARGV(['temp_inside']) do
raise "BOU"
end
fail("should not reach here")
rescue
end
expect(ARGV).to eq(current_ARGV)
end
end
# rubocop:enable Naming/VariableName
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/spec_helper.rb | fastlane/spec/spec_helper.rb | Fastlane.load_actions
def before_each_fastlane
Fastlane::Actions.clear_lane_context
ENV.delete('DELIVER_SCREENSHOTS_PATH')
ENV.delete('DELIVER_SKIP_BINARY')
ENV.delete('DELIVER_VERSION')
end
def stub_plugin_exists_on_rubygems(plugin_name, exists)
stub_request(:get, "https://rubygems.org/api/v1/gems/fastlane-plugin-#{plugin_name}.json").
with(headers: { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby' }).
to_return(status: 200, body: (exists ? { version: "1.0" }.to_json : nil), headers: {})
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/fastlane_require_spec.rb | fastlane/spec/fastlane_require_spec.rb | require 'fastlane/fastlane_require'
describe Fastlane do
describe Fastlane::FastlaneRequire do
it "formats gem require name for fastlane-plugin" do
gem_name = "fastlane-plugin-test"
gem_require_name = Fastlane::FastlaneRequire.format_gem_require_name(gem_name)
expect(gem_require_name).to eq("fastlane/plugin/test")
end
it "formats gem require name for non-fastlane-plugin" do
gem_name = "some-lib"
gem_require_name = Fastlane::FastlaneRequire.format_gem_require_name(gem_name)
expect(gem_require_name).to eq("some-lib")
end
describe "checks if a gem is installed" do
it "true on known installed gem" do
gem_name = "fastlane"
gem_installed = Fastlane::FastlaneRequire.gem_installed?(gem_name)
expect(gem_installed).to be(true)
end
it "false on known missing gem" do
gem_name = "foobar"
gem_installed = Fastlane::FastlaneRequire.gem_installed?(gem_name)
expect(gem_installed).to be(false)
end
it "true on known preinstalled gem" do
gem_name = "yaml"
gem_installed = Fastlane::FastlaneRequire.gem_installed?(gem_name)
expect(gem_installed).to be(true)
end
end
end
end
| ruby | MIT | d1f6eb6228644936997aae1956d8036ea62cd5b4 | 2026-01-04T15:37:27.371479Z | false |
fastlane/fastlane | https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/fastlane/spec/plugins_specs/plugin_generator_ui_spec.rb | fastlane/spec/plugins_specs/plugin_generator_ui_spec.rb | describe Fastlane::PluginGeneratorUI do
let(:ui) { Fastlane::PluginGeneratorUI.new }
describe '#message' do
it 'calls puts' do
expect(ui).to receive(:puts).with('hi')
ui.message('hi')
end
end
describe '#input' do
it 'calls UI#input' do
expect(UI).to receive(:input).with('hi')
ui.input('hi')
end
end
describe '#confirm' do
it 'calls UI#confirm' do
expect(UI).to receive(:confirm).with('hi')
ui.confirm('hi')
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.