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
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/cli.rb
lib/rails_best_practices/cli.rb
# frozen_string_literal: true module RailsBestPractices class CLI # Run analyze with ruby code # @param [Array] argv command argments # @return [Boolean] return true, if there is no violation. # @example # RailsBestPractices::CLI.run(['-d', '-o', 'path/to/file']) def self.run(argv) options = OptionParser.parse!(argv) if !argv.empty? && !File.exist?(argv.first) raise Errno::ENOENT, "#{argv.first} doesn't exist" end analyzer = Analyzer.new(argv.first, options) analyzer.analyze analyzer.output analyzer.runner.errors.empty? end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews.rb
lib/rails_best_practices/reviews.rb
# frozen_string_literal: true require_rel 'reviews'
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares.rb
lib/rails_best_practices/prepares.rb
# frozen_string_literal: true require_rel 'prepares' module RailsBestPractices module Prepares class << self def klasses models + mailers + controllers end def models @models ||= Core::Models.new end def model_associations @model_associations ||= Core::ModelAssociations.new end def model_attributes @model_attributes ||= Core::ModelAttributes.new end def model_methods @model_methods ||= Core::Methods.new end def mailers @mailers ||= Core::Mailers.new end def controllers @controllers ||= Core::Controllers.new end def controller_methods @controller_methods ||= Core::Methods.new end def helpers @helpers ||= Core::Helpers.new end def helper_methods @helper_methods ||= Core::Methods.new end def routes @routes ||= Core::Routes.new end def configs @configs ||= Core::Configs.new end def gems @gems ||= Core::Gems.new end # Clear all prepare objects. def clear instance_variables.each do |instance_variable| instance_variable_set(instance_variable, nil) end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/colorize.rb
lib/rails_best_practices/colorize.rb
# frozen_string_literal: true module RailsBestPractices class Colorize def self.red(message) "\e[31m#{message}\e[0m" end def self.green(message) "\e[32m#{message}\e[0m" end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/use_multipart_alternative_as_content_type_of_email_review.rb
lib/rails_best_practices/reviews/use_multipart_alternative_as_content_type_of_email_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Make sure to use multipart/alternative as content_type of email. # # See the best practice details here https://rails-bestpractices.com/posts/2010/08/05/use-multipart-alternative-as-content_type-of-email/ # # Implementation: # # Review process: # check class node to remember the class name, # and check the method definition nodes to see if the corresponding mailer views exist or not. class UseMultipartAlternativeAsContentTypeOfEmailReview < Review interesting_nodes :class, :def interesting_files MAILER_FILES url 'https://rails-bestpractices.com/posts/2010/08/05/use-multipart-alternative-as-content_type-of-email/' # check class node to remember the ActionMailer class name. add_callback :start_class do |node| @klazz_name = node.class_name.to_s end # check def node and find if the corresponding views exist or not? add_callback :start_def do |node| name = node.method_name.to_s unless rails3_canonical_mailer_views?(name) add_error('use multipart/alternative as content_type of email') end end private # check if rails's syntax mailer views are canonical. # # @param [String] name method name in action_mailer def rails_canonical_mailer_views?(name); end # check if rails3's syntax mailer views are canonical. # # @param [String] name method name in action_mailer def rails3_canonical_mailer_views?(name) return true if mailer_files(name).empty? return true if mailer_files(name).none? { |filename| filename.index 'html' } mailer_files(name).any? { |filename| filename.index 'html' } && mailer_files(name).any? { |filename| filename.index 'text' } end # all mail view files for a method name. def mailer_files(name) Dir.entries(mailer_directory) { |filename| filename.index name.to_s } end # the view directory of mailer. def mailer_directory File.join(Core::Runner.base_path, "app/views/#{@klazz_name.to_s.underscore}") end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/needless_deep_nesting_review.rb
lib/rails_best_practices/reviews/needless_deep_nesting_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review config/routes.rb file to make sure not to use too deep nesting routes. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/22/needless-deep-nesting/ # # Implementation: # # Review process: # chech all method_add_block nodes in route file. # # it is a recursively check in method_add_block node, # # if it is a method_add_block node, # increment @counter at the beginning of resources, # decrement @counter at the end of resrouces, # recursively check nodes in block body. # # if the child node is a command_call or command node, # and the message of the node is "resources" or "resource", # and the @counter is greater than @nested_count defined, # then it is a needless deep nesting. class NeedlessDeepNestingReview < Review interesting_nodes :method_add_block interesting_files ROUTE_FILES url 'https://rails-bestpractices.com/posts/2010/07/22/needless-deep-nesting/' def initialize(options = {}) super(options) @counter = 0 @nested_count = options['nested_count'] || 2 @shallow_nodes = [] end # check all method_add_block node. # # It is a recursively check, if it is a method_add_block node, # increment @counter at the beginning of resources, # decrement @counter at the end of method_add_block resources, # recursively check the block body. # # if the child node is a command_call or command node with message "resources" or "resource", # test if the @counter is greater than or equal to @nested_count, # if so, it is a needless deep nesting. add_callback :start_method_add_block do |node| @file = node.file recursively_check(node) end private # check nested route. # # if the receiver of the method_add_block is with message "resources" or "resource", # then increment the @counter, recursively check the block body, and decrement the @counter. # # if the node type is command_call or command, # and its message is resources or resource, # then check if @counter is greater than or equal to @nested_count, # if so, it is the needless deep nesting. def recursively_check(node) shallow = @shallow_nodes.include? node if %i[command_call command].include?(node[1].sexp_type) && %w[resources resource].include?(node[1].message.to_s) hash_node = node[1].arguments.grep_node(sexp_type: :bare_assoc_hash) shallow ||= (hash_node && hash_node.hash_value('shallow').to_s == 'true') @counter += 1 node.block_node.statements.each do |stmt_node| @shallow_nodes << stmt_node if shallow recursively_check(stmt_node) end @counter -= 1 elsif %i[command_call command].include?(node.sexp_type) && %w[resources resource].include?(node.message.to_s) add_error "needless deep nesting (nested_count > #{@nested_count})", @file, node.line_number if @counter >= @nested_count && !@shallow_nodes.include?(node) end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/hash_syntax_review.rb
lib/rails_best_practices/reviews/hash_syntax_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Check ruby 1.8 style hash and suggest to change hash syntax to 1.9. # # Review process: # check hash nodes in all files, # if the sexp type of hash key nodes is not :@lable, # then the hash is ruby 1.8 style. class HashSyntaxReview < Review interesting_nodes :hash, :bare_assoc_hash interesting_files ALL_FILES VALID_SYMBOL_KEY = /\A[@$_A-Za-z]([_\w]*[!_=?\w])?\z/.freeze # check hash node to see if it is ruby 1.8 style. add_callback :start_hash, :start_bare_assoc_hash do |node| if !empty_hash?(node) && hash_is_18?(node) && valid_keys?(node) add_error 'change Hash Syntax to 1.9' end end protected # check if hash node is empty. def empty_hash?(node) s(:hash, nil) == node || s(:bare_assoc_hash, nil) == node end # check if hash key/value pairs are ruby 1.8 style. def hash_is_18?(node) pair_nodes = node.sexp_type == :hash ? node[1][1] : node[1] return false if pair_nodes.blank? pair_nodes.any? { |pair_node| pair_node[1].sexp_type == :symbol_literal } end # check if the hash keys are valid to be converted to ruby 1.9 # syntax. def valid_keys?(node) node.hash_keys.all? { |key| key =~ VALID_SYMBOL_KEY } end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/not_rescue_exception_review.rb
lib/rails_best_practices/reviews/not_rescue_exception_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review all code to make sure we don't rescue Exception # This is a common mistake by Java or C# devs in ruby. # # See the best practice details here https://rails-bestpractices.com/posts/2012/11/01/don-t-rescue-exception-rescue-standarderror/ # # Implementation: # # Review process: # check all rescue node to see if its type is Exception class NotRescueExceptionReview < Review interesting_nodes :rescue interesting_files ALL_FILES url 'https://rails-bestpractices.com/posts/2012/11/01/don-t-rescue-exception-rescue-standarderror/' # check rescue node to see if its type is Exception add_callback :start_rescue do |rescue_node| if rescue_node.exception_classes.any? { |rescue_class| rescue_class.to_s == 'Exception' } add_error "Don't rescue Exception", rescue_node.file, rescue_node.exception_classes.first.line_number end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/isolate_seed_data_review.rb
lib/rails_best_practices/reviews/isolate_seed_data_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Make sure not to insert data in migration, move them to seed file. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/24/isolating-seed-data/ # # Implementation: # # Review process: # 1. check all assignment nodes, # if the right value is a call node with message "new", # then remember their left value as new variables. # # 2. check all call nodes, # if the message is "create" or "create!", # then it should be isolated to db seed. # if the message is "save" or "save!", # and the receiver is included in new variables, # then it should be isolated to db seed. class IsolateSeedDataReview < Review interesting_nodes :call, :assign interesting_files MIGRATION_FILES url 'https://rails-bestpractices.com/posts/2010/07/24/isolating-seed-data/' def initialize(options = {}) super(options) @new_variables = [] end # check assignment node. # # if the right value of the node is a call node with "new" message, # then remember it as new variables. add_callback :start_assign do |node| remember_new_variable(node) end # check the call node. # # if the message of the call node is "create" or "create!", # then you should isolate it to seed data. # # if the message of the call node is "save" or "save!", # and the receiver of the call node is included in @new_variables, # then you should isolate it to seed data. add_callback :start_call do |node| if ['create', 'create!'].include? node.message.to_s add_error('isolate seed data') elsif ['save', 'save!'].include? node.message.to_s add_error('isolate seed data') if new_record?(node) end end private # check assignment node, # if the right vavlue is a method_add_arg node with message "new", # then remember the left value as new variable. def remember_new_variable(node) right_value = node.right_value if right_value.sexp_type == :method_add_arg && right_value.message.to_s == 'new' @new_variables << node.left_value.to_s end end # see if the receiver of the call node is included in the @new_varaibles. def new_record?(node) @new_variables.include? node.receiver.to_s end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/move_code_into_controller_review.rb
lib/rails_best_practices/reviews/move_code_into_controller_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a view file to make sure there is no finder, finder should be moved to controller. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/24/move-code-into-controller/ # # Implementation: # # Review process: # only check all view files to see if there are finders, then the finders should be moved to controller. class MoveCodeIntoControllerReview < Review interesting_nodes :method_add_arg, :assign interesting_files VIEW_FILES url 'https://rails-bestpractices.com/posts/2010/07/24/move-code-into-controller/' FINDERS = %w[find all first last].freeze # check method_add_arg nodes. # # if the receiver of the method_add_arg node is a constant, # and the message of the method_add_arg node is one of the find, all, first and last, # then it is a finder and should be moved to controller. add_callback :start_method_add_arg do |node| add_error 'move code into controller' if finder?(node) end # check assign nodes. # # if the receiver of the right value node is a constant, # and the message of the right value node is one of the find, all, first and last, # then it is a finder and should be moved to controller. add_callback :start_assign do |node| add_error 'move code into controller', node.file, node.right_value.line_number if finder?(node.right_value) end private # check if the node is a finder call node. def finder?(node) node.receiver.const? && FINDERS.include?(node.message.to_s) end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/check_save_return_value_review.rb
lib/rails_best_practices/reviews/check_save_return_value_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review all code to make sure we either check the return value of "save", "update_attributes" # and "create" or use "save!", "update_attributes!", or "create!", respectively. # # See the best practice details here https://rails-bestpractices.com/posts/2012/11/02/check-the-return-value-of-save-otherwise-use-save/ # # Implementation: # # Review process: # Track which nodes are used by 'if', 'unless', '&&' nodes etc. as we pass them by. # Check all "save" calls to check the return value is used by a node we have visited. class CheckSaveReturnValueReview < Review include Classable interesting_nodes :call, :command_call, :method_add_arg, :if, :ifop, :elsif, :unless, :if_mod, :unless_mod, :assign, :binary interesting_files ALL_FILES url 'https://rails-bestpractices.com/posts/2012/11/02/check-the-return-value-of-save-otherwise-use-save/' add_callback :start_if, :start_ifop, :start_elsif, :start_unless, :start_if_mod, :start_unless_mod do |node| @used_return_value_of = node.conditional_statement.all_conditions end add_callback :start_assign do |node| @used_return_value_of = node.right_value end # Consider anything used in an expression like "A or B" as used add_callback :start_binary do |node| if %w[&& || and or].include?(node[2].to_s) all_conditions = node.all_conditions # if our current binary is a subset of the @used_return_value_of # then don't overwrite it already_included = @used_return_value_of && (all_conditions - @used_return_value_of).empty? @used_return_value_of = node.all_conditions unless already_included end end def return_value_is_used?(node) return false unless @used_return_value_of (node == @used_return_value_of) || @used_return_value_of.include?(node) end def model_classnames @model_classnames ||= models.map(&:to_s) end add_callback :start_call, :start_command_call, :start_method_add_arg do |node| unless @already_checked == node message = node.message.to_s if %w[save update_attributes].include? message unless return_value_is_used? node add_error "check '#{message}' return value or use '#{message}!'" end elsif message == 'create' # We're only interested in 'create' calls on model classes: possible_receiver_classes = [node.receiver.to_s] + classable_modules.map do |mod| "#{mod}::#{node.receiver}" end unless (possible_receiver_classes & model_classnames).empty? add_error "use 'create!' instead of 'create' as the latter may not always save" end end if node.sexp_type == :method_add_arg @already_checked = node[1] end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/move_code_into_helper_review.rb
lib/rails_best_practices/reviews/move_code_into_helper_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a view file to make sure there is no complex options_for_select message call. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/24/move-code-into-helper/ # # TODO: we need a better soluation, any suggestion? # # Implementation: # # Review process: # check al method method_add_arg nodes to see if there is a complex options_for_select helper. # # if the message of the method_add_arg node is options_for_select, # and the first argument of the method_add_arg node is array, # and the size of the array is greater than array_count defined, # then the options_for_select method should be moved into helper. class MoveCodeIntoHelperReview < Review interesting_nodes :method_add_arg interesting_files VIEW_FILES url 'https://rails-bestpractices.com/posts/2010/07/24/move-code-into-helper/' def initialize(options = {}) super(options) @array_count = options['array_count'] || 3 end # check method_add_arg node with message options_for_select (sorry we only check options_for_select helper now). # # if the first argument of options_for_select method call is an array, # and the size of the array is more than @array_count defined, # then the options_for_select helper should be moved into helper. add_callback :start_method_add_arg do |node| add_error "move code into helper (array_count >= #{@array_count})" if complex_select_options?(node) end private # check if the arguments of options_for_select are complex. # # if the first argument is an array, # and the size of array is greater than @array_count you defined, # then it is complext. def complex_select_options?(node) node[1].message.to_s == 'options_for_select' && node.arguments.all.first.sexp_type == :array && node.arguments.all.first.array_size > @array_count end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/replace_instance_variable_with_local_variable_review.rb
lib/rails_best_practices/reviews/replace_instance_variable_with_local_variable_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a partail view file to make sure there is no instance variable. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/24/replace-instance-variable-with-local-variable/ # # Implementation: # # Review process: # check all instance variable in partial view files, # if exist, then they should be replaced with local variable class ReplaceInstanceVariableWithLocalVariableReview < Review interesting_nodes :var_ref, :vcall interesting_files PARTIAL_VIEW_FILES url 'https://rails-bestpractices.com/posts/2010/07/24/replace-instance-variable-with-local-variable/' # check ivar node in partial view file, # it is an instance variable, and should be replaced with local variable. add_callback :start_var_ref, :start_vcall do |node| if node.to_s.start_with?('@') add_error 'replace instance variable with local variable' end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/move_model_logic_into_model_review.rb
lib/rails_best_practices/reviews/move_model_logic_into_model_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a controller file to make sure that complex model logic should not exist in controller, should be moved into a model. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/21/move-model-logic-into-the-model/ # # Implementation: # # Review process: # check all method defines in the controller files, # if there are multiple method calls apply to one receiver, # and the receiver is a variable, # then they are complex model logic, and they should be moved into model. class MoveModelLogicIntoModelReview < Review interesting_nodes :def interesting_files CONTROLLER_FILES url 'https://rails-bestpractices.com/posts/2010/07/21/move-model-logic-into-the-model/' def initialize(options = {}) super(options) @use_count = options['use_count'] || 4 end # check method define node to see if there are multiple method calls on one varialbe. # # it will check every call nodes, # if there are multiple call nodes who have the same receiver, # and the receiver is a variable, # then these method calls and attribute assignments should be moved into model. add_callback :start_def do |node| node.grep_nodes(sexp_type: %i[call assign]) do |child_node| remember_variable_use_count(child_node) end variable_use_count.each do |variable_node, count| add_error "move model logic into model (#{variable_node} use_count > #{@use_count})" if count > @use_count end reset_variable_use_count end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/remove_empty_helpers_review.rb
lib/rails_best_practices/reviews/remove_empty_helpers_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a helper file to make sure it is not an empty moduel. # # See the best practice details here https://rails-bestpractices.com/posts/2011/04/09/remove-empty-helpers/ # # Implementation: # # Review process: # check all helper files, if the body of module is nil, then the helper file should be removed. class RemoveEmptyHelpersReview < Review interesting_nodes :module interesting_files HELPER_FILES url 'https://rails-bestpractices.com/posts/2011/04/09/remove-empty-helpers/' # check the body of module node, if it is nil, then it should be removed. add_callback :start_module do |module_node| if module_node.module_name.to_s != 'ApplicationHelper' && empty_body?(module_node) add_error 'remove empty helpers' end end protected def empty_body?(module_node) s(:bodystmt, s(:stmts_add, s(:stmts_new), s(:void_stmt)), nil, nil, nil) == module_node.body end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/use_model_association_review.rb
lib/rails_best_practices/reviews/use_model_association_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # review a controller file to make sure to use model association instead of foreign key id assignment. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/19/use-model-association/ # # Implementation: # # Review process: # check model define nodes in all controller files, # if there is an attribute assignment node with message xxx_id=, # and after it, there is a call node with message "save" or "save!", # and the receivers of attribute assignment node and call node are the same, # then model association should be used instead of xxx_id assignment. class UseModelAssociationReview < Review interesting_nodes :def interesting_files CONTROLLER_FILES url 'https://rails-bestpractices.com/posts/2010/07/19/use-model-association/' # check method define nodes to see if there are some attribute assignments that can use model association instead. # # it will check attribute assignment node with message xxx_id=, and call node with message "save" or "save!" # # 1. if there is an attribute assignment node with message xxx_id=, # then remember the receiver of attribute assignment node. # 2. after assignment, if there is a call node with message "save" or "save!", # and the receiver of call node is one of the receiver of attribute assignment node, # then the attribute assignment should be replaced by using model association. add_callback :start_def do |node| @assignments = {} node.recursive_children do |child| case child.sexp_type when :assign attribute_assignment(child) when :call call_assignment(child) end end @assignments = nil end private # check an attribute assignment node, if its message is xxx_id, # then remember the receiver of the attribute assignment in @assignments. def attribute_assignment(node) if node.left_value.message.is_a?(Sexp) && node.left_value.message.to_s =~ /_id$/ receiver = node.left_value.receiver.to_s @assignments[receiver] = true end end # check a call node with message "save" or "save!", # if the receiver of call node exists in @assignments, # then the attribute assignment should be replaced by using model association. def call_assignment(node) if ['save', 'save!'].include? node.message.to_s receiver = node.receiver.to_s add_error "use model association (for #{receiver})" if @assignments[receiver] end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/review.rb
lib/rails_best_practices/reviews/review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # A Review class that takes charge of reviewing one rails best practice. class Review < Core::Check # default url. url '#' # remember use count for the variable in the call or assign node. # # find the variable in the call or assign node, # then save it to as key in @variable_use_count hash, and add the call count (hash value). def remember_variable_use_count(node) variable_node = variable(node) if variable_node && variable_node.to_s != 'self' && @last_variable_node != variable_node @last_variable_node = variable_node variable_use_count[variable_node.to_s] ||= 0 variable_use_count[variable_node.to_s] += 1 end end # return @variable_use_count hash. def variable_use_count @variable_use_count ||= {} end # reset @variable_use_count hash. def reset_variable_use_count @variable_use_count = nil end # find variable in the call or field node. def variable(node) while %i[call field method_add_arg method_add_block].include?(node.receiver.sexp_type) node = node.receiver end return if %i[fcall hash].include?(node.receiver.sexp_type) node.receiver end # get the models from Prepares. # # @return [Array] def models @models ||= Prepares.models end # get the model associations from Prepares. # # @return [Hash] def model_associations @model_associations ||= Prepares.model_associations end # get the model attributes from Prepares. # # @return [Hash] def model_attributes @model_attributes ||= Prepares.model_attributes end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/use_turbo_sprockets_rails3_review.rb
lib/rails_best_practices/reviews/use_turbo_sprockets_rails3_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Prepare Gemfile and review Capfile file to make sure using turbo-sprocket-rails3 # # See the best practice details here https://rails-bestpractices.com/posts/2012/11/23/speed-up-assets-precompile-with-turbo-sprockets-rails3/ # # Implementation: # # Review process: # only check if turbo-sprockets-rails3 gem is not used and load 'deploy/assets' in Capfile. class UseTurboSprocketsRails3Review < Review interesting_nodes :command interesting_files CAPFILE url 'https://rails-bestpractices.com/posts/2012/11/23/speed-up-assets-precompile-with-turbo-sprockets-rails3/' # check command node to see if load 'deploy/assets' add_callback :start_command do |node| if Prepares.gems.gem_version('rails').to_i == 3 if !Prepares.gems.has_gem?('turbo-sprockets-rails3') && node.message.to_s == 'load' && node.arguments.to_s == 'deploy/assets' add_error 'speed up assets precompile with turbo-sprockets-rails3' end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/replace_complex_creation_with_factory_method_review.rb
lib/rails_best_practices/reviews/replace_complex_creation_with_factory_method_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a controller file to make sure that complex model creation should not exist in # controller, should be replaced with factory method. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/21/replace-complex-creation-with-factory-method/ # # Implementation: # # Review process: # check all method defines in the controller files, # if there are multiple attribute assignments apply to one receiver, # and the receiver is a variable, # and after them there is a call node with message "save" or "save!", # then these attribute assignments are complex creation, should be replaced with factory method. class ReplaceComplexCreationWithFactoryMethodReview < Review interesting_nodes :def interesting_files CONTROLLER_FILES url 'https://rails-bestpractices.com/posts/2010/07/21/replace-complex-creation-with-factory-method/' def initialize(options = {}) super(options) @assigns_count = options['attribute_assignment_count'] || 2 end # check method define node to see if there are multiple assignments, more than # @assigns_count, on one variable before save. # # it wll check every attrasgn nodes in method define node, # if there are multiple assign nodes who have the same receiver, # and the receiver is a variable, # and after them, there is a call node with message "save" or "save!", # then these attribute assignments are complex creation, should be replaced with factory method. add_callback :start_def do |node| node.recursive_children do |child_node| case child_node.sexp_type when :assign if child_node.receiver[2].to_s == '.' remember_variable_use_count(child_node) end when :call check_variable_save(child_node) end end reset_variable_use_count end private # check the call node to see if it is with message "save" or "save!", # and the count attribute assignment on the receiver of the call node is greater than @assign_count defined, # then it is a complex creation, should be replaced with factory method. def check_variable_save(node) if ['save', 'save!'].include? node.message.to_s variable = node.receiver.to_s if variable_use_count[variable].to_i > @assigns_count hint = "#{variable} attribute_assignment_count > #{@assigns_count}" add_error "replace complex creation with factory method (#{hint})" end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/law_of_demeter_review.rb
lib/rails_best_practices/reviews/law_of_demeter_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review to make sure not to avoid the law of demeter. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/24/the-law-of-demeter/ # # Implementation: # # Review process: # check all method calls to see if there is method call to the association object. # if there is a call node whose receiver is an object of model (compare by name), # and whose message is an association of that model (also compare by name), # and outer the call node, it is also a call node, # then it violate the law of demeter. class LawOfDemeterReview < Review interesting_nodes :call interesting_files ALL_FILES url 'https://rails-bestpractices.com/posts/2010/07/24/the-law-of-demeter/' ASSOCIATION_METHODS = %w[belongs_to has_one].freeze # check the call node, # # if the receiver of the call node is also a call node, # and the receiver of the receiver call node matchs one of the class names, # and the message of the receiver call node matchs one of the association name with the class name, # then it violates the law of demeter. add_callback :start_call do |node| if node.receiver.sexp_type == :call && need_delegate?(node) add_error 'law of demeter' end end private # check if the call node can use delegate to avoid violating law of demeter. # # if the receiver of receiver of the call node matchs any in model names, # and the message of receiver of the call node matchs any in association names, # then it needs delegate. def need_delegate?(node) return unless variable(node) class_name = variable(node).to_s.sub('@', '').classify association_name = node.receiver.message.to_s association = model_associations.get_association(class_name, association_name) attribute_name = node.message.to_s association && ASSOCIATION_METHODS.include?(association['meta']) && is_association_attribute?(association['class_name'], association_name, attribute_name) end def is_association_attribute?(association_class, association_name, attribute_name) if association_name =~ /able$/ models.each do |class_name| if model_associations.is_association?(class_name, association_name.sub(/able$/, '')) || model_associations.is_association?(class_name, association_name.sub(/able$/, 's')) return true if model_attributes.is_attribute?(class_name, attribute_name) end end else model_attributes.is_attribute?(association_class, attribute_name) end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/use_parentheses_in_method_def_review.rb
lib/rails_best_practices/reviews/use_parentheses_in_method_def_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Check if method definition has parentheses around parameters. # # Review process: # check def node in all files, # if params node with values, but not wrapped by paren node, # then it should use parentheses around parameters. class UseParenthesesInMethodDefReview < Review interesting_nodes :def interesting_files ALL_FILES # check def node to see if parameters are wrapped by parentheses. add_callback :start_def do |node| if no_parentheses_around_parameters?(node) && has_parameters?(node) add_error('use parentheses around parameters in method definitions') end end protected def no_parentheses_around_parameters?(def_node) def_node[2][0] != :parent end def has_parameters?(def_node) def_node[2][0] == :params && !def_node[2][1..-1].compact.empty? end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/remove_unused_methods_in_helpers_review.rb
lib/rails_best_practices/reviews/remove_unused_methods_in_helpers_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Find out unused methods in helpers. # # Implementation: # # Review process: # remember all method calls in helpers. # if they are not called in views, helpers, or controllers # then they are unused methods in helpers. class RemoveUnusedMethodsInHelpersReview < Review include Moduleable include Callable include Exceptable interesting_files HELPER_FILES, VIEW_FILES, CONTROLLER_FILES def initialize(options = {}) super @helper_methods = Prepares.helper_methods self.class.interesting_files *Prepares.helpers.map(&:descendants) end # get all unused methods at the end of review process add_callback :after_check do @helper_methods.get_all_unused_methods.each do |method| next if excepted?(method) add_error "remove unused methods (#{method.class_name}##{method.method_name})", method.file, method.line_number end end protected def methods @helper_methods end def internal_except_methods ['*#url_for'] end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/use_before_filter_review.rb
lib/rails_best_practices/reviews/use_before_filter_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a controller file to make sure to use before_filter to remove duplicated first code # line_number in different action. # # See the best practice detailed here https://rails-bestpractices.com/posts/2010/07/24/use-before_filter/ # # Implementation: # # Review process: # check all first code line_number in method definitions (actions), # if they are duplicated, then they should be moved to before_filter. class UseBeforeFilterReview < Review interesting_nodes :class interesting_files CONTROLLER_FILES url 'https://rails-bestpractices.com/posts/2010/07/24/use-before_filter/' def initialize(options = {}) super() @customize_count = options['customize_count'] || 2 end # check class define node to see if there are method define nodes whose first code line_number are duplicated. # # it will check every def nodes in the class node until protected or private identification, # if there are defn nodes who have the same first code line_number, # then these duplicated first code line_numbers should be moved to before_filter. add_callback :start_class do |node| @first_sentences = {} node.body.statements.each do |statement_node| var_ref_or_vcall_included = %i[var_ref vcall].include?(statement_node.sexp_type) private_or_protected_included = %w[protected private].include?(statement_node.to_s) break if var_ref_or_vcall_included && private_or_protected_included remember_first_sentence(statement_node) if statement_node.sexp_type == :def end @first_sentences.each do |_first_sentence, def_nodes| next unless def_nodes.size > @customize_count add_error "use before_filter for #{def_nodes.map { |node| node.method_name.to_s }.join(',')}", node.file, def_nodes.map(&:line_number).join(',') end end private # check method define node, and remember the first sentence. def remember_first_sentence(node) first_sentence = node.body.statements.first return unless first_sentence first_sentence = first_sentence.remove_line_and_column unless first_sentence == s(:nil) @first_sentences[first_sentence] ||= [] @first_sentences[first_sentence] << node end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/use_observer_review.rb
lib/rails_best_practices/reviews/use_observer_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Make sure to use observer (sorry we only check the mailer deliver now). # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/24/use-observer/ # # TODO: we need a better solution, any suggestion? # # Implementation: # # Review process: # check all command nodes to see if they are callback definitions, like after_create, before_destroy, # if so, remember the callback methods. # # check all method define nodes to see # if the method is a callback method, # and there is a mailer deliver call, # then the method should be replaced by using observer. class UseObserverReview < Review interesting_nodes :def, :command interesting_files MODEL_FILES url 'https://rails-bestpractices.com/posts/2010/07/24/use-observer/' def initialize(options = {}) super @callbacks = [] end # check a command node. # # if it is a callback definition, # then remember its callback methods. add_callback :start_command do |node| remember_callback(node) end # check a method define node in prepare process. # # if it is callback method, # and there is a actionmailer deliver call in the method define node, # then it should be replaced by using observer. add_callback :start_def do |node| if callback_method?(node) && deliver_mailer?(node) add_error 'use observer' end end private # check a command node, if it is a callback definition, such as after_create, before_create, # then save the callback methods in @callbacks def remember_callback(node) if node.message.to_s =~ /^after_|^before_/ node.arguments.all.each do |argument| # ignore callback like after_create Comment.new @callbacks << argument.to_s if argument.sexp_type == :symbol_literal end end end # check a defn node to see if the method name exists in the @callbacks. def callback_method?(node) @callbacks.find { |callback| callback == node.method_name.to_s } end # check a def node to see if it contains a actionmailer deliver call. # # if the message of call node is deliver, # and the receiver of the call node is with receiver node who exists in @callbacks, # then the call node is actionmailer deliver call. def deliver_mailer?(node) node.grep_nodes(sexp_type: :call) do |child_node| if child_node.message.to_s == 'deliver' if child_node.receiver.sexp_type == :method_add_arg && mailers.include?(child_node.receiver[1].receiver.to_s) return true end end end false end def mailers @mailers ||= Prepares.mailers end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/use_say_with_time_in_migrations_review.rb
lib/rails_best_practices/reviews/use_say_with_time_in_migrations_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a migration file to make sure to use say or say_with_time for customized data changes # to produce a more readable output. # # See the best practice detials here https://rails-bestpractices.com/posts/2010/08/19/use-say-and-say_with_time-in-migrations-to-make-a-useful-migration-log/ # # Implementation: # # Review process: # check class method define nodes (self.up or self.down). # if there is a method call in the class method definition, # and the message of method call is not say, say_with_time and default migration methods # (such as add_column and create_table), then the method call should be wrapped by say or say_with_time. class UseSayWithTimeInMigrationsReview < Review interesting_nodes :defs interesting_files MIGRATION_FILES url 'https://rails-bestpractices.com/posts/2010/08/19/use-say-and-say_with_time-in-migrations-to-make-a-useful-migration-log/' WITH_SAY_METHODS = %w[say say_with_time].freeze # check a class method define node to see if there are method calls that need to be wrapped by say # or say_with_time. # # it will check the first block node, # if any method call whose message is not default migration methods in the block node, # then such method call should be wrapped by say or say_with_time add_callback :start_defs do |node| node.body.statements.each do |child_node| next if child_node.grep_nodes_count(sexp_type: %i[fcall command], message: WITH_SAY_METHODS) > 0 receiver_node = if child_node.sexp_type == :method_add_block child_node[1] elsif child_node.sexp_type == :method_add_arg child_node[1] else child_node end if receiver_node.sexp_type == :call add_error('use say with time in migrations', node.file, child_node.line_number) end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/check_destroy_return_value_review.rb
lib/rails_best_practices/reviews/check_destroy_return_value_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review all code to make sure we either check the return value of "destroy" # or use "destroy!" # # Review process: # Track which nodes are used by 'if', 'unless', '&&' nodes etc. as we pass them by. # Check all "save" calls to check the return value is used by a node we have visited. class CheckDestroyReturnValueReview < Review include Classable interesting_nodes :call, :command_call, :method_add_arg, :if, :ifop, :elsif, :unless, :if_mod, :unless_mod, :assign, :binary interesting_files ALL_FILES add_callback :start_if, :start_ifop, :start_elsif, :start_unless, :start_if_mod, :start_unless_mod do |node| @used_return_value_of = node.conditional_statement.all_conditions end add_callback :start_assign do |node| @used_return_value_of = node.right_value end # Consider anything used in an expression like "A or B" as used add_callback :start_binary do |node| if %w[&& || and or].include?(node[2].to_s) all_conditions = node.all_conditions # if our current binary is a subset of the @used_return_value_of # then don't overwrite it already_included = @used_return_value_of && (all_conditions - @used_return_value_of).empty? @used_return_value_of = node.all_conditions unless already_included end end def return_value_is_used?(node) return false unless @used_return_value_of (node == @used_return_value_of) || @used_return_value_of.include?(node) end def model_classnames @model_classnames ||= models.map(&:to_s) end add_callback :start_call, :start_command_call, :start_method_add_arg do |node| unless @already_checked == node message = node.message.to_s if message.eql? 'destroy' unless return_value_is_used? node add_error "check '#{message}' return value or use '#{message}!'" end end if node.sexp_type == :method_add_arg @already_checked = node[1] end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/remove_unused_methods_in_controllers_review.rb
lib/rails_best_practices/reviews/remove_unused_methods_in_controllers_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Find out unused methods in controllers. # # Implementation: # # Review process: # remember all method calls in controllers, # if they are not defined in routes, # and they are not called in controllers, # then they are the unused methods in controllers. class RemoveUnusedMethodsInControllersReview < Review include Classable include Moduleable include Callable include Exceptable include InheritedResourcesable interesting_nodes :class, :command, :method_add_arg, :assign interesting_files CONTROLLER_FILES, VIEW_FILES, HELPER_FILES INHERITED_RESOURCES_METHODS = %w[resource collection begin_of_association_chain build_resource].freeze def initialize(options = {}) super @controller_methods = Prepares.controller_methods @routes = Prepares.routes @inherited_resources = false end add_callback :start_class do |_node| @current_controller_name = @klass.to_s end # mark custom inherited_resources methods as used. add_callback :end_class do |_node| if @inherited_resources INHERITED_RESOURCES_METHODS.each do |method| call_method(method, @current_controller_name) end end end # skip render and around_filter nodes for start_command callbacks. def skip_command_callback_nodes %w[render_cell render around_filter] end # mark corresponding action as used for cells' render and render_call. add_callback :start_command, :start_method_add_arg do |node| case node.message.to_s when 'render_cell' controller_name, action_name, = *node.arguments.all.map(&:to_s) call_method(action_name, "#{controller_name}_cell".classify) when 'render' first_argument = node.arguments.all.first if first_argument.present? && first_argument.hash_value('state').present? action_name = first_argument.hash_value('state').to_s call_method(action_name, current_class_name) end when 'around_filter', 'around_action' node.arguments.all.each { |argument| mark_used(argument) } when 'layout' first_argument = node.arguments.all.first if first_argument.sexp_type == :symbol_literal mark_used(first_argument) end when 'helper_method' node.arguments.all.each { |argument| mark_publicize(argument.to_s) } when 'delegate' last_argument = node.arguments.all.last if last_argument.sexp_type == :bare_assoc_hash && last_argument.hash_value('to').to_s == 'controller' controller_name = current_module_name.sub('Helper', 'Controller') node.arguments.all[0..-2].each { |method| mark_publicize(method.to_s, controller_name) } end else # nothing end end # mark assignment as used, like current_user = @user add_callback :start_assign do |node| if node.left_value.sexp_type == :var_field call_method "#{node.left_value}=", current_class_name end end # get all unused methods at the end of review process. add_callback :after_check do @routes.each do |route| if route.action_name == '*' action_names = @controller_methods.get_methods(route.controller_name_with_namespaces).map(&:method_name) action_names.each { |action_name| call_method(action_name, route.controller_name_with_namespaces) } else call_method(route.action_name, route.controller_name_with_namespaces) end end @controller_methods.get_all_unused_methods.each do |method| next if excepted?(method) add_error "remove unused methods (#{method.class_name}##{method.method_name})", method.file, method.line_number end end protected def methods @controller_methods end def internal_except_methods %w[rescue_action default_url_options].map { |method_name| "*\##{method_name}" } + %w[Devise::OmniauthCallbacksController].map { |controller_name| "#{controller_name}#*" } end def mark_publicize(method_name, class_name = current_class_name) @controller_methods.mark_publicize(class_name, method_name) @controller_methods.mark_parent_class_methods_publicize(class_name, method_name) end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/restrict_auto_generated_routes_review.rb
lib/rails_best_practices/reviews/restrict_auto_generated_routes_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a route file to make sure all auto-generated routes have corresponding actions in controller. # # See the best practice details here https://rails-bestpractices.com/posts/2011/08/19/restrict-auto-generated-routes/ # # Implementation: # # Review process: # check all resources and resource method calls, # compare the generated routes and corresponding actions in controller, # if there is a route generated, but there is not action in that controller, # then you should restrict your routes. class RestrictAutoGeneratedRoutesReview < Review interesting_nodes :command, :command_call, :method_add_block interesting_files ROUTE_FILES url 'https://rails-bestpractices.com/posts/2011/08/19/restrict-auto-generated-routes/' def resource_methods if Prepares.configs['config.api_only'] %w[show create update destroy] else %w[show new create edit update destroy] end end def resources_methods resource_methods + ['index'] end def initialize(options = {}) super(options) @namespaces = [] @resource_controllers = [] end # check if the generated routes have the corresponding actions in controller for rails routes. add_callback :start_command, :start_command_call do |node| if node.message.to_s == 'resources' if (mod = module_option(node)) @namespaces << mod end check_resources(node) @resource_controllers << node.arguments.all.first.to_s elsif node.message.to_s == 'resource' check_resource(node) @resource_controllers << node.arguments.all.first.to_s end end add_callback :end_command do |node| if node.message.to_s == 'resources' @resource_controllers.pop @namespaces.pop if module_option(node) elsif node.message.to_s == 'resource' @resource_controllers.pop end end # remember the namespace. add_callback :start_method_add_block do |node| case node.message.to_s when 'namespace' @namespaces << node.arguments.all.first.to_s if check_method_add_block?(node) when 'resources', 'resource' @resource_controllers << node.arguments.all.first.to_s if check_method_add_block?(node) when 'scope' if check_method_add_block?(node) && (mod = module_option(node)) @namespaces << mod end end end # end of namespace call. add_callback :end_method_add_block do |node| if check_method_add_block?(node) case node.message.to_s when 'namespace' @namespaces.pop when 'resources', 'resource' @resource_controllers.pop when 'scope' if check_method_add_block?(node) && module_option(node) @namespaces.pop end end end end def check_method_add_block?(node) node[1].sexp_type == :command || (node[1].sexp_type == :command_call && node.receiver.to_s != 'map') end private # check resources call, if the routes generated by resources does not exist in the controller. def check_resources(node) _check(node, resources_methods) end # check resource call, if the routes generated by resources does not exist in the controller. def check_resource(node) _check(node, resource_methods) end # get the controller name. def controller_name(node) if option_with_hash(node) option_node = node.arguments.all[1] name = if hash_key_exist?(option_node, 'controller') option_node.hash_value('controller').to_s else node.arguments.all.first.to_s.gsub('::', '').tableize end else name = node.arguments.all.first.to_s.gsub('::', '').tableize end namespaced_class_name(name) end # get the class name with namespace. def namespaced_class_name(name) class_name = "#{name.split('/').map(&:camelize).join('::')}Controller" if @namespaces.empty? class_name else @namespaces.map { |namespace| "#{namespace.camelize}::" }.join('') + class_name end end def _check(node, methods) controller_name = controller_name(node) return unless Prepares.controllers.include? controller_name _methods = _methods(node, methods) unless _methods.all? { |meth| Prepares.controller_methods.has_method?(controller_name, meth) } prepared_method_names = Prepares.controller_methods.get_methods(controller_name).map(&:method_name) only_methods = (_methods & prepared_method_names).map { |meth| ":#{meth}" } routes_message = if only_methods.size > 3 "except: [#{(methods.map { |meth| ':' + meth } - only_methods).join(', ')}]" else "only: [#{only_methods.join(', ')}]" end add_error "restrict auto-generated routes #{friendly_route_name(node)} (#{routes_message})" end end def _methods(node, methods) if option_with_hash(node) option_node = node.arguments.all[1] if hash_key_exist?(option_node, 'only') option_node.hash_value('only').to_s == 'none' ? [] : Array(option_node.hash_value('only').to_object) elsif hash_key_exist?(option_node, 'except') if option_node.hash_value('except').to_s == 'all' [] else (methods - Array(option_node.hash_value('except').to_object)) end else methods end else methods end end def module_option(node) option_node = node.arguments[1].last if option_node && option_node.sexp_type == :bare_assoc_hash && hash_key_exist?(option_node, 'module') option_node.hash_value('module').to_s end end def option_with_hash(node) node.arguments.all.size > 1 && node.arguments.all[1].sexp_type == :bare_assoc_hash end def hash_key_exist?(node, key) node.hash_keys&.include?(key) end def friendly_route_name(node) if @resource_controllers.last == node.arguments.to_s [@namespaces.join('/'), @resource_controllers.join('/')].delete_if(&:blank?).join('/') else [@namespaces.join('/'), @resource_controllers.join('/'), node.arguments.to_s].delete_if(&:blank?).join('/') end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/keep_finders_on_their_own_model_review.rb
lib/rails_best_practices/reviews/keep_finders_on_their_own_model_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review model files to make sure finders are on their own model. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/23/keep-finders-on-their-own-model/ # # Implementation: # # Review process: # check all call nodes in model files. # # if the call node is a finder (find, all, first or last), # and the it calls the other model, # and there is a hash argument for finder, # then it should keep finders on its own model. class KeepFindersOnTheirOwnModelReview < Review interesting_nodes :method_add_arg interesting_files MODEL_FILES url 'https://rails-bestpractices.com/posts/2010/07/23/keep-finders-on-their-own-model/' FINDERS = %w[find all first last].freeze # check all the call nodes to see if there is a finder for other model. # # if the call node is # # 1. the message of call node is one of the find, all, first or last # 2. the receiver of call node is also a call node (it's the other model) # 3. the any of its arguments is a hash (complex finder) # # then it should keep finders on its own model. add_callback :start_method_add_arg do |node| add_error 'keep finders on their own model' if other_finder?(node) end private # check if the call node is the finder of other model. # # the message of the node should be one of find, all, first or last, # and the receiver of the node should be with message :call (this is the other model), # and any of its arguments is a hash, # then it is the finder of other model. def other_finder?(node) FINDERS.include?(node[1].message.to_s) && node[1].receiver.sexp_type == :call && node.arguments.grep_nodes_count(sexp_type: :bare_assoc_hash) > 0 end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/simplify_render_in_views_review.rb
lib/rails_best_practices/reviews/simplify_render_in_views_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a view file to make sure using simplified syntax for render. # # See the best practice details here https://rails-bestpractices.com/posts/2010/12/04/simplify-render-in-views/ # # Implementation: # # Review process: # check all render method commands in view files, # if there is a key 'partial' in the argument, then they should be replaced by simplified syntax. class SimplifyRenderInViewsReview < Review interesting_nodes :command interesting_files VIEW_FILES url 'https://rails-bestpractices.com/posts/2010/12/04/simplify-render-in-views/' VALID_KEYS = %w[object collection locals].freeze # check command node in view file, # if its message is render and the arguments contain a key partial, # then it should be replaced by simplified syntax. add_callback :start_command do |node| if node.message.to_s == 'render' hash_node = node.arguments.all.first if hash_node && hash_node.sexp_type == :bare_assoc_hash && include_partial?(hash_node) && valid_hash?(hash_node) add_error 'simplify render in views' end end end protected def include_partial?(hash_node) hash_node.hash_keys.include?('partial') && !hash_node.hash_value('partial').to_s.include?('/') end def valid_hash?(hash_node) keys = hash_node.hash_keys keys.delete('partial') (keys - VALID_KEYS).empty? end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/use_scope_access_review.rb
lib/rails_best_practices/reviews/use_scope_access_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a controller to make sure to use scope access instead of manually checking current_user and redirect. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/20/use-scope-access/ # # Implementation: # # Review process: # check all if nodes to see # # if they are compared with current_user or current_user.id, # and there is redirect_to method call in if block body, # then it should be replaced by using scope access. class UseScopeAccessReview < Review interesting_nodes :if, :unless, :elsif, :ifop, :if_mod, :unless_mod interesting_files CONTROLLER_FILES url 'https://rails-bestpractices.com/posts/2010/07/20/use-scope-access/' # check if node. # # if it is a method call compared with current_user or current_user.id, # and there is a redirect_to method call in the block body, # then it should be replaced by using scope access. add_callback :start_if, :start_unless, :start_elsif, :start_ifop, :start_if_mod, :start_unless_mod do |node| add_error 'use scope access' if current_user_redirect?(node) end private # check a if node to see # # if the conditional statement is compared with current_user or current_user.id, # and there is a redirect_to method call in the block body, # then it should be replaced by using scope access. def current_user_redirect?(node) all_conditions = if node.conditional_statement == node.conditional_statement.all_conditions [node.conditional_statement] else node.conditional_statement.all_conditions end results = all_conditions.map do |condition_node| ['==', '!='].include?(condition_node.message.to_s) && (current_user?(condition_node.argument) || current_user?(condition_node.receiver)) end results.any? { |result| result == true } && node.body.grep_node(message: 'redirect_to') end # check a call node to see if it uses current_user, or current_user.id. def current_user?(node) node.to_s == 'current_user' || (node.receiver.to_s == 'current_user' && node.message.to_s == 'id') end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/use_query_attribute_review.rb
lib/rails_best_practices/reviews/use_query_attribute_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Make sure to use query attribute instead of nil?, blank? and present?. # # See the best practice details here https://rails-bestpractices.com/posts/2010/10/03/use-query-attribute/ # # Implementation: # # Review process: # check all method calls within conditional statements, like @user.login.nil? # if their receivers are one of the model names # and their messages of first call are not pluralize and not in any of the association names # and their messages of second call are one of nil?, blank?, present?, or they are == "" # then you can use query attribute instead. class UseQueryAttributeReview < Review interesting_nodes :if, :unless, :elsif, :ifop, :if_mod, :unless_mod interesting_files ALL_FILES url 'https://rails-bestpractices.com/posts/2010/10/03/use-query-attribute/' QUERY_METHODS = %w[nil? blank? present?].freeze # check if node to see whose conditional statement nodes contain nodes that can use query attribute instead. # # it will check every call nodes in the if nodes. If the call node is # # 1. two method calls, like @user.login.nil? # 2. the receiver is one of the model names # 3. the message of first call is the model's attribute, # the message is not in any of associations name and is not pluralize # 4. the message of second call is one of nil?, blank? or present? or # the message is == and the argument is "" # # then the call node can use query attribute instead. add_callback :start_if, :start_unless, :start_elsif, :start_ifop, :start_if_mod, :start_unless_mod do |node| all_conditions = if node.conditional_statement == node.conditional_statement.all_conditions [node.conditional_statement] else node.conditional_statement.all_conditions end all_conditions.each do |condition_node| next unless query_attribute_node = query_attribute_node(condition_node) receiver_node = query_attribute_node.receiver add_error "use query attribute (#{receiver_node.receiver}.#{receiver_node.message}?)", node.file, query_attribute_node.line_number end end private # recursively check conditional statement nodes to see if there is a call node that may be # possible query attribute. def query_attribute_node(conditional_statement_node) case conditional_statement_node.sexp_type when :and, :or node = query_attribute_node(conditional_statement_node[1]) || query_attribute_node(conditional_statement_node[2]) node.file = conditional_statement_code.file return node when :not node = query_attribute_node(conditional_statement_node[1]) node.file = conditional_statement_node.file when :call return conditional_statement_node if possible_query_attribute?(conditional_statement_node) when :binary return conditional_statement_node if possible_query_attribute?(conditional_statement_node) end nil end # check if the node may use query attribute instead. # # if the node contains two method calls, e.g. @user.login.nil? # # for the first call, the receiver should be one of the class names and # the message should be one of the attribute name. # # for the second call, the message should be one of nil?, blank? or present? or # it is compared with an empty string. # # the node that may use query attribute. def possible_query_attribute?(node) return false unless node.receiver.sexp_type == :call variable_node = variable(node) message_node = node.grep_node(receiver: variable_node.to_s).message is_model?(variable_node) && model_attribute?(variable_node, message_node.to_s) && (QUERY_METHODS.include?(node.message.to_s) || compare_with_empty_string?(node)) end # check if the receiver is one of the models. def is_model?(variable_node) return false if variable_node.const? class_name = variable_node.to_s.sub(/^@/, '').classify models.include?(class_name) end # check if the receiver and message is one of the model's attribute. # the receiver should match one of the class model name, and the message should match one of attribute name. def model_attribute?(variable_node, message) class_name = variable_node.to_s.sub(/^@/, '').classify attribute_type = model_attributes.get_attribute_type(class_name, message) attribute_type && !%w[integer float].include?(attribute_type) end # check if the node is with node type :binary, node message :== and node argument is empty string. def compare_with_empty_string?(node) node.sexp_type == :binary && ['==', '!='].include?(node.message.to_s) && s(:string_literal, s(:string_content)) == node.argument end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/add_model_virtual_attribute_review.rb
lib/rails_best_practices/reviews/add_model_virtual_attribute_review.rb
# frozen_string_literal: true require_rel 'review' module RailsBestPractices module Reviews # Make sure to add a model virual attribute to simplify model creation. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/21/add-model-virtual-attribute/ # # Implementation: # # Review process: # check method define nodes in all controller files, # if there are more than one [] method calls with the same receiver and arguments, # but assigned to one model's different attribute. # and after these method calls, there is a save method call for that model, # then the model needs to add a virtual attribute. class AddModelVirtualAttributeReview < Review interesting_nodes :def interesting_files CONTROLLER_FILES url 'https://rails-bestpractices.com/posts/2010/07/21/add-model-virtual-attribute/' # check method define nodes to see if there are some attribute assignments that can use model virtual attribute instead in review process. # # it will check every attribute assignment nodes and call node of message :save or :save!, if # # 1. there are more than one arguments who contain array reference node in the right value of assignment nodes, # 2. the messages of attribute assignment nodes housld be different (:first_name= , :last_name=) # 3. the argument of call nodes with message :[] should be same (:full_name) # 4. there should be a call node with message :save or :save! after attribute assignment nodes # 5. and the receiver of save or save! call node should be the same with the receiver of attribute assignment nodes # # then the attribute assignment nodes can add model virtual attribute instead. add_callback :start_def do |node| @assignments = {} node.recursive_children do |child| case child.sexp_type when :assign assign(child) when :call call_assignment(child) end end end private # check an attribute assignment node, if there is a array reference node in the right value of assignment node, # then remember this attribute assignment. def assign(node) left_value = node.left_value right_value = node.right_value return unless left_value.sexp_type == :field && right_value.sexp_type == :call aref_node = right_value.grep_node(sexp_type: :aref) if aref_node assignments(left_value.receiver.to_s) << { message: left_value.message.to_s, arguments: aref_node.to_s } end end # check a call node with message "save" or "save!", # if there exists an attribute assignment for the receiver of this call node, # and if the arguments of this attribute assignments has duplicated entries (different message and same arguments), # then this node needs to add a virtual attribute. def call_assignment(node) if ['save', 'save!'].include? node.message.to_s receiver = node.receiver.to_s add_error "add model virtual attribute (for #{receiver})" if params_dup?( assignments(receiver).collect { |h| h[:arguments] } ) end end # if the nodes are duplicated. def params_dup?(nodes) return false if nodes.nil? !dups(nodes).empty? end # get the assignments of receiver. def assignments(receiver) @assignments[receiver] ||= [] end # Get the duplicate entries from an Enumerable. # # @return [Enumerable] the duplicate entries. def dups(nodes) nodes.each_with_object({}) { |v, h| h[v] = h[v].to_i + 1 }.reject { |_k, v| v == 1 }.keys end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/simplify_render_in_controllers_review.rb
lib/rails_best_practices/reviews/simplify_render_in_controllers_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a controller file to make sure using simplified syntax for render. # # See the best practice details here https://rails-bestpractices.com/posts/2010/12/12/simplify-render-in-controllers/ # # Implementation: # # Review process: # check all render method commands in controller files, # if there is a key 'action', 'template' or 'file' in the argument, # then they should be replaced by simplified syntax. class SimplifyRenderInControllersReview < Review interesting_nodes :command interesting_files CONTROLLER_FILES url 'https://rails-bestpractices.com/posts/2010/12/12/simplify-render-in-controllers/' # check command node in the controller file, # if its message is render and the arguments contain a key action, template or file, # then it should be replaced by simplified syntax. add_callback :start_command do |node| if node.message.to_s == 'render' keys = node.arguments.all.first.hash_keys if keys && keys.size == 1 && (keys.include?('action') || keys.include?('template') || keys.include?('file')) add_error 'simplify render in controllers' end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/not_use_default_route_review.rb
lib/rails_best_practices/reviews/not_use_default_route_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review config/routes file to make sure not use default route that rails generated. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/22/not-use-default-route-if-you-use-restful-design/ # # Implementation: # # Review process: # check all method command_call or command node to see if it is the same as rails default route. # # map.connect ':controller/:action/:id' # map.connect ':controller/:action/:id.:format' # # or # # match ':controller(/:action(/:id(.:format)))' class NotUseDefaultRouteReview < Review interesting_nodes :command_call, :command interesting_files ROUTE_FILES url 'https://rails-bestpractices.com/posts/2010/07/22/not-use-default-route-if-you-use-restful-design/' # check all command nodes add_callback :start_command do |node| if node.message.to_s == 'match' && node.arguments.all.first.to_s == ':controller(/:action(/:id(.:format)))' add_error 'not use default route' end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/default_scope_is_evil_review.rb
lib/rails_best_practices/reviews/default_scope_is_evil_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review model files to make sure not use default_scope # # See the best practice details here https://rails-bestpractices.com/posts/2013/06/15/default_scope-is-evil/ # # Implementation: # # Review process: # check all command node to see if its message is default_scope class DefaultScopeIsEvilReview < Review interesting_nodes :command interesting_files MODEL_FILES url 'https://rails-bestpractices.com/posts/2013/06/15/default_scope-is-evil/' # check all command nodes' message add_callback :start_command do |node| if node.message.to_s == 'default_scope' add_error 'default_scope is evil' end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/protect_mass_assignment_review.rb
lib/rails_best_practices/reviews/protect_mass_assignment_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review model files to make sure to use attr_accessible, attr_protected or strong_parameters to protect mass assignment. # # See the best practices details here https://rails-bestpractices.com/posts/2012/03/06/protect-mass-assignment/ # # Implmentation: # # Review process: # check nodes to see if there is a command with message attr_accessible or attr_protected, # or include ActiveModel::ForbiddenAttributesProtection. class ProtectMassAssignmentReview < Review interesting_files MODEL_FILES interesting_nodes :class, :command, :var_ref, :vcall, :fcall url 'https://rails-bestpractices.com/posts/2012/03/06/protect-mass-assignment/' # we treat it as mass assignment by default. add_callback :start_class do |_node| @mass_assignement = true check_activerecord_version check_whitelist_attributes_config check_include_forbidden_attributes_protection_config end # check if it is ActiveRecord::Base subclass and # if it sets config.active_record.whitelist_attributes to true. add_callback :end_class do |node| check_active_record(node) add_error 'protect mass assignment' if @mass_assignement end # check if it is attr_accessible or attr_protected command, # if it uses strong_parameters, # and if it uses devise. add_callback :start_command do |node| check_rails_builtin(node) check_strong_parameters(node) check_devise(node) end # check if it is attr_accessible, attr_protected, acts_as_authlogic without parameters. add_callback :start_var_ref, :start_vcall do |node| check_rails_builtin(node) check_authlogic(node) end # check if it uses authlogic. add_callback :start_fcall do |node| check_authlogic(node) end private def check_activerecord_version if Prepares.gems.gem_version('activerecord').to_i > 3 @mass_assignement = false end end def check_whitelist_attributes_config if Prepares.configs['config.active_record.whitelist_attributes'] == 'true' @whitelist_attributes = true end end def check_include_forbidden_attributes_protection_config if Prepares.configs['railsbp.include_forbidden_attributes_protection'] == 'true' @mass_assignement = false end end def check_rails_builtin(node) if @whitelist_attributes || [node.to_s, node.message.to_s].any? { |str| %w[attr_accessible attr_protected].include? str } @mass_assignement = false end end def check_strong_parameters(command_node) if command_node.message.to_s == 'include' && command_node.arguments.all.first.to_s == 'ActiveModel::ForbiddenAttributesProtection' @mass_assignement = false end end def check_devise(command_node) if command_node.message.to_s == 'devise' @mass_assignement = false end end def check_authlogic(node) if [node.to_s, node.message.to_s].include? 'acts_as_authentic' @mass_assignement = false end end def check_active_record(const_path_ref_node) if const_path_ref_node.base_class.to_s != 'ActiveRecord::Base' @mass_assignement = false end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/overuse_route_customizations_review.rb
lib/rails_best_practices/reviews/overuse_route_customizations_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review config/routes.rb file to make sure there are no overuse route customizations. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/22/overuse-route-customizations/ # # Implementation: # # Review process: # # check all method_add_block nodes in route file. # if the receiver of method_add_block node is with message resources, # and in the block body of method_add_block node, there are more than @customize_count command nodes, # whose message is get, post, update or delete, # then these custom routes are overuse. class OveruseRouteCustomizationsReview < Review interesting_nodes :command_call, :method_add_block interesting_files ROUTE_FILES url 'https://rails-bestpractices.com/posts/2010/07/22/overuse-route-customizations/' VERBS = %w[get post update delete].freeze def initialize(options = {}) super(options) @customize_count = options['customize_count'] || 3 end # check method_add_block node to see if the count of member and collection custom routes is more than @customize_count defined. # # if the receiver of method_add_block node is with message "resources", # and in the block body of method_add_block node, there are more than @customize_count call nodes, # whose message is :get, :post, :update or :delete, # then they are overuse route customizations. add_callback :start_method_add_block do |node| if member_and_collection_count_for_rails3(node) > @customize_count add_error "overuse route customizations (customize_count > #{@customize_count})", node.file, node.line_number end end private # check method_add_block node to calculate the count of member and collection custom routes. # # if its receiver is with message "resources", # then calculate the count of call nodes, whose message is get, post, update or delete, # it is just the count of member and collection custom routes. def member_and_collection_count_for_rails3(node) node[1].message.to_s == 'resources' ? node.grep_nodes_count(sexp_type: :command, message: VERBS) : 0 end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/remove_unused_methods_in_models_review.rb
lib/rails_best_practices/reviews/remove_unused_methods_in_models_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Find out unused methods in models. # # Implemenation: # # Review process: # remember all method calls, # at end, check if all defined methods are called, # if not, non called methods are unused. class RemoveUnusedMethodsInModelsReview < Review include Classable include Callable include Exceptable interesting_nodes :command, :command_call, :method_add_arg interesting_files ALL_FILES def initialize(options = {}) super @model_methods = Prepares.model_methods end # skip scope and validate nodes for start_command callbacks. def skip_command_callback_nodes %w[named_scope scope validate validate_on_create validate_on_update] end # mark validate methods as used. # mark key method and value method for collection_select and grouped_collection_select. add_callback :start_command do |node| arguments = node.arguments.all case node.message.to_s when 'validate', 'validate_on_create', 'validate_on_update' arguments.each { |argument| mark_used(argument) } when 'collection_select' mark_used(arguments[3]) mark_used(arguments[4]) when 'grouped_collection_select' mark_used(arguments[3]) mark_used(arguments[4]) mark_used(arguments[5]) mark_used(arguments[6]) end end # mark key method and value method for collection_select and grouped_collection_select. add_callback :start_command_call do |node| arguments = node.arguments.all case node.message.to_s when 'collection_select' mark_used(arguments[2]) mark_used(arguments[3]) when 'grouped_collection_select' mark_used(arguments[2]) mark_used(arguments[3]) mark_used(arguments[4]) mark_used(arguments[5]) end end # mark key method and value method for options_from_collection_for_select and # option_groups_from_collection_for_select. add_callback :start_method_add_arg do |node| arguments = node.arguments.all case node.message.to_s when 'options_from_collection_for_select' mark_used(arguments[1]) mark_used(arguments[2]) when 'option_groups_from_collection_for_select' mark_used(arguments[1]) mark_used(arguments[2]) mark_used(arguments[3]) mark_used(arguments[4]) end end # get all unused methods at the end of review process. add_callback :after_check do @model_methods.get_all_unused_methods.each do |method| next unless !excepted?(method) && method.method_name !~ /=$/ add_error "remove unused methods (#{method.class_name}##{method.method_name})", method.file, method.line_number end end protected def methods @model_methods end def internal_except_methods %w[ initialize validate validate_each validate_on_create validate_on_update human_attribute_name assign_attributes attributes attribute to_xml to_json as_json to_param before_save before_create before_update before_destroy after_save after_create after_update after_destroy after_find after_initialize method_missing table_name module_prefix ].map { |method_name| "*\##{method_name}" } end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/move_code_into_model_review.rb
lib/rails_best_practices/reviews/move_code_into_model_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a view file to make sure there is no complex logic call for model. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/24/move-code-into-model/ # # Implementation: # # Review process: # check if, unless, elsif there are multiple method calls or attribute assignments apply to one receiver, # and the receiver is a variable, then they should be moved into model. class MoveCodeIntoModelReview < Review interesting_nodes :if, :unless, :elsif, :ifop, :if_mod, :unless_mod interesting_files VIEW_FILES url 'https://rails-bestpractices.com/posts/2010/07/24/move-code-into-model/' def initialize(options = {}) super(options) @use_count = options['use_count'] || 2 end # check if node to see whose conditional statementnodes contain multiple call nodes with same receiver who is a variable. # # it will check every call and assignment nodes in the conditional statement nodes. # # if there are multiple call and assignment nodes who have the same receiver, # and the receiver is a variable, then the conditional statement nodes should be moved into model. add_callback :start_if, :start_unless, :start_elsif, :start_ifop, :start_if_mod, :start_unless_mod do |node| node.conditional_statement.grep_nodes(sexp_type: :call) { |child_node| remember_variable_use_count(child_node) } variable_use_count.each do |variable_node, count| add_error "move code into model (#{variable_node} use_count > #{@use_count})" if count > @use_count end reset_variable_use_count end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/move_finder_to_named_scope_review.rb
lib/rails_best_practices/reviews/move_finder_to_named_scope_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review a controller file to make sure there are no complex finder. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/14/move-finder-to-named_scope/ # # Implementation: # # Review process: # check all method method_add_arg nodes in controller files. # if there is any call node with message find, all, first or last, # and it has a hash argument, # then it is a complex finder, and should be moved to model's named scope. class MoveFinderToNamedScopeReview < Review interesting_nodes :method_add_arg interesting_files CONTROLLER_FILES url 'https://rails-bestpractices.com/posts/2010/07/14/move-finder-to-named_scope/' FINDERS = %w[find all first last].freeze # check method_add_ag node if its message is one of find, all, first or last, # and it has a hash argument, # then the call node is the finder that should be moved to model's named_scope. add_callback :start_method_add_arg do |node| add_error 'move finder to named_scope' if finder?(node) end private # check if the method_add_arg node is a finder. # # if the receiver of method_add_arg node is a constant, # and the message of call method_add_arg is one of find, all, first or last, # and any of its arguments is a hash, # then it is a finder. def finder?(node) FINDERS.include?(node[1].message.to_s) && node[1].sexp_type == :call && node.arguments.grep_nodes_count(sexp_type: :bare_assoc_hash) > 0 end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/always_add_db_index_review.rb
lib/rails_best_practices/reviews/always_add_db_index_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review db/schema.rb file to make sure every reference key has a database index. # # See the best practice details here https://rails-bestpractices.com/posts/2010/07/24/always-add-db-index/ # # Implementation: # # Review process: # only check the command and command_calls nodes and at the end of review process, # if the receiver of command node is "create_table", then remember the table names # if the receiver of command_call node is "integer" or "string" or "bigint" and suffix with _id, then remember it as foreign key # if the receiver of command_call node is "string", the name of it is _type suffixed and there is an integer or string column _id suffixed, then remember it as polymorphic foreign key # if the receiver of command_call node is remembered as foreign key and it have argument non-false "index", then remember the index columns # if the receiver of command node is "add_index", then remember the index columns # after all of these, at the end of review process # # ActiveRecord::Schema.define(version: 20101201111111) do # ...... # end # # if there are any foreign keys not existed in index columns, # then the foreign keys should add db index. class AlwaysAddDbIndexReview < Review interesting_nodes :command, :command_call interesting_files SCHEMA_FILE url 'https://rails-bestpractices.com/posts/2010/07/24/always-add-db-index/' def initialize(options = {}) super(options) @index_columns = {} @foreign_keys = {} @table_nodes = {} end # check command_call node. # # if the message of command_call node is "create_table", then remember the table name. # if the message of command_call node is "add_index", then remember it as index columns. add_callback :start_command_call do |node| if %w[integer string bigint].include? node.message.to_s remember_foreign_key_columns(node) elsif node.message.to_s == 'index' remember_index_columns_inside_table(node) end end # check command node. # # if the message of command node is "integer", # then remember it as a foreign key of last create table name. # # if the message of command node is "type" and the name of argument is _type suffixed, # then remember it with _id suffixed column as polymorphic foreign key. add_callback :start_command do |node| case node.message.to_s when 'create_table' remember_table_nodes(node) when 'add_index' remember_index_columns_outside_table(node) end end # check at the end of review process. # # compare foreign keys and index columns, # if there are any foreign keys not existed in index columns, # then we should add db index for that foreign keys. add_callback :after_check do remove_table_not_exist_foreign_keys remove_only_type_foreign_keys combine_polymorphic_foreign_keys @foreign_keys.each do |table, foreign_key| table_node = @table_nodes[table] foreign_key.each do |column| next unless not_indexed?(table, column) add_error "always add db index (#{table} => [#{Array(column).join(', ')}])", table_node.file, table_node.line_number end end end private # remember the node as index columns, when used outside a table # block, i.e. # add_index :table_name, :column_name def remember_index_columns_outside_table(node) table_name = node.arguments.all.first.to_s index_column = node.arguments.all[1].to_object @index_columns[table_name] ||= [] @index_columns[table_name] << index_column end # remember the node as index columns, when used inside a table # block, i.e. # t.index [:column_name, ...] def remember_index_columns_inside_table(node) table_name = @table_name index_column = node.arguments.all.first.to_object @index_columns[table_name] ||= [] @index_columns[table_name] << index_column end # remember table nodes def remember_table_nodes(node) @table_name = node.arguments.all.first.to_s @table_nodes[@table_name] = node end # remember foreign key columns def remember_foreign_key_columns(node) table_name = @table_name foreign_key_column = node.arguments.all.first.to_s @foreign_keys[table_name] ||= [] if foreign_key_column =~ /(.*?)_id$/ @foreign_keys[table_name] << if @foreign_keys[table_name].delete("#{Regexp.last_match(1)}_type") ["#{Regexp.last_match(1)}_id", "#{Regexp.last_match(1)}_type"] else foreign_key_column end foreign_id_column = foreign_key_column elsif foreign_key_column =~ /(.*?)_type$/ @foreign_keys[table_name] << if @foreign_keys[table_name].delete("#{Regexp.last_match(1)}_id") ["#{Regexp.last_match(1)}_id", "#{Regexp.last_match(1)}_type"] else foreign_key_column end foreign_id_column = "#{Regexp.last_match(1)}_id" end if foreign_id_column index_node = node.arguments.all.last.hash_value('index') if index_node.present? && (index_node.to_s != 'false') @index_columns[table_name] ||= [] @index_columns[table_name] << foreign_id_column end end end # remove the non foreign keys without corresponding tables. def remove_table_not_exist_foreign_keys @foreign_keys.each do |table, foreign_keys| foreign_keys.delete_if do |key| if key.is_a?(String) && key =~ /_id$/ class_name = Prepares.model_associations.get_association_class_name(table, key[0..-4]) class_name ? !@table_nodes[class_name.gsub('::', '').tableize] : !@table_nodes[key[0..-4].pluralize] end end end end # remove the non foreign keys with only _type column. def remove_only_type_foreign_keys @foreign_keys.each do |_table, foreign_keys| foreign_keys.delete_if { |key| key.is_a?(String) && key =~ /_type$/ } end end # combine polymorphic foreign keys, e.g. # [tagger_id], [tagger_type] => [tagger_id, tagger_type] def combine_polymorphic_foreign_keys @index_columns.each do |_table, foreign_keys| foreign_id_keys = foreign_keys.select { |key| key.size == 1 && key.first =~ /_id/ } foreign_type_keys = foreign_keys.select { |key| key.size == 1 && key.first =~ /_type/ } foreign_id_keys.each do |id_key| next unless type_key = foreign_type_keys.detect { |type_key| type_key.first == id_key.first.sub(/_id/, '') + '_type' } foreign_keys.delete(id_key) foreign_keys.delete(type_key) foreign_keys << id_key + type_key end end end # check if the table's column is indexed. def not_indexed?(table, column) index_columns = @index_columns[table] !index_columns || index_columns.none? { |e| greater_than_or_equal(Array(e), Array(column)) } end # check if more_array is greater than less_array or equal to less_array. def greater_than_or_equal(more_array, less_array) more_size = more_array.size less_size = less_array.size (more_array - less_array).size == more_size - less_size end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/not_use_time_ago_in_words_review.rb
lib/rails_best_practices/reviews/not_use_time_ago_in_words_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review view and helper files to make sure not use time_ago_in_words or distance_of_time_in_words_to_now. # # See the best practice details here https://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/ # # Implementation: # # Review process: # check all fcall node to see if its message is time_ago_in_words and distance_of_time_in_words_to_now class NotUseTimeAgoInWordsReview < Review interesting_nodes :fcall interesting_files VIEW_FILES, HELPER_FILES url 'https://rails-bestpractices.com/posts/2012/02/10/not-use-time_ago_in_words/' # check fcall node to see if its message is time_ago_in_words or distance_of_time_in_words_to_now add_callback :start_fcall do |node| if node.message.to_s == 'time_ago_in_words' || node.message.to_s == 'distance_of_time_in_words_to_now' add_error 'not use time_ago_in_words' end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/reviews/dry_bundler_in_capistrano_review.rb
lib/rails_best_practices/reviews/dry_bundler_in_capistrano_review.rb
# frozen_string_literal: true module RailsBestPractices module Reviews # Review config/deploy.rb file to make sure using the bundler's capistrano recipe. # # See the best practice details here https://rails-bestpractices.com/posts/2010/09/02/dry-bundler-in-capistrano/ # # Implementation: # # Review process: # only check the command nodes to see if there is bundler namespace in config/deploy.rb file, # # if the message of command node is "namespace" and the first argument is "bundler", # then it should use bundler's capistrano recipe. class DryBundlerInCapistranoReview < Review interesting_nodes :command interesting_files DEPLOY_FILES url 'https://rails-bestpractices.com/posts/2010/09/02/dry-bundler-in-capistrano/' # check call node to see if it is with message "namespace" and argument "bundler". add_callback :start_command do |node| if node.message.to_s == 'namespace' && node.arguments.all[0].to_s == 'bundler' add_error 'dry bundler in capistrano' end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core_ext/erubis.rb
lib/rails_best_practices/core_ext/erubis.rb
# frozen_string_literal: true require 'erubis' module Erubis class OnlyRuby < Eruby def add_preamble(src); end def add_text(src, text) src << text.gsub(/[^\s;]/, '') end def add_stmt(src, code) src << code src << ';' end def add_expr_literal(src, code) src << code src << ';' end def add_expr_escaped(src, code) src << code src << ';' end def add_expr_debug(src, code) src << code src << ';' end def add_postamble(src); end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/inline_disables/comment_ripper.rb
lib/rails_best_practices/inline_disables/comment_ripper.rb
# frozen_string_literal: true module RailsBestPractices module InlineDisables class CommentRipper < Ripper::SexpBuilder attr_reader :comments def initialize(*arg) super @comments = [] end def on_comment(*arg) # [sexp_type, statement, [lineno, column]] = super comments << super end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/inline_disables/inline_disable.rb
lib/rails_best_practices/inline_disables/inline_disable.rb
# frozen_string_literal: true module RailsBestPractices module InlineDisables class InlineDisable < Core::Check interesting_files ALL_FILES url '#' def initialize(*args) super @disabled_errors = [] end def check(filename, content) comments = CommentRipper.new(content).tap(&:parse).comments comments.each do |_sexp_type, statement, (line_number, _column)| add_as_disable_errors(filename, statement, line_number) end end def disabled?(error) error_key = [error.filename, error.line_number, error.type.split('::').last].join('-') disabled_error_keys.include?(error_key) end private def disabled_error_keys @disabled_error_keys ||= Set.new(@disabled_errors.map { |e| [e.filename, e.line_number, e.type].join('-') }) end def add_as_disable_errors(filename, statement, line_number) match = statement.match(/rails_b(?:est_)?p(?:ractices)?:disable (.*)/) return unless match check_names = match[1].split(',') check_names.each do |check_name| add_as_disable_error(filename, check_name.gsub(/Check$/, 'Review'), line_number) end end def add_as_disable_error(filename, check_name, line_number) @disabled_errors << RailsBestPractices::Core::Error.new( filename: filename, line_number: line_number, message: 'disable by inline comment', type: check_name, url: url ) end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares/initializer_prepare.rb
lib/rails_best_practices/prepares/initializer_prepare.rb
# frozen_string_literal: true module RailsBestPractices module Prepares # Check all initializers class InitializerPrepare < Core::Check interesting_nodes :method_add_arg, :class interesting_files INITIALIZER_FILES def initialize @configs = Prepares.configs end # check if AR include ActiveModel::ForbiddenAttributesProtection add_callback :start_method_add_arg do |node| if include_forbidden_attributes_protection?(node) @configs['railsbp.include_forbidden_attributes_protection'] = 'true' end end # check if the node is # ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection) def include_forbidden_attributes_protection?(node) node.receiver.to_s == 'ActiveRecord::Base' && node.message.to_s == 'send' && node.arguments.all.map(&:to_s) == ['include', 'ActiveModel::ForbiddenAttributesProtection'] end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares/route_prepare.rb
lib/rails_best_practices/prepares/route_prepare.rb
# frozen_string_literal: true module RailsBestPractices module Prepares # Remembber routes. class RoutePrepare < Core::Check interesting_nodes :command, :command_call, :method_add_block, :do_block, :brace_block interesting_files ROUTE_FILES RESOURCES_ACTIONS = %w[index show new create edit update destroy].freeze RESOURCE_ACTIONS = %w[show new create edit update destroy].freeze def initialize @routes = Prepares.routes @namespaces = [] @controller_names = [] end # remember route for rails3. add_callback :start_command do |node| case node.message.to_s when 'resources' add_resources_routes(node) when 'resource' add_resource_routes(node) when 'get', 'post', 'put', 'patch', 'delete' first_argument = node.arguments.all.first second_argument = node.arguments.all[1] if @controller_names.last if first_argument.sexp_type == :bare_assoc_hash action_names = [first_argument.hash_values.first.to_s] elsif first_argument.sexp_type == :array action_names = first_argument.array_values.map(&:to_s) elsif second_argument.try(:sexp_type) == :bare_assoc_hash && second_argument.hash_value('to').present? if second_argument.hash_value('to').sexp_type == :string_literal controller_name, action_name = second_argument.hash_value('to').to_s.split('#') action_names = [action_name] else action_names = [second_argument.hash_value('to').to_s] end elsif first_argument.sexp_type == :symbol_literal && second_argument.try(:sexp_type) && second_argument.sexp_type == :symbol_literal action_names = node.arguments.all.select { |arg| arg.sexp_type == :symbol_literal }.map(&:to_s) else action_names = [first_argument.to_s] end action_names.each do |action_name| @routes.add_route(current_namespaces, current_controller_name, action_name) end else if first_argument.sexp_type == :bare_assoc_hash route_node = first_argument.hash_values.first # do not parse redirect block if route_node.sexp_type != :method_add_arg controller_name, action_name = route_node.to_s.split('#') @routes.add_route(current_namespaces, controller_name.underscore, action_name) end elsif first_argument.sexp_type == :array first_argument.array_values.map(&:to_s).each do |action_node| @routes.add_route(current_namespaces, controller_name, action_node.to_s) end elsif second_argument.try(:sexp_type) == :bare_assoc_hash if second_argument.hash_value('to').present? controller_name, action_name = second_argument.hash_value('to').to_s.split('#') else controller_name = current_controller_name action_name = second_argument.hash_value('action') end @routes.add_route(current_namespaces, controller_name.try(:underscore), action_name) else controller_name, action_name = first_argument.to_s.split('/') @routes.add_route(current_namespaces, controller_name.underscore, action_name) end end when 'match' options = node.arguments.all.last case options.sexp_type when :bare_assoc_hash if options.hash_value('controller').present? return if options.hash_value('controller').sexp_type == :regexp_literal controller_name = options.hash_value('controller').to_s action_name = options.hash_value('action').present? ? options.hash_value('action').to_s : '*' @routes.add_route(current_namespaces, controller_name, action_name) else route_node = options.hash_values.find do |value_node| value_node.sexp_type == :string_literal && value_node.to_s.include?('#') end if route_node.present? controller_name, action_name = route_node.to_s.split('#') @routes.add_route(current_namespaces, controller_name.underscore, action_name) end end when :string_literal, :symbol_literal if current_controller_name @routes.add_route(current_namespaces, current_controller_name, options.to_s) end else # do nothing end when 'root' options = node.arguments.all.last case options.sexp_type when :bare_assoc_hash route_node = options.hash_values.find do |value_node| value_node.sexp_type == :string_literal && value_node.to_s.include?('#') end if route_node.present? controller_name, action_name = route_node.to_s.split('#') @routes.add_route(current_namespaces, controller_name.underscore, action_name) end when :string_literal controller_name, action_name = options.to_s.split('#') @routes.add_route(current_namespaces, controller_name.underscore, action_name) end else # nothing to do end end # TODO: should remove but breaks some tests # remember route for rails2. add_callback :start_command_call do |node| case node.message.to_s when 'resources' add_resources_routes(node) when 'resource' add_resource_routes(node) when 'namespace' # nothing to do else options = node.arguments.all.last if options.hash_value('controller').present? @controller_name = [:option, options.hash_value('controller').to_s] end action_name = options.hash_value('action').present? ? options.hash_value('action').to_s : '*' @routes.add_route(current_namespaces, current_controller_name, action_name) end end # remember the namespace. add_callback :start_method_add_block do |node| case node.message.to_s when 'namespace' @namespaces << node.arguments.all.first.to_s @controller_name = nil when 'scope' if node.arguments.all.last.hash_value('module').present? @namespaces << node.arguments.all.last.hash_value('module').to_s end @controller_name = if node.arguments.all.last.hash_value('controller').present? [:scope, node.arguments.all.last.hash_value('controller').to_s] else @controller_name.try(:first) == :scope ? @controller_name : nil end when 'with_options' argument = node.arguments.all.last if argument.sexp_type == :bare_assoc_hash && argument.hash_value('controller').present? @controller_name = [:with_option, argument.hash_value('controller').to_s] end else # do nothing end end # end of namespace call. add_callback :end_method_add_block do |node| case node.message.to_s when 'namespace' @namespaces.pop when 'scope' if node.arguments.all.last.hash_value('module').present? @namespaces.pop end else # do nothing end end # remember current controller name, used for nested resources. add_callback :start_do_block, :start_brace_block do |_node| @controller_names << @controller_name.try(:last) end # remove current controller name, and use upper lever resource name. add_callback :end_do_block, :end_brace_block do |_node| @controller_names.pop end %i[resources resource].each do |route_name| class_eval <<-EOF def add_#{route_name}_routes(node) resource_names = node.arguments.all.select { |argument| :symbol_literal == argument.sexp_type } resource_names.each do |resource_name| @controller_name = [:#{route_name}, node.arguments.all.first.to_s] options = node.arguments.all.last if options.hash_value("module").present? @namespaces << options.hash_value("module").to_s end if options.hash_value("controller").present? @controller_name = [:#{route_name}, options.hash_value("controller").to_s] end action_names = if options.hash_value("only").present? get_#{route_name}_actions(options.hash_value("only").to_object) elsif options.hash_value("except").present? self.class.const_get(:#{route_name.to_s.upcase}_ACTIONS) - get_#{route_name}_actions(options.hash_value("except").to_object) else self.class.const_get(:#{route_name.to_s.upcase}_ACTIONS) end action_names.each do |action_name| @routes.add_route(current_namespaces, current_controller_name, action_name) end member_routes = options.hash_value("member") if member_routes.present? action_names = :array == member_routes.sexp_type ? member_routes.to_object : member_routes.hash_keys action_names.each do |action_name| @routes.add_route(current_namespaces, current_controller_name, action_name) end end collection_routes = options.hash_value("collection") if collection_routes.present? action_names = :array == collection_routes.sexp_type ? collection_routes.to_object : collection_routes.hash_keys action_names.each do |action_name| @routes.add_route(current_namespaces, current_controller_name, action_name) end end if options.hash_value("module").present? @namespaces.pop end end end def get_#{route_name}_actions(action_names) case action_names when "all" self.class.const_get(:#{route_name.to_s.upcase}_ACTIONS) when "none" [] else Array(action_names) end end def add_customize_routes end EOF end def current_namespaces @namespaces.dup end def current_controller_name @controller_names.last || @controller_name.try(:last) end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares/schema_prepare.rb
lib/rails_best_practices/prepares/schema_prepare.rb
# frozen_string_literal: true module RailsBestPractices module Prepares # Remember the model attributes. class SchemaPrepare < Core::Check interesting_nodes :command, :command_call interesting_files SCHEMA_FILE # all attribute types ATTRIBUTE_TYPES = %w[integer float boolean string text date time datetime binary].freeze def initialize @model_attributes = Prepares.model_attributes end add_callback :start_command do |node| if node.message.to_s == 'create_table' @last_klazz = node.arguments.all.first.to_s.classify end end # check command_call node to remember the model attributes. add_callback :start_command_call do |node| if ATTRIBUTE_TYPES.include? node.message.to_s attribute_name = node.arguments.all.first.to_s @model_attributes.add_attribute(@last_klazz, attribute_name, node.message.to_s) end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares/mailer_prepare.rb
lib/rails_best_practices/prepares/mailer_prepare.rb
# frozen_string_literal: true module RailsBestPractices module Prepares # Remember the mailer names. class MailerPrepare < Core::Check include Core::Check::Classable interesting_nodes :class interesting_files MAILER_FILES, MODEL_FILES def initialize @mailers = Prepares.mailers end # check class node. # # if it is a subclass of ActionMailer::Base, # then remember its class name. add_callback :start_class do |_node| if current_extend_class_name == 'ActionMailer::Base' @mailers << @klass end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares/gemfile_prepare.rb
lib/rails_best_practices/prepares/gemfile_prepare.rb
# frozen_string_literal: true module RailsBestPractices module Prepares # Remember all gems in Gemfile class GemfilePrepare < Core::Check interesting_files GEMFILE_LOCK def initialize @gems = Prepares.gems end def check(_filename, content) content.split("\n").each do |line| if line =~ /([^ ]+) \((\d.*)\)/ @gems << Core::Gem.new(Regexp.last_match(1), Regexp.last_match(2)) end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares/model_prepare.rb
lib/rails_best_practices/prepares/model_prepare.rb
# frozen_string_literal: true module RailsBestPractices module Prepares # Remember models and model associations. class ModelPrepare < Core::Check include Core::Check::Classable include Core::Check::Accessable interesting_nodes :class, :def, :defs, :command, :alias interesting_files MODEL_FILES ASSOCIATION_METHODS = %w[ belongs_to has_one has_many has_and_belongs_to_many embeds_many embeds_one embedded_in many one ].freeze def initialize @models = Prepares.models @model_associations = Prepares.model_associations @model_attributes = Prepares.model_attributes @methods = Prepares.model_methods end # remember the class name. add_callback :start_class do |_node| if current_extend_class_name != 'ActionMailer::Base' @models << @klass end end # check def node to remember all methods. # # the remembered methods (@methods) are like # { # "Post" => { # "save" => {"file" => "app/models/post.rb", "line_number" => 10, "unused" => false, "unused" => false}, # "find" => {"file" => "app/models/post.rb", "line_number" => 10, "unused" => false, "unused" => false} # }, # "Comment" => { # "create" => {"file" => "app/models/comment.rb", "line_number" => 10, "unused" => false, "unused" => false}, # } # } add_callback :start_def do |node| if @klass && current_extend_class_name != 'ActionMailer::Base' && (classable_modules.empty? || klasses.any?) method_name = node.method_name.to_s @methods.add_method( current_class_name, method_name, { 'file' => node.file, 'line_number' => node.line_number }, current_access_control ) end end # check defs node to remember all static methods. # # the remembered methods (@methods) are like # { # "Post" => { # "save" => {"file" => "app/models/post.rb", "line_number" => 10, "unused" => false, "unused" => false}, # "find" => {"file" => "app/models/post.rb", "line_number" => 10, "unused" => false, "unused" => false} # }, # "Comment" => { # "create" => {"file" => "app/models/comment.rb", "line_number" => 10, "unused" => false, "unused" => false}, # } # } add_callback :start_defs do |node| if @klass && current_extend_class_name != 'ActionMailer::Base' method_name = node.method_name.to_s @methods.add_method( current_class_name, method_name, { 'file' => node.file, 'line_number' => node.line_number }, current_access_control ) end end # check command node to remember all assoications or named_scope/scope methods. # # the remembered association names (@associations) are like # { # "Project" => { # "categories" => {"has_and_belongs_to_many" => "Category"}, # "project_manager" => {"has_one" => "ProjectManager"}, # "portfolio" => {"belongs_to" => "Portfolio"}, # "milestones => {"has_many" => "Milestone"} # } # } add_callback :start_command do |node| case node.message.to_s when 'named_scope', 'scope', 'alias_method' method_name = node.arguments.all.first.to_s @methods.add_method( current_class_name, method_name, { 'file' => node.file, 'line_number' => node.line_number }, current_access_control ) when 'alias_method_chain' method, feature = *node.arguments.all.map(&:to_s) @methods.add_method( current_class_name, "#{method}_with_#{feature}", { 'file' => node.file, 'line_number' => node.line_number }, current_access_control ) @methods.add_method( current_class_name, method.to_s, { 'file' => node.file, 'line_number' => node.line_number }, current_access_control ) when 'field' arguments = node.arguments.all attribute_name = arguments.first.to_s attribute_type = arguments.last.hash_value('type').present? ? arguments.last.hash_value('type').to_s : 'String' @model_attributes.add_attribute(current_class_name, attribute_name, attribute_type) when 'key' attribute_name, attribute_type = node.arguments.all.map(&:to_s) @model_attributes.add_attribute(current_class_name, attribute_name, attribute_type) when *ASSOCIATION_METHODS remember_association(node) end end # check alias node to remembr the alias methods. add_callback :start_alias do |node| method_name = node.new_method.to_s @methods.add_method( current_class_name, method_name, { 'file' => node.file, 'line_number' => node.line_number }, current_access_control ) end # after prepare process, fix incorrect associations' class_name. add_callback :after_check do @model_associations.each do |model, model_associations| model_associations.each do |_association_name, association_meta| unless @models.include?(association_meta['class_name']) if @models.include?("#{model}::#{association_meta['class_name']}") association_meta['class_name'] = "#{model}::#{association_meta['class_name']}" elsif @models.include?(model.gsub(/::\w+$/, '')) association_meta['class_name'] = model.gsub(/::\w+$/, '') end end end end end private # remember associations, with class to association names. def remember_association(node) association_meta = node.message.to_s association_name = node.arguments.all.first.to_s arguments_node = node.arguments.all.last if arguments_node.hash_value('class_name').present? association_class = arguments_node.hash_value('class_name').to_s end association_class ||= association_name.classify @model_associations.add_association(current_class_name, association_name, association_meta, association_class) end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares/controller_prepare.rb
lib/rails_best_practices/prepares/controller_prepare.rb
# frozen_string_literal: true module RailsBestPractices module Prepares # Remember controllers and controller methods class ControllerPrepare < Core::Check include Core::Check::Classable include Core::Check::InheritedResourcesable include Core::Check::Accessable interesting_nodes :class, :var_ref, :vcall, :command, :def interesting_files CONTROLLER_FILES DEFAULT_ACTIONS = %w[index show new create edit update destroy].freeze def initialize @controllers = Prepares.controllers @methods = Prepares.controller_methods @helpers = Prepares.helpers @inherited_resources = false end # check class node to remember the class name. # also check if the controller is inherit from InheritedResources::Base. add_callback :start_class do |_node| @controllers << @klass @current_controller_name = @klass.to_s @actions = DEFAULT_ACTIONS if @inherited_resources end # remember the action names at the end of class node if the controller is a InheritedResources. add_callback :end_class do |node| if @inherited_resources && @current_controller_name != 'ApplicationController' @actions.each do |action| @methods.add_method( @current_controller_name, action, 'file' => node.file, 'line_number' => node.line_number ) end end end # check if there is a DSL call inherit_resources. add_callback :start_var_ref do |_node| @actions = DEFAULT_ACTIONS if @inherited_resources end # check if there is a DSL call inherit_resources. add_callback :start_vcall do |_node| @actions = DEFAULT_ACTIONS if @inherited_resources end # restrict actions for inherited_resources add_callback :start_command do |node| if node.message.to_s == 'include' @helpers.add_module_descendant(node.arguments.all.first.to_s, current_class_name) elsif @inherited_resources && node.message.to_s == 'actions' if node.arguments.all.first.to_s == 'all' @actions = DEFAULT_ACTIONS option_argument = node.arguments.all[1] if option_argument && option_argument.sexp_type == :bare_assoc_hash && option_argument.hash_value('except') @actions -= option_argument.hash_value('except').to_object end else @actions = node.arguments.all.map(&:to_s) end end end # check def node to remember all methods. # # the remembered methods (@methods) are like # { # "PostsController" => { # "save" => {"file" => "app/controllers/posts_controller.rb", "line_number" => 10, "unused" => false}, # "find" => {"file" => "app/controllers/posts_controller.rb", "line_number" => 10, "unused" => false} # }, # "CommentsController" => { # "create" => {"file" => "app/controllers/comments_controller.rb", "line_number" => 10, "unused" => false}, # } # } add_callback :start_def do |node| method_name = node.method_name.to_s @methods.add_method( current_class_name, method_name, { 'file' => node.file, 'line_number' => node.line_number }, current_access_control ) end # ask Reviews::RemoveUnusedMoethodsInHelperReview to check the controllers who include helpers. add_callback :after_check do descendants = @helpers.map(&:descendants).flatten if descendants.present? Reviews::RemoveUnusedMethodsInHelpersReview.interesting_files *descendants.map { |descendant| /#{descendant.underscore}/ } end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares/helper_prepare.rb
lib/rails_best_practices/prepares/helper_prepare.rb
# frozen_string_literal: true module RailsBestPractices module Prepares # Remember helper methods. class HelperPrepare < Core::Check include Core::Check::Moduleable include Core::Check::Accessable interesting_nodes :def, :command interesting_files HELPER_FILES, CONTROLLER_FILES def initialize @helpers = Prepares.helpers @methods = Prepares.helper_methods end # check module node to remember the module name. add_callback :start_module do |_node| @helpers << Core::Mod.new(current_module_name, []) end # check def node to remember all methods. # # the remembered methods (@methods) are like # { # "PostsHelper" => { # "create_time" => {"file" => "app/helpers/posts_helper.rb", "line_number" => 10, "unused" => false}, # "update_time" => {"file" => "app/helpers/posts_helper.rb", "line_number" => 10, "unused" => false} # } # } add_callback :start_def do |node| if node.file =~ HELPER_FILES method_name = node.method_name.to_s @methods.add_method( current_module_name, method_name, { 'file' => node.file, 'line_number' => node.line_number }, current_access_control ) end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/prepares/config_prepare.rb
lib/rails_best_practices/prepares/config_prepare.rb
# frozen_string_literal: true module RailsBestPractices module Prepares # Remember all configs class ConfigPrepare < Core::Check interesting_nodes :assign interesting_files CONFIG_FILES def initialize @configs = Prepares.configs end # check assignments to config add_callback :start_assign do |node| if node.left_value.grep_node(sexp_type: %i[vcall var_ref], to_s: 'config').present? @configs[node.left_value.to_s] = node.right_value.to_s end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/lexicals/remove_tab_check.rb
lib/rails_best_practices/lexicals/remove_tab_check.rb
# frozen_string_literal: true module RailsBestPractices module Lexicals # Make sure there are no tabs in files. # # See the best practice details here https://rails-bestpractices.com/posts/2011/07/04/remove-tab/ class RemoveTabCheck < Core::Check interesting_files ALL_FILES url 'https://rails-bestpractices.com/posts/2011/07/04/remove-tab/' # check if the content of file contains a tab. # # @param [String] filename name of the file # @param [String] content content of the file def check(filename, content) if content =~ /\t/m line_no = $`.count("\n") + 1 add_error('remove tab, use spaces instead', filename, line_no) end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/lexicals/long_line_check.rb
lib/rails_best_practices/lexicals/long_line_check.rb
# frozen_string_literal: true module RailsBestPractices module Lexicals # Keep lines fewer than 80 characters. class LongLineCheck < Core::Check interesting_files ALL_FILES def initialize(options = {}) super(options) @max_line_length = options['max_line_length'] || 80 end # check if a line is over 80 characters # # @param [String] filename name of the file # @param [String] content content of the file def check(filename, content) # Only check ruby files if /\.rb$/ =~ filename line_no = 0 content.each_line do |line| line_no += 1 actual_line_length = line.sub(/\s+$/, '').length next unless actual_line_length > @max_line_length add_error( "line is longer than #{@max_line_length} characters (#{actual_line_length} characters)", filename, line_no ) end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/lexicals/remove_trailing_whitespace_check.rb
lib/rails_best_practices/lexicals/remove_trailing_whitespace_check.rb
# frozen_string_literal: true module RailsBestPractices module Lexicals # Make sure there are no trailing whitespace in codes. # # See the best practice details here https://rails-bestpractices.com/posts/2010/12/02/remove-trailing-whitespace/ class RemoveTrailingWhitespaceCheck < Core::Check interesting_files ALL_FILES url 'https://rails-bestpractices.com/posts/2010/12/02/remove-trailing-whitespace/' # check if the content of file contain a trailing whitespace. # # @param [String] filename name of the file # @param [String] content content of the file def check(filename, content) if content =~ / +\n/m line_no = $`.count("\n") + 1 add_error('remove trailing whitespace', filename, line_no) end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/checks_loader.rb
lib/rails_best_practices/core/checks_loader.rb
# frozen_string_literal: true module RailsBestPractices module Core class ChecksLoader def initialize(config) @config = config end # load all lexical checks. def load_lexicals load_checks_from_config { |check_name| RailsBestPractices::Lexicals.const_get(check_name) } end # load all reviews according to configuration. def load_reviews load_checks_from_config do |check_name| RailsBestPractices::Reviews.const_get(check_name.gsub(/Check$/, 'Review')) end end private # read the checks from yaml config. def checks_from_config @checks ||= YAML.load_file @config end # load all checks from the configuration def load_checks_from_config(&block) checks_from_config.each_with_object([]) do |check, active_checks| check_instance = instantiate_check(block, *check) active_checks << check_instance unless check_instance.nil? end end # instantiates a check def instantiate_check(block, check_name, options) check_class = load_check_class(check_name, &block) check_class&.new(options || {}) end # loads the class for a check by calling the given block def load_check_class(check_name) yield(check_name) rescue NameError # nothing to do, the check does not exist end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/gems.rb
lib/rails_best_practices/core/gems.rb
# frozen_string_literal: true module RailsBestPractices module Core class Gems < Array def has_gem?(gem_name) find { |gem| gem.name == gem_name } end def gem_version(gem_name) find { |gem| gem.name == gem_name }.try(:version) end end # Gem info includes gem name and gem version class Gem attr_reader :name, :version def initialize(name, version) @name = name @version = version end def to_s "#{@name} (#{@version})" end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/methods.rb
lib/rails_best_practices/core/methods.rb
# frozen_string_literal: true module RailsBestPractices module Core # Method container. class Methods def initialize @methods = {} @possible_methods = {} end # Add a method. # # @param [String] class name # @param [String] method name # @param [Hash] method meta, file and line, {"file" => "app/models/post.rb", "line_number" => 5} # @param [String] access control, public, protected or private def add_method(class_name, method_name, meta = {}, access_control = 'public') return if class_name == '' return if has_method?(class_name, method_name) methods(class_name) << Method.new(class_name, method_name, access_control, meta) if access_control == 'public' @possible_methods[method_name] = false end end # Get methods of a class. # # @param [String] class name # @param [String] access control # @return [Array] all methods of a class for such access control, if access control is nil, return all public/protected/private methods def get_methods(class_name, access_control = nil) if access_control methods(class_name).select { |method| method.access_control == access_control } else methods(class_name) end end # If a class has a method. # # @param [String] class name # @param [String] method name # @param [String] access control # @return [Boolean] has a method or not def has_method?(class_name, method_name, access_control = nil) if access_control !!methods(class_name).find do |method| method.method_name == method_name && method.access_control == access_control end else !!methods(class_name).find { |method| method.method_name == method_name } end end # Mark parent class' method as used. # # @param [String] class name # @param [String] method name def mark_parent_class_method_used(class_name, method_name) klass = Prepares.klasses.find { |klass| klass.to_s == class_name } if klass&.extend_class_name mark_parent_class_method_used(klass.extend_class_name, method_name) method = get_method(klass.extend_class_name, method_name) method&.mark_used end end # Mark sub classes' method as used. # # @param [String] class name # @param [String] method name def mark_subclasses_method_used(class_name, method_name) Prepares.klasses.select { |klass| klass.extend_class_name == class_name }.each do |klass| mark_subclasses_method_used(klass.to_s, method_name) method = get_method(klass.to_s, method_name) method&.mark_used end end # Mark the method as public. # # @param [String] class name # @param [String] method name def mark_publicize(class_name, method_name) method = get_method(class_name, method_name) method&.publicize end # Mark parent classs' method as public. # # @param [String] class name # @param [String] method name def mark_parent_class_methods_publicize(class_name, method_name) klass = Prepares.klasses.find { |klass| klass.to_s == class_name } if klass&.extend_class_name mark_parent_class_methods_publicize(klass.extend_class_name, method_name) mark_publicize(class_name, method_name) end end # Remomber the method name, the method is probably be used for the class' public method. # # @param [String] method name def possible_public_used(method_name) @possible_methods[method_name] = true end # Get a method in a class. # # @param [String] class name # @param [String] method name # @param [String] access control # @return [Method] Method object def get_method(class_name, method_name, access_control = nil) if access_control methods(class_name).find do |method| method.method_name == method_name && method.access_control == access_control end else methods(class_name).find { |method| method.method_name == method_name } end end # Get all unused methods. # # @param [String] access control # @return [Array] array of Method def get_all_unused_methods(access_control = nil) @methods.inject([]) do |unused_methods, (_class_name, methods)| unused_methods += if access_control methods.select { |method| method.access_control == access_control && !method.used } else methods.reject(&:used) end end.reject { |method| method.access_control == 'public' && @possible_methods[method.method_name] } end private # Methods of a class. # # @param [String] class name # @return [Array] array of methods def methods(class_name) @methods[class_name] ||= [] end end # Method info includes class name, method name, access control, file, line_number, used. class Method attr_reader :access_control, :class_name, :method_name, :used, :file, :line_number def initialize(class_name, method_name, access_control, meta) @class_name = class_name @method_name = method_name @file = meta['file'] @line_number = meta['line_number'] @access_control = access_control @used = false end # Mark the method as used. def mark_used @used = true end # Mark the method as public def publicize @access_control = 'public' end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/klasses.rb
lib/rails_best_practices/core/klasses.rb
# frozen_string_literal: true module RailsBestPractices module Core # Klass container. class Klasses < Array # If include the class. # # @param [String] class name # @return [Boolean] include or not def include?(class_name) find { |klass| klass.to_s == class_name } end end # Class info includes class name, extend class name and module names. class Klass attr_reader :extend_class_name, :class_name def initialize(class_name, extend_class_name, modules) @modules = modules.dup base = @modules.map { |modu| "#{modu}::" }.join('') @class_name = base + class_name if extend_class_name @extend_class_name = base + extend_class_name end end def to_s class_name end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/model_associations.rb
lib/rails_best_practices/core/model_associations.rb
# frozen_string_literal: true module RailsBestPractices module Core # Model associations container. class ModelAssociations def initialize @associations = {} end # # @param [String] model name # @param [String] association name # @param [String] association meta, has_many, has_one, belongs_to and has_and_belongs_to_many # @param [String] association class name def add_association(model_name, association_name, association_meta, association_class = nil) @associations[model_name] ||= {} @associations[model_name][association_name] = { 'meta' => association_meta, 'class_name' => association_class || association_name.classify } end # Get a model association. # # @param [String] model name # @param [String] association name # @return [Hash] {"meta" => association_meta, "class_name" => association_class} def get_association(model_name, association_name) associations = @associations[model_name] associations && associations[association_name] end # If it is a model's association. # # @param [String] model name # @param [String] association name # @return [Boolean] true if it is the model's association def is_association?(model_name, association_name) associations = @associations[model_name] !!(associations && associations[association_name]) end # delegate each to @associations. def each @associations.each { |model, model_associations| yield model, model_associations } end # Get association's class name # # @param [String] table name # @param [String] association_name # @return [String] association's class name def get_association_class_name(table_name, association_name) ( associations = @associations.select { |model, _model_associations| model.gsub('::', '').tableize == table_name }.values .first ) && (association_meta = associations.select { |name, _meta| name == association_name }.values.first) && association_meta['class_name'] end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/controllers.rb
lib/rails_best_practices/core/controllers.rb
# frozen_string_literal: true require_rel 'klasses' module RailsBestPractices module Core # Controller classes. class Controllers < Klasses; end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/routes.rb
lib/rails_best_practices/core/routes.rb
# frozen_string_literal: true module RailsBestPractices module Core class Routes < Array # add a route. # # @param [Array] namesapces # @param [String] controller name # @param [String] action name def add_route(namespaces, controller_name, action_name) if namespaces.present? || controller_name.present? self << Route.new(namespaces, controller_name, action_name) end end end class Route attr_reader :namespaces, :controller_name, :action_name def initialize(namespaces, controller_name, action_name) @namespaces = namespaces # mappings can be specified by e.g. # post 'some/:pattern' => 'controller#action' if action_name.is_a?(String) && action_name =~ /\A(\w+)#(\w+)\z/ controller_name = Regexp.last_match(1) action_name = Regexp.last_match(2) end if controller_name entities = controller_name.split('/') @namespaces += entities[0..-2] if entities.size > 1 @controller_name = entities.last end @action_name = action_name end def controller_name_with_namespaces if controller_name namespaces.map { |namespace| "#{namespace.camelize}::" }.join('') + "#{controller_name.camelize}Controller" else namespaces.map(&:camelize).join('::') + 'Controller' end end def to_s "#{controller_name_with_namespaces}\##{action_name}" end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/models.rb
lib/rails_best_practices/core/models.rb
# frozen_string_literal: true module RailsBestPractices module Core # Model classes. class Models < Klasses; end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/mailers.rb
lib/rails_best_practices/core/mailers.rb
# frozen_string_literal: true module RailsBestPractices module Core # Mailer classes. class Mailers < Klasses; end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/model_attributes.rb
lib/rails_best_practices/core/model_attributes.rb
# frozen_string_literal: true module RailsBestPractices module Core # Model attributes container. class ModelAttributes def initialize @attributes = {} end # Add a model attribute. # # @param [String] model name # @param [String] attribute name # @param [String] attribute type def add_attribute(model_name, attribute_name, attribute_type) @attributes[model_name] ||= {} @attributes[model_name][attribute_name] = attribute_type end # Get attribute type. # # @param [String] model name # @param [String] attribute name # @return [String] attribute type def get_attribute_type(model_name, attribute_name) @attributes[model_name] ||= {} @attributes[model_name][attribute_name] end # If it is a model's attribute. # # @param [String] model name # @param [String] attribute name # @return [Boolean] true if it is the model's attribute def is_attribute?(model_name, attribute_name) @attributes[model_name] ||= {} !!@attributes[model_name][attribute_name] end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/helpers.rb
lib/rails_best_practices/core/helpers.rb
# frozen_string_literal: true require_rel 'modules' module RailsBestPractices module Core # Helper moduels. class Helpers < Modules; end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/runner.rb
lib/rails_best_practices/core/runner.rb
# frozen_string_literal: true require 'yaml' require 'active_support/core_ext/object/blank' begin require 'active_support/core_ext/object/try' rescue LoadError require 'active_support/core_ext/try' end require 'active_support/inflector' module RailsBestPractices module Core # Runner is the main class, it can check source code of a filename with all checks (according to the configuration). # # the check process is partitioned into two parts, # # 1. prepare process, it will do some preparations for further checking, such as remember the model associations. # 2. review process, it does real check, if the source code violates some best practices, the violations will be notified. class Runner attr_reader :checks class << self attr_writer :base_path, :config_path # get the base path, by default, the base path is current path. # # @return [String] the base path def base_path @base_path || '.' end # get the configuration path, if will default to config/rails_best_practices.yml # # @return [String] the config path def config_path custom_config = @config_path || File.join(Runner.base_path, 'config/rails_best_practices.yml') File.exist?(custom_config) ? custom_config : RailsBestPractices::Analyzer::DEFAULT_CONFIG end end # initialize the runner. # # @param [Hash] options pass the prepares and reviews. def initialize(options = {}) @config = self.class.config_path lexicals = Array(options[:lexicals]) prepares = Array(options[:prepares]) reviews = Array(options[:reviews]) checks_loader = ChecksLoader.new(@config) @lexicals = lexicals.empty? ? checks_loader.load_lexicals : lexicals @prepares = prepares.empty? ? load_prepares : prepares @reviews = reviews.empty? ? checks_loader.load_reviews : reviews load_plugin_reviews if reviews.empty? @lexical_checker ||= CodeAnalyzer::CheckingVisitor::Plain.new(checkers: @lexicals) @plain_prepare_checker ||= CodeAnalyzer::CheckingVisitor::Plain.new( checkers: @prepares.select { |checker| checker.is_a? Prepares::GemfilePrepare } ) @default_prepare_checker ||= CodeAnalyzer::CheckingVisitor::Default.new( checkers: @prepares.reject { |checker| checker.is_a? Prepares::GemfilePrepare } ) @review_checker ||= CodeAnalyzer::CheckingVisitor::Default.new(checkers: @reviews) @inlnie_disable ||= InlineDisables::InlineDisable.new @inline_disable_checker ||= CodeAnalyzer::CheckingVisitor::Plain.new(checkers: [@inlnie_disable]) end # lexical analysis the file. # # @param [String] filename of the file # @param [String] content of the file def lexical(filename, content) @lexical_checker.check(filename, content) end def after_lexical @lexical_checker.after_check end # prepare the file. # # @param [String] filename of the file # @param [String] content of the file def prepare(filename, content) @plain_prepare_checker.check(filename, content) @default_prepare_checker.check(filename, content) end def after_prepare @plain_prepare_checker.after_check @default_prepare_checker.after_check end # review the file. # # @param [String] filename of the file # @param [String] content of the file def review(filename, content) content = parse_html_template(filename, content) @review_checker.check(filename, content) end def after_review @review_checker.after_check end # disable check by inline comment the file. # # @param [String] filename of the file # @param [String] content of the file def inline_disable(filename, content) content = parse_html_template(filename, content) @inline_disable_checker.check(filename, content) end def after_inline_disable @inline_disable_checker.after_check end # get all errors from lexicals and reviews. # # @return [Array] all errors from lexicals and reviews def errors @errors ||= begin reported_errors = (@reviews + @lexicals).collect(&:errors).flatten reported_errors.reject { |error| @inlnie_disable.disabled?(error) } end end private # parse html template code, erb, haml and slim. # # @param [String] filename is the filename of the erb, haml or slim code. # @param [String] content is the source code of erb, haml or slim file. def parse_html_template(filename, content) if filename =~ /.*\.erb$|.*\.rhtml$/ content = Erubis::OnlyRuby.new(content).src elsif filename =~ /.*\.haml$/ begin require 'haml' content = Haml::Engine.new(content).precompiled # remove \xxx characters content.gsub!(/\\\d{3}/, '') rescue LoadError raise "In order to parse #{filename}, please install the haml gem" rescue Haml::Error, SyntaxError # do nothing, just ignore the wrong haml files. end elsif filename =~ /.*\.slim$/ begin require 'slim' content = Slim::Engine.new.call(content) rescue LoadError raise "In order to parse #{filename}, please install the slim gem" rescue SyntaxError # do nothing, just ignore the wrong slim files end end content end # load all prepares. def load_prepares Prepares.constants.map { |prepare| Prepares.const_get(prepare).new } end # load all plugin reviews. def load_plugin_reviews plugins = File.join(Runner.base_path, 'lib', 'rails_best_practices', 'plugins', 'reviews') if File.directory?(plugins) Dir[File.expand_path(File.join(plugins, '*.rb'))].each do |review| require review end if RailsBestPractices.constants.map(&:to_sym).include? :Plugins RailsBestPractices::Plugins::Reviews.constants.each do |review| @reviews << RailsBestPractices::Plugins::Reviews.const_get(review).new end end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/check.rb
lib/rails_best_practices/core/check.rb
# frozen_string_literal: true module RailsBestPractices module Core # A Check class that takes charge of checking the sexp. class Check < CodeAnalyzer::Checker ALL_FILES = /.*/.freeze CONTROLLER_FILES = %r{app/(controllers|cells)/.*\.rb$}.freeze MIGRATION_FILES = %r{db/migrate/.*\.rb$}.freeze MODEL_FILES = %r{app/models/.*\.rb$}.freeze MAILER_FILES = %r{app/models/.*mailer\.rb$|app/mailers/.*\.rb}.freeze VIEW_FILES = %r{app/(views|cells)/.*\.(erb|haml|slim|builder|rxml)$}.freeze PARTIAL_VIEW_FILES = %r{app/(views|cells)/.*/_.*\.(erb|haml|slim|builder|rxml)$}.freeze ROUTE_FILES = %r{config/routes.*\.rb}.freeze SCHEMA_FILE = %r{db/schema\.rb}.freeze HELPER_FILES = %r{app/helpers/.*\.rb$}.freeze DEPLOY_FILES = %r{config/deploy.*\.rb}.freeze CONFIG_FILES = %r{config/(application|environment|environments/.*)\.rb}.freeze INITIALIZER_FILES = %r{config/initializers/.*\.rb}.freeze CAPFILE = /Capfile/.freeze GEMFILE_LOCK = /Gemfile\.lock/.freeze SKIP_FILES = %r{db/schema.rb}.freeze def initialize(options = {}) options.each do |key, value| instance_variable_set("@#{key}", value) end end # check if the check will need to parse the node file. # # @param [String] the file name of node. # @return [Boolean] true if the check will need to parse the file. def parse_file?(node_file) node_file.is_a?(String) && is_interesting_file?(node_file) && !is_ignored?(node_file) end def is_interesting_file?(node_file) interesting_files.any? do |pattern| if pattern == ALL_FILES node_file =~ pattern && node_file !~ SKIP_FILES else node_file =~ pattern end end end def is_ignored?(node_file) regex_ignored_files.map { |r| !!r.match(node_file) }.inject(:|) end def regex_ignored_files @regex_ignored_files ||= Array(@ignored_files).map { |pattern| Regexp.new(pattern) } end # add error if source code violates rails best practice. # # @param [String] message, is the string message for violation of the rails best practice # @param [String] filename, is the filename of source code # @param [Integer] line_number, is the line number of the source code which is reviewing def add_error(message, filename = @node.file, line_number = @node.line_number) errors << RailsBestPractices::Core::Error.new( filename: filename, line_number: line_number, message: message, type: self.class.to_s, url: url ) end # errors that violate the rails best practices. def errors @errors ||= [] end # default url is empty. # # @return [String] the url of rails best practice def url self.class.url end # method_missing to catch all start and end process for each node type, like # # start_def # end_def # start_call # end_call # # if there is a "debug" method defined in check, each node will be output. def method_missing(method_name, *args) if method_name.to_s =~ /^start_/ p args if respond_to?(:debug) elsif method_name.to_s =~ /^end_/ # nothing to do else super end end class << self def url(url = nil) url ? @url = url : @url end def debug? @debug == true end def debug @debug = true end end # Helper to parse the class name. module Classable def self.included(base) base.class_eval do interesting_nodes :module, :class # remember module name add_callback :start_module do |node| classable_modules << node.module_name.to_s end # end of the module. add_callback :end_module do |_node| classable_modules.pop end # remember the class name add_callback :start_class do |node| base_class_name = node.base_class.is_a?(CodeAnalyzer::Nil) ? nil : node.base_class.to_s @klass = Core::Klass.new(node.class_name.to_s, base_class_name, classable_modules) klasses << @klass end # end of the class add_callback :end_class do |_node| klasses.pop @klass = klasses.last end end end # get the current class name. def current_class_name @klass.to_s end # get the current extend class name. def current_extend_class_name @klass.extend_class_name end # modules. def classable_modules @class_modules ||= [] end def klasses @klasses ||= [] end end # Helper to parse the module name. module Moduleable def self.included(base) base.class_eval do interesting_nodes :module # remember module name add_callback :start_module do |node| moduleable_modules << node.module_name.to_s end # end of module add_callback :end_module do |_node| moduleable_modules.pop end end end # get the current module name. def current_module_name moduleable_modules.join('::') end # modules. def moduleable_modules @moduleable_modules ||= [] end end # Helper to add callbacks to mark the methods are used. module Callable def self.included(base) base.class_eval do interesting_nodes :call, :fcall, :var_ref, :vcall, :command_call, :command, :alias, :assoc_new, :method_add_arg # remembe the message of call node. add_callback :start_call do |node| mark_used(node.message) end # remembe the message of fcall node. add_callback :start_fcall do |node| mark_used(node.message) end # remembe name of var_ref node. add_callback :start_var_ref do |node| mark_used(node) end # remembe name of vcall node. add_callback :start_vcall do |node| mark_used(node) end # skip start_command callback for these nodes def skip_command_callback_nodes [] end # remember the message of command node. # remember the argument of alias_method and alias_method_chain as well. add_callback :start_command do |node| case node.message.to_s when *skip_command_callback_nodes # nothing when 'alias_method' mark_used(node.arguments.all[1]) when 'alias_method_chain' method, feature = *node.arguments.all.map(&:to_s) call_method("#{method}_with_#{feature}") when /^(before|after)_/ node.arguments.all.each { |argument| mark_used(argument) } else mark_used(node.message) last_argument = node.arguments.all.last if last_argument.present? && last_argument.sexp_type == :bare_assoc_hash last_argument.hash_values.each { |argument_value| mark_used(argument_value) } end end end # remembe the message of command call node. add_callback :start_command_call do |node| mark_used(node.message) end # remember the old method of alias node. add_callback :start_alias do |node| mark_used(node.old_method) end # remember hash values for hash key "methods". # # def to_xml(options = {}) # super options.merge(exclude: :visible, methods: [:is_discussion_conversation]) # end add_callback :start_assoc_new do |node| if node.key == 'methods' mark_used(node.value) end if node.value.nil? mark_used(node.key) end end # remember the first argument for try and send method. add_callback :start_method_add_arg do |node| case node.message.to_s when 'try' mark_used(node.arguments.all.first) when 'send' if %i[symbol_literal string_literal].include?(node.arguments.all.first.sexp_type) mark_used(node.arguments.all.first) end else # nothing end end private def mark_used(method_node) return if method_node == :call if method_node.is_a?(String) method_name = method_node elsif method_node.sexp_type == :bare_assoc_hash method_node.hash_values.each { |value_node| mark_used(value_node) } elsif method_node.sexp_type == :array method_node.array_values.each { |value_node| mark_used(value_node) } else method_name = method_node.to_s end call_method(method_name) end def call_method(method_name, class_name = nil) class_name ||= respond_to?(:current_class_name) ? current_class_name : current_module_name if methods.has_method?(class_name, method_name) methods.get_method(class_name, method_name).mark_used end methods.mark_parent_class_method_used(class_name, method_name) methods.mark_subclasses_method_used(class_name, method_name) methods.possible_public_used(method_name) end end end end # Helper to indicate if the controller is inherited from InheritedResources. module InheritedResourcesable def self.included(base) base.class_eval do interesting_nodes :class, :var_ref, :vcall interesting_files CONTROLLER_FILES # check if the controller is inherit from InheritedResources::Base. add_callback :start_class do |_node| if current_extend_class_name == 'InheritedResources::Base' @inherited_resources = true end end # check if there is a DSL call inherit_resources. add_callback :start_var_ref do |node| if node.to_s == 'inherit_resources' @inherited_resources = true end end # check if there is a DSL call inherit_resources. add_callback :start_vcall do |node| if node.to_s == 'inherit_resources' @inherited_resources = true end end end end end # Helper to check except methods. module Exceptable def self.included(base) base.class_eval do def except_methods @except_methods + internal_except_methods end # check if the method is in the except methods list. def excepted?(method) is_ignored?(method.file) || except_methods.any? { |except_method| Exceptable.matches method, except_method } end def internal_except_methods raise NoMethodError, 'no method internal_except_methods' end end end def self.matches(method, except_method) class_name, method_name = except_method.split('#') method_name = '.*' if method_name == '*' method_expression = Regexp.new method_name matched = method.method_name =~ method_expression if matched class_name = '.*' if class_name == '*' class_expression = Regexp.new class_name class_names = Prepares.klasses.select { |klass| klass.class_name == method.class_name }.map(&:extend_class_name).compact class_names.unshift method.class_name matched = class_names.any? { |name| name =~ class_expression } end !!matched end end # Helper to parse the access control. module Accessable def self.included(base) base.class_eval do interesting_nodes :var_ref, :vcall, :class, :module # remember the current access control for methods. add_callback :start_var_ref do |node| if %w[public protected private].include? node.to_s @access_control = node.to_s end end # remember the current access control for methods. add_callback :start_vcall do |node| if %w[public protected private].include? node.to_s @access_control = node.to_s end end # set access control to "public" by default. add_callback :start_class do |_node| @access_control = 'public' end # set access control to "public" by default. add_callback :start_module do |_node| @access_control = 'public' end end # get the current acces control. def current_access_control @access_control end end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/configs.rb
lib/rails_best_practices/core/configs.rb
# frozen_string_literal: true module RailsBestPractices module Core class Configs < Hash; end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/modules.rb
lib/rails_best_practices/core/modules.rb
# frozen_string_literal: true module RailsBestPractices module Core # Module container class Modules < Array # add module descendant. # # @param [String] module name # @param [String] descendant name def add_module_descendant(module_name, descendant) mod = find { |mod| mod.to_s == module_name } mod&.add_descendant(descendant) end end # Module info include module name and module spaces. class Mod attr_reader :descendants def initialize(module_name, modules) @module_name = module_name @modules = modules @descendants = [] end def add_descendant(descendant) @descendants << descendant end def to_s if @modules.empty? @module_name else @modules.map { |modu| "#{modu}::" }.join('') + @module_name end end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
flyerhzm/rails_best_practices
https://github.com/flyerhzm/rails_best_practices/blob/2ef40880d12ff8ed5f516871133ec569df03b192/lib/rails_best_practices/core/error.rb
lib/rails_best_practices/core/error.rb
# frozen_string_literal: true module RailsBestPractices module Core # Error is the violation to rails best practice. # # it indicates the filenname, line number and error message for the violation. class Error < CodeAnalyzer::Warning attr_reader :type, :url attr_accessor :git_commit, :git_username, :hg_commit, :hg_username def initialize(options = {}) super @type = options[:type] @url = options[:url] @git_commit = options[:git_commit] @git_username = options[:git_username] @hg_commit = options[:hg_commit] @hg_username = options[:hg_username] end def short_filename File.expand_path(filename)[File.expand_path(Core::Runner.base_path).size..-1].sub(%r{^/}, '') end def first_line_number line_number.split(',').first end end end end
ruby
MIT
2ef40880d12ff8ed5f516871133ec569df03b192
2026-01-04T15:47:01.660067Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/spec_helper.rb
spec_helper.rb
# This module is only used to check the environment is currently a testing env module SpecHelper end require "coveralls" Coveralls.wear! unless ENV["FASTLANE_SKIP_UPDATE_CHECK"] require "webmock/rspec" WebMock.disable_net_connect!(allow: 'coveralls.io') require "fastlane" UI = FastlaneCore::UI unless ENV["DEBUG"] fastlane_tests_tmpdir = "#{Dir.tmpdir}/fastlane_tests" $stdout.puts("Changing stdout to #{fastlane_tests_tmpdir}, set `DEBUG` environment variable to print to stdout (e.g. when using `pry`)") $stdout = File.open(fastlane_tests_tmpdir, "w") end if FastlaneCore::Helper.mac? xcode_path = FastlaneCore::Helper.xcode_path unless xcode_path.include?("Contents/Developer") UI.error("Seems like you didn't set the developer tools path correctly") UI.error("Detected path '#{xcode_path}'") if xcode_path.to_s.length > 0 UI.error("Please run the following on your machine") UI.command("sudo xcode-select -s /Applications/Xcode.app") UI.error("Adapt the path if you have Xcode installed/named somewhere else") exit(1) end end (Fastlane::TOOLS + [:spaceship, :fastlane_core]).each do |tool| path = File.join(tool.to_s, "spec", "spec_helper.rb") require_relative path if File.exist?(path) require tool.to_s end my_main = self RSpec.configure do |config| config.before(:each) do |current_test| # We don't want to call the RubyGems API at any point # This was a request that was added with Ruby 2.4.0 allow(Fastlane::FastlaneRequire).to receive(:install_gem_if_needed).and_return(nil) ENV['FASTLANE_PLATFORM_NAME'] = nil # execute `before_each_*` method from spec_helper for each tool tool_name = current_test.id.match(%r{\.\/(\w+)\/})[1] method_name = "before_each_#{tool_name}".to_sym begin my_main.send(method_name) rescue NoMethodError # no method implemented end # Make sure PATH didn't get emptied during execution of previous (!) test expect(ENV['PATH']).to be_truthy, "PATH is missing. (Previous test probably emptied it.)" end config.after(:each) do |current_test| # execute `after_each_*` method from spec_helper for each tool tool_name = current_test.id.match(%r{\.\/(\w+)\/})[1] method_name = "after_each_#{tool_name}".to_sym begin my_main.send(method_name) rescue NoMethodError # no method implemented end end config.example_status_persistence_file_path = "#{Dir.tmpdir}/rspec_failed_tests.txt" # skip some tests if not running on mac unless FastlaneCore::Helper.mac? # define metadata tags that also imply :skip config.define_derived_metadata(:requires_xcode) do |meta| meta[:skip] = "Skipped: Requires Xcode to be installed (which is not possible on this platform and no workaround has been implemented)" end config.define_derived_metadata(:requires_xcodebuild) do |meta| meta[:skip] = "Skipped: Requires `xcodebuild` to be installed (which is not possible on this platform and no workaround has been implemented)" end config.define_derived_metadata(:requires_plistbuddy) do |meta| meta[:skip] = "Skipped: Requires `plistbuddy` to be installed (which is not possible on this platform and no workaround has been implemented)" end config.define_derived_metadata(:requires_keychain) do |meta| meta[:skip] = "Skipped: Requires `keychain` to be installed (which is not possible on this platform and no workaround has been implemented)" end config.define_derived_metadata(:requires_security) do |meta| meta[:skip] = "Skipped: Requires `security` to be installed (which is not possible on this platform and no workaround has been implemented)" end # also skip `before()` for test groups that are skipped because of their tags. # only works for `describe` groups (that are parents of the `before`, not if the tag is set on `it`. # caution: has unexpected side effect on usage of `skip: false` for individual examples, # see https://groups.google.com/d/msg/rspec/5qeKQr_7G7k/Pb3ss2hOAAAJ module HookOverrides def before(*args) super unless metadata[:skip] end end config.extend(HookOverrides) end # skip some more tests if run on on Windows if FastlaneCore::Helper.windows? || !system('which xar') config.define_derived_metadata(:requires_xar) do |meta| meta[:skip] = "Skipped: Requires `xar` to be installed (which is not possible on Windows and some Linux distros and no workaround has been implemented)" end end if FastlaneCore::Helper.windows? config.define_derived_metadata(:requires_pty) do |meta| meta[:skip] = "Skipped: Requires `pty` to be available (which is not possible on Windows and no workaround has been implemented)" end end end module FastlaneSpec module Env # a wrapper to temporarily modify the values of ARGV to # avoid errors like: "warning: already initialized constant ARGV" # if no block is given, modifies ARGV for good # rubocop:disable Naming/MethodName def self.with_ARGV(argv) copy = ARGV.dup ARGV.clear ARGV.concat(argv) # Commander::Methods imports delegate methods that shares the singleton # so this prevents Commander from choosing wrong command previously cached. Commander::Runner.instance_variable_set(:@instance, nil) begin # Do not check for "block_given?". This method is useless without a # block, and must fail if used like that. yield ensure ARGV.clear ARGV.concat(copy) end end # rubocop:enable Naming/MethodName def self.with_verbose(verbose) orig_verbose = FastlaneCore::Globals.verbose? FastlaneCore::Globals.verbose = verbose # Do not check for "block_given?". This method is useless without a # block, and must fail if used like that. yield ensure FastlaneCore::Globals.verbose = orig_verbose end # Executes the provided block after adjusting the ENV to have the # provided keys and values set as defined in hash. After the block # completes, restores the ENV to its previous state. require "climate_control" def self.with_env_values(hash, &block) ClimateControl.modify(hash, &block) end def self.with_action_context_values(hash, &block) with_global_key_values(Fastlane::Actions.lane_context, hash, &block) end def self.with_global_key_values(global_store, hash) old_vals = global_store.select { |k, v| hash.include?(k) } hash.each { |k, v| global_store[k] = v } yield ensure hash.each do |k, v| if old_vals.include?(k) global_store[k] = old_vals[k] else global_store.delete(k) end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/spec/commands_generator_spec.rb
scan/spec/commands_generator_spec.rb
require 'scan/commands_generator' describe Scan::CommandsGenerator do let(:available_options) { Scan::Options.available_options } describe ":tests option handling" do def expect_manager_work_with(expected_options) expect(Scan::Manager).to receive_message_chain(:new, :work) do |actual_options| expect(actual_options._values).to eq(expected_options._values) end end it "can use the clean short flag from tool options" do # leaving out the command name defaults to 'tests' stub_commander_runner_args(['-c', 'true']) expected_options = FastlaneCore::Configuration.create(available_options, { clean: true }) expect_manager_work_with(expected_options) Scan::CommandsGenerator.start end it "can use the scheme flag from tool options" do # leaving out the command name defaults to 'tests' stub_commander_runner_args(['--scheme', 'MyScheme']) expected_options = FastlaneCore::Configuration.create(available_options, { scheme: 'MyScheme' }) expect_manager_work_with(expected_options) Scan::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/scan/spec/error_handler_spec.rb
scan/spec/error_handler_spec.rb
require 'scan' describe Scan do describe Scan::ErrorHandler do let(:log_path) { '~/scan.log' } describe "handle_build_error" do describe "when parsing parallel test failure output" do it "does not report a build failure" do expect(Scan).to receive(:config).and_return({}) output = File.open('./scan/spec/fixtures/parallel_testing_failure.log', &:read) expect do Scan::ErrorHandler.handle_build_error(output, log_path) end.not_to raise_error end end describe "when parsing non-parallel test failure output" do it "does not report a build failure" do expect(Scan).to receive(:config).and_return({}) output = File.open('./scan/spec/fixtures/non_parallel_testing_failure.log', &:read) expect do Scan::ErrorHandler.handle_build_error(output, log_path) end.to_not(raise_error) end end describe "when parsing early failure output" do let(:output_path) { './scan/spec/fixtures/early_testing_failure.log' } before(:each) do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { project: './scan/examples/standard/app.xcodeproj' }) end it "reports a build failure", requires_xcodebuild: true do output = File.open(output_path, &:read) expect do Scan::ErrorHandler.handle_build_error(output, log_path) end.to(raise_error(FastlaneCore::Interface::FastlaneBuildFailure)) end it "mentions log above when not suppressing output", requires_xcodebuild: true do output = File.open(output_path, &:read) expect do Scan::ErrorHandler.handle_build_error(output, log_path) end.to(raise_error(FastlaneCore::Interface::FastlaneBuildFailure, "Error building the application. See the log above.")) end it "mentions log file when suppressing output", requires_xcodebuild: true do Scan.config[:suppress_xcode_output] = true output = File.open(output_path, &:read) expect do Scan::ErrorHandler.handle_build_error(output, log_path) end.to(raise_error(FastlaneCore::Interface::FastlaneBuildFailure, "Error building the application. See the log here: '#{log_path}'.")) end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/spec/slack_poster_spec.rb
scan/spec/slack_poster_spec.rb
require 'scan' require 'slack-notifier' describe Scan::SlackPoster do before do # mock the network request part allow_any_instance_of(Fastlane::Actions::SlackAction::Runner).to receive(:post_message).with(any_args) end describe "slack_url handling" do describe "without a slack_url set" do it "skips Slack posting", requires_xcodebuild: true do # ensures that people's local environment variable doesn't interfere with this test FastlaneSpec::Env.with_env_values('SLACK_URL' => nil) do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { project: './scan/examples/standard/app.xcodeproj' }) expect(Fastlane::Actions::SlackAction).not_to(receive(:run)) Scan::SlackPoster.new.run({ tests: 0, failures: 0 }) end end end describe "with the slack_url option set but skip_slack set to true" do it "skips Slack posting", requires_xcodebuild: true do # ensures that people's local environment variable doesn't interfere with this test FastlaneSpec::Env.with_env_values('SLACK_URL' => nil) do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { project: './scan/examples/standard/app.xcodeproj', slack_url: 'https://slack/hook/url', skip_slack: true }) expect(Fastlane::Actions::SlackAction).not_to(receive(:run)) Scan::SlackPoster.new.run({ tests: 0, failures: 0 }) end end end describe "with the SLACK_URL ENV var set but skip_slack set to true" do it "skips Slack posting", requires_xcodebuild: true do FastlaneSpec::Env.with_env_values('SLACK_URL' => 'https://slack/hook/url') do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { project: './scan/examples/standard/app.xcodeproj', skip_slack: true }) expect(Fastlane::Actions::SlackAction).not_to(receive(:run)) Scan::SlackPoster.new.run({ tests: 0, failures: 0 }) end end end describe "with the SLACK_URL ENV var set to empty string" do it "skips Slack posting", requires_xcodebuild: true do FastlaneSpec::Env.with_env_values('SLACK_URL' => '') do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { project: './scan/examples/standard/app.xcodeproj' }) expect(Fastlane::Actions::SlackAction).not_to(receive(:run)) Scan::SlackPoster.new.run({ tests: 0, failures: 0 }) end end end describe "with the slack_url option set to empty string" do it "skips Slack posting", requires_xcodebuild: true do # ensures that people's local environment variable doesn't interfere with this test FastlaneSpec::Env.with_env_values('SLACK_URL' => nil) do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { project: './scan/examples/standard/app.xcodeproj', slack_url: '' }) expect(Fastlane::Actions::SlackAction).not_to(receive(:run)) Scan::SlackPoster.new.run({ tests: 0, failures: 0 }) end end end def expected_slack_poster_arguments hash = { message: a_string_matching(' Tests:'), channel: nil, slack_url: 'https://slack/hook/url', username: 'fastlane', icon_url: 'https://fastlane.tools/assets/img/fastlane_icon.png', default_payloads: nil, attachment_properties: { fields: [ { title: 'Test Failures', value: '0', short: true }, { title: 'Successful Tests', value: '0', short: true } ] } } end describe "with slack_url option set to a URL value" do it "does Slack posting", requires_xcodebuild: true do # ensures that people's local environment variable doesn't interfere with this test FastlaneSpec::Env.with_env_values('SLACK_URL' => nil) do expect(ENV['SLACK_URL']).to eq(nil) Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { project: './scan/examples/standard/app.xcodeproj', slack_url: 'https://slack/hook/url' }) expect(FastlaneCore::Configuration).to( receive(:create) .with(any_args, hash_including(expected_slack_poster_arguments)) .and_call_original ) Scan::SlackPoster.new.run({ tests: 0, failures: 0 }) end end end describe "with SLACK_URL ENV var set to a URL value" do it "does Slack posting", requires_xcodebuild: true do FastlaneSpec::Env.with_env_values('SLACK_URL' => 'https://slack/hook/url') do expect(ENV['SLACK_URL']).to eq('https://slack/hook/url') Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { project: './scan/examples/standard/app.xcodeproj' }) expect(FastlaneCore::Configuration).to( receive(:create) .with(any_args, hash_including(expected_slack_poster_arguments)) .and_call_original ) Scan::SlackPoster.new.run({ tests: 0, failures: 0 }) end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/spec/test_command_generator_spec.rb
scan/spec/test_command_generator_spec.rb
describe Scan do before(:all) do options = { project: "./scan/examples/standard/app.xcodeproj" } config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) @project = FastlaneCore::Project.new(config) end before(:each) do @valid_simulators = "== Devices == -- iOS 10.0 -- iPhone 5 (5FF87891-D7CB-4C65-9F88-701A471223A9) (Shutdown) iPhone 5s (E697990C-3A83-4C01-83D1-C367011B31EE) (Shutdown) iPhone 6 (A35509F5-78A4-4B7D-B199-0F1244A5A7FC) (Shutdown) iPhone 6 Plus (F8E78DE1-F715-46BE-B9FD-4909CC45C05F) (Shutdown) iPhone 6s (021A465B-A294-4D9E-AD07-6BDC8E186343) (Shutdown) iPhone 6s Plus (1891208D-477A-4399-83BE-7D57B176A32B) (Shutdown) iPhone SE (B3D411C0-7FC4-4248-BEB8-7B09668023C8) (Shutdown) iPad Retina (07773A11-417D-4D4C-BC25-1C3444D50836) (Shutdown) iPad Air (2ABEAF08-E480-4617-894F-6BAB587E7963) (Shutdown) iPad Air 2 (DA6C7D10-564B-4563-884D-834EF4F10FB9) (Shutdown) iPad Pro (9.7-inch) (C051C63B-EDF7-4871-860A-BF975B517E94) (Shutdown) iPad Pro (12.9-inch) (EED6BFB4-5DD9-48AB-8573-5172EF6F2A93) (Shutdown) -- iOS 9.3 -- iPhone 4s (238767C4-AF29-4485-878C-7011B98DCB87) (Shutdown) iPhone 5 (B8E05CCB-B97A-41FC-A8A8-2771711690B5) (Shutdown) iPhone 5s (F48E1168-110C-4EC6-805C-6B03A03CAC2D) (Shutdown) iPhone 6 (BD0777BE-32DC-425F-8FC6-10008F7AB814) (Shutdown) iPhone 6 Plus (E9F12F3C-75B9-47D0-998A-02220E1E7E9D) (Shutdown) iPhone 6s (70E1E92F-A292-4980-BC3C-7770C5EEFCFD) (Shutdown) iPhone 6s Plus (A250CEDA-5CCD-4396-B215-19AF6D0B4ADA) (Shutdown) iPad 2 (57344451-50CF-40E1-96FA-DFEFC1107B79) (Shutdown) iPad Retina (AD4384AC-3D47-4B43-B0E2-2020C41D67F5) (Shutdown) iPad Air (DD134998-177F-47DA-99FA-D549D9305476) (Shutdown) iPad Air 2 (9B54C167-21A9-4AD7-97D4-21F2F1D7EAAF) (Shutdown) iPad Pro (61EEEF5C-EA64-47EF-9EED-3075E983FBCD) (Shutdown) -- iOS 9.0 -- iPhone 4s (88975B7F-DE3C-4680-8653-F4212E389E35) (Shutdown) iPhone 5 (9905A018-9DC9-4DD8-BA14-B0B000CC8622) (Shutdown) iPhone 5s (FD90588B-1020-45C5-8EE9-C5CF89A26A22) (Shutdown) iPhone 6 (9A224332-DF90-4A30-BB7B-D0ABFE2A658F) (Shutdown) iPhone 6 Plus (B12E4F8A-00DF-4DFA-AF0F-FCAD6C16CBDE) (Shutdown) iPad 2 (A9B8647B-1C6C-41D5-8B51-B2D0A7FD4549) (Shutdown) iPad Retina (39EAB2A5-FBF8-417C-9578-4C47125E6658) (Shutdown) iPad Air (1D37AF01-FA0A-485A-86CD-A5F26845C528) (Shutdown) iPad Air 2 (90FF95A9-CB0E-4670-B9C4-A9BC6500F4EA) (Shutdown) -- iOS 8.4 -- iPhone 4s (16764BF6-4E85-42CE-9C1E-E5B0185B49BD) (Shutdown) iPhone 5 (6636AA80-6030-468A-8650-479A1A11899A) (Shutdown) iPhone 5s (5E15A2AC-2787-4C8D-8FBA-DF09FD216326) (Shutdown) iPhone 6 (9842E17B-F831-4CEE-BF7A-90EC14A346B7) (Shutdown) iPhone 6 Plus (6B638BF3-773A-4604-BB4A-75C33138C371) (Shutdown) iPad 2 (D15D74A7-338D-4CCC-9FE4-158917220903) (Shutdown) iPad Retina (3482DB34-48FE-4166-9C85-C30042E82DFE) (Shutdown) iPad Air (CF1146F7-9C3C-490A-B41C-38D0674333E6) (Shutdown) -- tvOS 9.2 -- Apple TV 1080p (83C3BAF8-54AD-4403-A688-D0B6E58020AF) (Shutdown) -- watchOS 2.2 -- Apple Watch - 38mm (779DA803-15AF-4E18-86B1-F4BF94547891) (Shutdown) Apple Watch - 42mm (A6371161-FEEA-46E2-9382-0DB41C85FA70) (Shutdown) " FastlaneCore::Simulator.clear_cache response = "response" allow(response).to receive(:read).and_return(@valid_simulators) allow(Open3).to receive(:popen3).with("xcrun simctl list devices").and_yield(nil, response, nil, nil) allow(Open3).to receive(:capture3).with("xcrun simctl runtime -h").and_return([nil, 'Usage: simctl runtime <operation> <arguments>', nil]) allow(FastlaneCore::Helper).to receive(:xcode_at_least?).and_return(false) allow(FastlaneCore::CommandExecutor).to receive(:execute).with(command: "sw_vers -productVersion", print_all: false, print_command: false).and_return('10.12.1') allow(Scan).to receive(:project).and_return(@project) end context "with xcpretty" do before(:each) do allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false) end describe Scan::TestCommandGenerator do before(:each) do @test_command_generator = Scan::TestCommandGenerator.new @project.options.delete(:use_system_scm) end it "raises an exception when project path wasn't found" do tmp_path = Dir.mktmpdir path = "#{tmp_path}/notExistent" expect do options = { project: path } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end.to raise_error("Project file not found at path '#{path}'") end describe "Supports toolchain" do it "should fail if :xctestrun and :toolchain is set" do allow(FastlaneCore::FastlaneFolder).to receive(:path).and_return(".") expect do Fastlane::FastFile.new.parse("lane :test do scan( project: './scan/examples/standard/app.xcodeproj', xctestrun: './path/1.xctestrun', toolchain: 'com.apple.dt.toolchain.Swift_2_3' ) end").runner.execute(:test) end.to raise_error("Unresolved conflict between options: 'toolchain' and 'xctestrun'") end it "passes the toolchain option to xcodebuild", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", sdk: "9.0", toolchain: "com.apple.dt.toolchain.Swift_2_3" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-sdk '9.0'", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-toolchain 'com.apple.dt.toolchain.Swift_2_3'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", :build, :test ]) end end it "supports additional parameters", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") xcargs = { DEBUG: "1", BUNDLE_NAME: "Example App" } options = { project: "./scan/examples/standard/app.xcodeproj", sdk: "9.0", xcargs: xcargs } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-sdk '9.0'", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", "DEBUG=1 BUNDLE_NAME=Example\\ App", :build, :test ]) end describe "supports number of retries" do before(:each) do allow(FastlaneCore::Helper).to receive(:xcode_at_least?).and_return(true) end it "with 1 or more retries", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj", sdk: "9.0", number_of_retries: 1 } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-sdk '9.0'", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", "-retry-tests-on-failure", "-test-iterations 2", :build, :test ]) end end it "supports custom xcpretty formatter as a gem name", requires_xcodebuild: true do options = { formatter: "custom-formatter", project: "./scan/examples/standard/app.xcodeproj", sdk: "9.0" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result.last).to include("| xcpretty -f `custom-formatter`") end it "supports custom xcpretty formatter as a path to a ruby file", requires_xcodebuild: true do options = { formatter: "custom-formatter.rb", project: "./scan/examples/standard/app.xcodeproj", sdk: "9.0" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result.last).to include("| xcpretty -f 'custom-formatter.rb'") end it "uses system scm", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", use_system_scm: true } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to include("-scmProvider system").once end it "uses system scm via project options", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj" } @project.options[:use_system_scm] = true Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to include("-scmProvider system").once end it "uses system scm options exactly once", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", use_system_scm: true } @project.options[:use_system_scm] = true Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.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: "./scan/examples/standard/app.xcodeproj" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to_not(include("-scmProvider system")) end describe "Standard Example" do describe "Xcode project" do before do options = { project: "./scan/examples/standard/app.xcodeproj" } Scan.config = FastlaneCore::Configuration.create(Scan::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("~/Library/Logs/scan/app-app.log") result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", :build, :test ]) end it "#project_path_array", requires_xcodebuild: true do result = @test_command_generator.project_path_array expect(result).to eq(["-scheme app", "-project ./scan/examples/standard/app.xcodeproj"]) end it "#build_path", requires_xcodebuild: true do result = @test_command_generator.build_path regex = %r{Library/Developer/Xcode/Archives/\d\d\d\d\-\d\d\-\d\d} expect(result).to match(regex) end it "#buildlog_path is used when provided", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", buildlog_path: "/tmp/my/path" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.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 = @test_command_generator.xcodebuild_log_path expect(result.to_s).to include(File.expand_path("#{FastlaneCore::Helper.buildlog_path}/scan")) end end describe "SPM package" do describe "No workspace" do before do options = { package_path: "./scan/examples/package/", scheme: "package" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end it "uses the correct build command with the example package and scheme", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "cd ./scan/examples/package/ &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme package", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", :build, :test ]) end it "#project_path_array", requires_xcodebuild: true do result = @test_command_generator.project_path_array expect(result).to eq(["-scheme package"]) end end describe "With workspace" do before do options = { package_path: "./scan/examples/package/", scheme: "package", workspace: "." } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end it "uses the correct build command with the example package and scheme", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "cd ./scan/examples/package/ &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme package", "-workspace .", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", :build, :test ]) end it "#project_path_array", requires_xcodebuild: true do result = @test_command_generator.project_path_array expect(result).to eq(["-scheme package", "-workspace ."]) end end end end describe "Derived Data Example" do before do options = { project: "./scan/examples/standard/app.xcodeproj", derived_data_path: "/tmp/my/derived_data" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end it "uses the correct build command with the example project", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath /tmp/my/derived_data", :build, :test ]) end end describe "Test Parallel Testing" do # don't want to override settings defined in xcode unless explicitly asked to it "doesn't add option if not passed explicitly", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).not_to include("-parallel-testing-enabled YES") if FastlaneCore::Helper.xcode_at_least?(10) expect(result).not_to include("-parallel-testing-enabled NO") if FastlaneCore::Helper.xcode_at_least?(10) end it "specify YES when set to true", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj", parallel_testing: true } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to include("-parallel-testing-enabled YES") if FastlaneCore::Helper.xcode_at_least?(10) end it "specify NO when set to false", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj", parallel_testing: false } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to include("-parallel-testing-enabled NO") if FastlaneCore::Helper.xcode_at_least?(10) end end describe "Test Concurrent Workers" do before do options = { project: "./scan/examples/standard/app.xcodeproj", concurrent_workers: 4 } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end it "uses the correct number of concurrent workers", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") result = @test_command_generator.generate expect(result).to include("-parallel-testing-worker-count 4") if FastlaneCore::Helper.xcode_at_least?(10) end end describe "Test Max Concurrent Simulators" do before do options = { project: "./scan/examples/standard/app.xcodeproj", max_concurrent_simulators: 3 } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end it "uses the correct number of concurrent simulators", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") result = @test_command_generator.generate expect(result).to include("-maximum-concurrent-test-simulator-destinations 3") if FastlaneCore::Helper.xcode_at_least?(10) end end describe "Test Disable Concurrent Simulators" do before do options = { project: "./scan/examples/standard/app.xcodeproj", disable_concurrent_testing: true } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end it "disables concurrent simulators", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") result = @test_command_generator.generate expect(result).to include("-disable-concurrent-testing") if FastlaneCore::Helper.xcode_at_least?(10) end end describe "with Scan option :include_simulator_logs" do context "extract system.logarchive" do it "copies all device logs to the output directory", requires_xcodebuild: true do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', include_simulator_logs: true, devices: ["iPhone 6s", "iPad Air"], project: './scan/examples/standard/app.xcodeproj' }) Scan.cache[:temp_junit_report] = './scan/spec/fixtures/boring.log' # This is a needed side effect from running TestCommandGenerator which is not done in this test Scan.cache[:result_bundle_path] = '/tmp/scan_results/test.xcresults' expect(FastlaneCore::CommandExecutor). to receive(:execute). with(command: %r{xcrun simctl spawn 021A465B-A294-4D9E-AD07-6BDC8E186343 log collect --start '\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d' --output /tmp/scan_results/system_logs-iPhone\\ 6s_iOS_10.0.logarchive 2>/dev/null}, print_all: false, print_command: true) expect(FastlaneCore::CommandExecutor). to receive(:execute). with(command: %r{xcrun simctl spawn 2ABEAF08-E480-4617-894F-6BAB587E7963 log collect --start '\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d' --output /tmp/scan_results/system_logs-iPad\\ Air_iOS_10.0.logarchive 2>/dev/null}, print_all: false, print_command: true) allow(Trainer::TestParser).to receive(:auto_convert).and_return({ "some/path": { successful: true, number_of_tests: 100, number_of_failures: 0, number_of_tests_excluding_retries: 10, number_of_failures_excluding_retries: 0, number_of_retries: 0 } }) mock_test_result_parser = Object.new allow(Scan::TestResultParser).to receive(:new).and_return(mock_test_result_parser) allow(mock_test_result_parser).to receive(:parse_result).and_return({ tests: 100, failures: 0 }) mock_slack_poster = Object.new allow(Scan::SlackPoster).to receive(:new).and_return(mock_slack_poster) allow(mock_slack_poster).to receive(:run) mock_test_command_generator = Object.new allow(Scan::TestCommandGenerator).to receive(:new).and_return(mock_test_command_generator) allow(mock_test_command_generator).to receive(:xcodebuild_log_path).and_return('./scan/spec/fixtures/boring.log') Scan::Runner.new.handle_results(0) end end end describe "Result Bundle Example" do it "uses the correct build command with the example project when using Xcode 10 or earlier", requires_xcodebuild: true do allow(FastlaneCore::Helper).to receive(:xcode_version).and_return('10') log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj", result_bundle: true, scheme: 'app' } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", "-resultBundlePath ./fastlane/test_output/app.test_result", :build, :test ]) end it "uses the correct build command with the example project when using Xcode 11 or later", requires_xcodebuild: true do allow(FastlaneCore::Helper).to receive(:xcode_version).and_return('11') log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj", result_bundle: true, scheme: 'app' } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", "-resultBundlePath ./fastlane/test_output/app.xcresult", :build, :test ]) end it "uses the correct build command with the example project when using Xcode 11 or later and a custom result bundle path", requires_xcodebuild: true do allow(FastlaneCore::Helper).to receive(:xcode_version).and_return('11') log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj", result_bundle_path: "./my_test_output/Alice's Man$ion backtick` quote\" 2024-09-30 at 5.10.35 PM (1).xcresult", scheme: 'app' } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", "-resultBundlePath ./my_test_output/Alice\\'s\\ Man\\$ion\\ backtick\\`\\ quote\\\"\\ 2024-09-30\\ at\\ 5.10.35\\ PM\\ \\(1\\).xcresult", :build, :test ]) end end describe "Test Exclusion Example" do it "only tests the test bundle/suite/cases specified in only_testing when the input is an array", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj", scheme: 'app', only_testing: %w(TestBundleA/TestSuiteB TestBundleC) } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", '-only-testing:TestBundleA/TestSuiteB', '-only-testing:TestBundleC', :build, :test ]) end it "only tests the test bundle/suite/cases specified in only_testing when the input is a string", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj", scheme: 'app', only_testing: 'TestBundleA/TestSuiteB' } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to start_with([ "set -o pipefail &&", "env NSUnbufferedIO=YES xcodebuild", "-scheme app", "-project ./scan/examples/standard/app.xcodeproj", "-destination 'platform=iOS Simulator,id=E697990C-3A83-4C01-83D1-C367011B31EE'", "-derivedDataPath #{Scan.config[:derived_data_path].shellescape}", '-only-testing:TestBundleA/TestSuiteB', :build, :test ]) end it "does not the test bundle/suite/cases specified in skip_testing when the input is an array", requires_xcodebuild: true do log_path = File.expand_path("~/Library/Logs/scan/app-app.log") options = { project: "./scan/examples/standard/app.xcodeproj", scheme: 'app', skip_testing: %w(TestBundleA/TestSuiteB TestBundleC) } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) result = @test_command_generator.generate expect(result).to start_with([
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
true
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/spec/test_result_parser_spec.rb
scan/spec/test_result_parser_spec.rb
describe Scan do describe Scan::TestResultParser do it "properly parses the xcodebuild output" do output = "<?xml version='1.0' encoding='UTF-8'?> <testsuites tests='2' failures='1'> <testsuite name='appTests' tests='2' failures='1'> <testcase classname='appTests' name='testExample'> <failure message='((1 == 2 - 4) is true) failed'>appTests/appTests.m:30</failure> </testcase> <testcase classname='appTests' name='testPerformanceExample' time='0.262'/> </testsuite> </testsuites>" result = Scan::TestResultParser.new.parse_result(output) expect(result).to eq({ tests: 2, failures: 1 }) end it "properly parses the xcodebuild output when the properties are in a different order" do output = "<?xml version='1.0' encoding='UTF-8'?> <testsuites failures='1' tests='2'> <testsuite name='appTests' tests='2' failures='1'> <testcase classname='appTests' name='testExample'> <failure message='((1 == 2 - 4) is true) failed'>appTests/appTests.m:30</failure> </testcase> <testcase classname='appTests' name='testPerformanceExample' time='0.262'/> </testsuite> </testsuites>" result = Scan::TestResultParser.new.parse_result(output) expect(result).to eq( tests: 2, failures: 1 ) end it "properly parses the xcodebuild output" do output = "<?xml version='1.0' encoding='UTF-8'?> <testsuites tests='2' failures='1'/>" result = Scan::TestResultParser.new.parse_result(output) expect(result).to eq( tests: 2, failures: 1 ) end it "properly parses the xcodebuild output when there are extra properties" do output = "<?xml version='1.0' encoding='UTF-8'?> <testsuites foo='1' tests='2' bar='3' failures='1' baz='4'> <testsuite name='appTests' tests='2' failures='1'> <testcase classname='appTests' name='testExample'> <failure message='((1 == 2 - 4) is true) failed'>appTests/appTests.m:30</failure> </testcase> <testcase classname='appTests' name='testPerformanceExample' time='0.262'/> </testsuite> </testsuites>" result = Scan::TestResultParser.new.parse_result(output) expect(result).to eq( tests: 2, failures: 1 ) end it "returns early if the xcodebuild output is nil" do output = nil result = Scan::TestResultParser.new.parse_result(output) expect(result).to eq( tests: 0, failures: 0 ) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/spec/xcpretty_reporter_options_generator_spec.rb
scan/spec/xcpretty_reporter_options_generator_spec.rb
describe Scan do describe Scan::XCPrettyReporterOptionsGenerator, requires_xcodebuild: true do before(:all) do options = { project: "./scan/examples/standard/app.xcodeproj" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) Scan.cache[:temp_junit_report] = nil end describe "xcpretty reporter options generation" do it "generates options for the junit tempfile report required by scan" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html", "report.html", "/test_output", false, nil) reporter_options = generator.generate_reporter_options temp_junit_report = Scan.cache[:temp_junit_report] expect(temp_junit_report).not_to(be_nil) expect(reporter_options).to end_with([ "--report junit", "--output '#{temp_junit_report}'" ]) end it "generates options for a custom junit report with default file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "junit", nil, "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report junit", "--output '/test_output/report.junit'" ]) end it "generates options for a custom junit report with custom file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "junit", "junit.xml", "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report junit", "--output '/test_output/junit.xml'" ]) end it "generates options for a custom html report with default file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html", nil, "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report html", "--output '/test_output/report.html'" ]) end it "generates options for a custom html report with custom file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html", "custom_report.html", "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report html", "--output '/test_output/custom_report.html'" ]) end it "generates options for a custom json-compilation-database file with default file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "json-compilation-database", nil, "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report json-compilation-database", "--output '/test_output/report.json-compilation-database'" ]) end it "generates options for a custom json-compilation-database file with a custom file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "json-compilation-database", "custom_report.json", "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report json-compilation-database", "--output '/test_output/custom_report.json'" ]) end it "generates options for a custom json-compilation-database file with a clang naming convention" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "json-compilation-database", "ignore_custom_name_here.json", "/test_output", true, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report json-compilation-database", "--output '/test_output/compile_commands.json'" ]) end it "generates options for a multiple reports with default file names" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html,junit", nil, "/test_output", true, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report html", "--output '/test_output/report.html'", "--report junit", "--output '/test_output/report.junit'" ]) end it "generates options for a multiple reports with default file names" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html,junit", "custom_report.html,junit.xml", "/test_output", true, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report html", "--output '/test_output/custom_report.html'", "--report junit", "--output '/test_output/junit.xml'" ]) end context "options passed as arrays" do it "generates options for the junit tempfile report required by scan" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["html"], ["report.html"], "test_output", false, nil) reporter_options = generator.generate_reporter_options temp_junit_report = Scan.cache[:temp_junit_report] expect(temp_junit_report).not_to(be_nil) expect(reporter_options).to end_with([ "--report junit", "--output '#{temp_junit_report}'" ]) end it "generates options for a custom junit report with default file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["junit"], nil, "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report junit", "--output '/test_output/report.junit'" ]) end it "generates options for a custom junit report with custom file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["junit"], ["junit.xml"], "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report junit", "--output '/test_output/junit.xml'" ]) end it "generates options for a custom html report with default file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["html"], nil, "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report html", "--output '/test_output/report.html'" ]) end it "generates options for a custom html report with custom file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["html"], ["custom_report.html"], "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report html", "--output '/test_output/custom_report.html'" ]) end it "generates options for a custom json-compilation-database file with default file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["json-compilation-database"], nil, "/test_output", false, nil) reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report json-compilation-database", "--output '/test_output/report.json-compilation-database'" ]) end it "generates options for a custom json-compilation-database file with a custom file name" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["json-compilation-database"], ["custom_report.json"], "/test_output", false, "") reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report json-compilation-database", "--output '/test_output/custom_report.json'" ]) end it "generates options for a custom json-compilation-database file with a clang naming convention" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["json-compilation-database"], ["ignore_custom_name_here.json"], "/test_output", true, "") reporter_options = generator.generate_reporter_options expect(reporter_options).to include("--report json-compilation-database") expect(reporter_options).to include("--output '/test_output/compile_commands.json'") expect(reporter_options).to start_with([ "--report json-compilation-database", "--output '/test_output/compile_commands.json'" ]) end it "generates options for a multiple reports with default file names" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["html", "junit"], nil, "/test_output", true, "") reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report html", "--output '/test_output/report.html'", "--report junit", "--output '/test_output/report.junit'" ]) end it "generates options for a multiple reports with custom file names" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, ["html", "junit"], ["custom_report.html", "junit.xml"], "/test_output", true, "") reporter_options = generator.generate_reporter_options expect(reporter_options).to start_with([ "--report html", "--output '/test_output/custom_report.html'", "--report junit", "--output '/test_output/junit.xml'" ]) end end describe "xcpretty format options generation" do it "generates options to use xcpretty's `test` format option" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html", "report.html", "/test_output", false, "--test") reporter_options = generator.generate_xcpretty_args_options expect(reporter_options).to end_with("--test") end it "generates options to use xcpretty's `simple` format option" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html", "report.html", "/test_output", false, "--simple") reporter_options = generator.generate_xcpretty_args_options expect(reporter_options).to end_with("--simple") end it "generates options to use xcpretty's `tap` format option and ASCII format" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html", "report.html", "/test_output", false, "--tap --no-utf") reporter_options = generator.generate_xcpretty_args_options expect(reporter_options).to end_with("--tap --no-utf") end it "generates options to use xcpretty's `knock` format option and color format" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html", "report.html", "/test_output", false, "--knock --color") reporter_options = generator.generate_xcpretty_args_options expect(reporter_options).to end_with("--knock --color") end it "generates valid options when no xcpretty arguments specified" do generator = Scan::XCPrettyReporterOptionsGenerator.new(false, "html", "report.html", "/test_output", false, nil) reporter_options = generator.generate_xcpretty_args_options expect(reporter_options).to be_nil end end context "generator created from Scan.config" do it "generates options for a single reports while using custom_report_file_name" do options = { project: "./scan/examples/standard/app.xcodeproj", output_types: "junit,html", output_files: "junit.xml", output_directory: "/test_output" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) Scan.cache[:temp_junit_report] = nil expect(FastlaneCore::UI).to receive(:important).with("WARNING: output_types and output_files do not have the same number of items. Default values will be substituted as needed.") reporter_options = Scan::XCPrettyReporterOptionsGenerator.generate_from_scan_config.generate_reporter_options expect(reporter_options).to eq([ "--report junit", "--output '/test_output/junit.xml'", "--report html", "--output '/test_output/report.html'", "--report junit", "--output '#{Scan.cache[:temp_junit_report]}'" ]) end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/spec/runner_spec.rb
scan/spec/runner_spec.rb
require 'scan' describe Scan do describe Scan::Runner do describe "handle_results" do before(:each) do mock_slack_poster = Object.new allow(Scan::SlackPoster).to receive(:new).and_return(mock_slack_poster) allow(mock_slack_poster).to receive(:run) mock_test_command_generator = Object.new allow(Scan::TestCommandGenerator).to receive(:new).and_return(mock_test_command_generator) allow(mock_test_command_generator).to receive(:xcodebuild_log_path).and_return('./scan/spec/fixtures/boring.log') mock_test_result_parser = Object.new allow(Scan::TestResultParser).to receive(:new).and_return(mock_test_result_parser) allow(mock_test_result_parser).to receive(:parse_result).and_return({ tests: 100, failures: 0 }) allow(Trainer::TestParser).to receive(:auto_convert).and_return({ "some/path": { successful: true, number_of_tests: 10, number_of_failures: 0, number_of_tests_excluding_retries: 10, number_of_failures_excluding_retries: 0, number_of_retries: 0 } }) @scan = Scan::Runner.new end describe "with scan option :include_simulator_logs set to false" do it "does not copy any device logs to the output directory", requires_xcodebuild: true do # Circle CI is setting the SCAN_INCLUDE_SIMULATOR_LOGS env var, so just leaving # the include_simulator_logs option out does not let it default to false Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', project: './scan/examples/standard/app.xcodeproj', include_simulator_logs: false }) # This is a needed side effect from running TestCommandGenerator which is not done in this test Scan.cache[:result_bundle_path] = '/tmp/scan_results/test.xcresults' expect(FastlaneCore::Simulator).not_to(receive(:copy_logs)) @scan.handle_results(0) end end describe "with scan option :include_simulator_logs set to true" do it "copies any device logs to the output directory", requires_xcodebuild: true do # Circle CI is setting the SCAN_INCLUDE_SIMULATOR_LOGS env var, so just leaving # the include_simulator_logs option out does not let it default to false Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', project: './scan/examples/standard/app.xcodeproj', include_simulator_logs: true }) # This is a needed side effect from running TestCommandGenerator which is not done in this test Scan.cache[:result_bundle_path] = '/tmp/scan_results/test.xcresults' expect(FastlaneCore::Simulator).to receive(:copy_logs) @scan.handle_results(0) end end describe "Test Failure" do it "raises a FastlaneTestFailure instead of a crash or UserError", requires_xcodebuild: true do expect do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', project: './scan/examples/standard/app.xcodeproj' }) # This is a needed side effect from running TestCommandGenerator which is not done in this test Scan.cache[:result_bundle_path] = '/tmp/scan_results/test.xcresults' allow(Trainer::TestParser).to receive(:auto_convert).and_return({ "some/path": { successful: true, number_of_tests: 10, number_of_failures: 1, number_of_tests_excluding_retries: 10, number_of_failures_excluding_retries: 1, number_of_retries: 0 } }) @scan.handle_results(0) end.to raise_error(FastlaneCore::Interface::FastlaneTestFailure, "Tests have failed") end end describe "when handling result" do it "returns output if fail_build is false", requires_xcodebuild: true do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', project: './scan/examples/standard/app.xcodeproj', fail_build: false }) # This is a needed side effect from running TestCommandGenerator which is not done in this test Scan.cache[:result_bundle_path] = '/tmp/scan_results/test.xcresults' allow(Trainer::TestParser).to receive(:auto_convert).and_return({ "some/path": { successful: true, number_of_tests: 10, number_of_failures: 1, number_of_tests_excluding_retries: 10, number_of_failures_excluding_retries: 1, number_of_retries: 0 } }) expect(@scan.handle_results(0)).to eq({ number_of_tests: 10, number_of_failures: 1, number_of_skipped: 0, number_of_tests_excluding_retries: 10, number_of_failures_excluding_retries: 1, number_of_retries: 0 }) end end describe "with scan option :disable_xcpretty set to true" do it "does not generate a temp junit report", requires_xcodebuild: true do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', project: './scan/examples/standard/app.xcodeproj', disable_xcpretty: true }) # This is a needed side effect from running TestCommandGenerator which is not done in this test Scan.cache[:result_bundle_path] = '/tmp/scan_results/test.xcresults' Scan.cache[:temp_junit_report] = '/var/folders/non_existent_file.junit' @scan.handle_results(0) expect(Scan.cache[:temp_junit_report]).to(eq('/var/folders/non_existent_file.junit')) end it "fails if tests_exit_status is not 0", requires_xcodebuild: true do expect do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', project: './scan/examples/standard/app.xcodeproj', disable_xcpretty: true }) # This is a needed side effect from running TestCommandGenerator which is not done in this test Scan.cache[:result_bundle_path] = '/tmp/scan_results/test.xcresults' @scan.handle_results(1) end.to raise_error(FastlaneCore::Interface::FastlaneTestFailure, "Test execution failed. Exit status: 1") end end end describe "retry_execute" do before(:each) do @scan = Scan::Runner.new end it "retry a failed test", requires_xcodebuild: true do error_output = <<-ERROR_OUTPUT Failing tests: FastlaneAppTests: FastlaneAppTests.testCoinToss() -[FastlaneAppTestsOC testCoinTossOC] ERROR_OUTPUT expect(Fastlane::UI).to receive(:important).with("Retrying tests: FastlaneAppTests/FastlaneAppTests/testCoinToss, FastlaneAppTests/FastlaneAppTestsOC/testCoinTossOC").once expect(Fastlane::UI).to receive(:important).with("Number of retries remaining: 4").once expect(@scan).to receive(:execute) @scan.retry_execute(retries: 5, error_output: error_output) end it "retry a failed test when project scheme name has non-whitespace character", requires_xcodebuild: true do error_output = <<-ERROR_OUTPUT Failing tests: Fastlane-App-Tests: FastlaneAppTests.testCoinToss() -[FastlaneAppTestsOC testCoinTossOC] ERROR_OUTPUT expect(Fastlane::UI).to receive(:important).with("Retrying tests: Fastlane-App-Tests/FastlaneAppTests/testCoinToss, Fastlane-App-Tests/FastlaneAppTestsOC/testCoinTossOC").once expect(Fastlane::UI).to receive(:important).with("Number of retries remaining: 4").once expect(@scan).to receive(:execute) @scan.retry_execute(retries: 5, error_output: error_output) end it "fail to parse error output", requires_xcodebuild: true do error_output = <<-ERROR_OUTPUT Failing tests: FastlaneAppTests: FastlaneAppTests.testCoinToss() -[FastlaneAppTestsOC testCoinTossOC] ERROR_OUTPUT expect do @scan.retry_execute(retries: 5, error_output: error_output) end.to raise_error(FastlaneCore::Interface::FastlaneBuildFailure, "Failed to find failed tests to retry (could not parse error output)") end end describe "test_results" do before(:each) do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', project: './scan/examples/standard/app.xcodeproj', include_simulator_logs: false }) mock_slack_poster = Object.new allow(Scan::SlackPoster).to receive(:new).and_return(mock_slack_poster) allow(mock_slack_poster).to receive(:run) mock_test_command_generator = Object.new allow(Scan::TestCommandGenerator).to receive(:new).and_return(mock_test_command_generator) allow(mock_test_command_generator).to receive(:xcodebuild_log_path).and_return('./scan/spec/fixtures/boring.log') @scan = Scan::Runner.new end it "still proceeds successfully if the temp junit report was deleted", requires_xcodebuild: true do Scan.cache[:temp_junit_report] = '/var/folders/non_existent_file.junit' expect(@scan.test_results).to_not(be_nil) expect(Scan.cache[:temp_junit_report]).to_not(eq('/var/folders/non_existent_file.junit')) end describe "when output_style is raw" do it "still proceeds successfully and generates a temp junit report", requires_xcodebuild: true do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', project: './scan/examples/standard/app.xcodeproj', include_simulator_logs: false, output_style: "raw" }) Scan.cache[:temp_junit_report] = '/var/folders/non_existent_file.junit' expect(@scan.test_results).to_not(be_nil) expect(Scan.cache[:temp_junit_report]).to_not(eq('/var/folders/non_existent_file.junit')) end end end describe "#zip_build_products" do it "doesn't zip data when :should_zip_build_products is false", requires_xcodebuild: true do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', project: './scan/examples/standard/app.xcodeproj', should_zip_build_products: false }) expect(FastlaneCore::Helper).to receive(:backticks).with(anything).exactly(0).times scan = Scan::Runner.new scan.zip_build_products end it "zips data when :should_zip_build_products is true", requires_xcodebuild: true do Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { output_directory: '/tmp/scan_results', derived_data_path: '/tmp/derived_data/app', project: './scan/examples/standard/app.xcodeproj', should_zip_build_products: true }) path = File.join(Scan.config[:derived_data_path], "Build/Products") path = File.absolute_path(path) output_path = File.absolute_path('/tmp/scan_results/build_products.zip') expect(FastlaneCore::Helper).to receive(:backticks) .with("cd '#{path}' && rm -f '#{output_path}' && zip -r '#{output_path}' *", { print: false }) .exactly(1).times scan = Scan::Runner.new scan.zip_build_products end end describe "output_xctestrun" do it "copies .xctestrun file when :output_xctestrun is true", requires_xcodebuild: true do Dir.mktmpdir("scan_results") do |tmp_dir| # Configuration Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, { derived_data_path: File.join(tmp_dir, 'derived_data'), output_directory: File.join(tmp_dir, 'output'), project: './scan/examples/standard/app.xcodeproj', output_xctestrun: true }) # Make output directory FileUtils.mkdir_p(Scan.config[:output_directory]) # Make derived data directory path = File.join(Scan.config[:derived_data_path], "Build/Products") FileUtils.mkdir_p(path) # Create .xctestrun file that will be copied xctestrun_path = File.join(path, 'something-project-something.xctestrun') FileUtils.touch(xctestrun_path) scan = Scan::Runner.new scan.copy_xctestrun output_path = File.join(Scan.config[:output_directory], 'settings.xctestrun') expect(File.file?(output_path)).to eq(true) end end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/spec/detect_values_spec.rb
scan/spec/detect_values_spec.rb
describe Scan do describe Scan::DetectValues do describe 'Xcode project' do describe 'detects FastlaneCore::Project' do it 'with no :project or :package_path given', requires_xcodebuild: true do # Mocks input from detect_projects project = FastlaneCore::Project.new({ project: "./scan/examples/standard/app.xcodeproj" }) expect(FastlaneCore::Project).to receive(:detect_projects) expect(FastlaneCore::Project).to receive(:new).and_return(project) options = {} Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end it 'with :project given', requires_xcodebuild: true do expect(FastlaneCore::Project).to receive(:detect_projects) expect(FastlaneCore::Project).to receive(:new).and_call_original options = { project: "./scan/examples/standard/app.xcodeproj" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end end end describe 'SPM package' do describe 'does not attempt to detect FastlaneCore::Project' do it 'with :package_path given', requires_xcodebuild: true do expect(FastlaneCore::Project).to_not(receive(:detect_projects)) options = { package_path: "./scan/examples/package/" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end end end describe 'Xcode config handling' do before do options = { project: "./scan/examples/standard/app.xcodeproj" } FileUtils.mkdir_p("./scan/examples/standard/app.xcodeproj/project.xcworkspace/xcuserdata/#{ENV['USER']}.xcuserdatad/") FileUtils.copy("./scan/examples/standard/WorkspaceSettings.xcsettings", "./scan/examples/standard/app.xcodeproj/project.xcworkspace/xcuserdata/#{ENV['USER']}.xcuserdatad/WorkspaceSettings.xcsettings") Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) @project = FastlaneCore::Project.new(Scan.config) end it "fetches the path from the Xcode config", requires_xcodebuild: true do derived_data = Scan.config[:derived_data_path] expect(derived_data).to match(File.expand_path("./scan/examples/standard/")) end end describe "#default_os_version" do before do Scan::DetectValues.clear_cache end it 'informs users of unknown platform name' do expect do Scan::DetectValues.default_os_version('test') end.to raise_error(FastlaneCore::Interface::FastlaneCrash, "Unknown platform: test") end it 'returns an error if `xcrun simctl runtime -h` is broken' do help_output = 'garbage' allow(Open3).to receive(:capture3).with('xcrun simctl runtime -h').and_return([nil, help_output, nil]) expect do Scan::DetectValues.default_os_version('iOS') end.to raise_error(FastlaneCore::Interface::FastlaneError) end it 'returns an error if `xcodebuild -showsdks -json` is broken' do help_output = 'Usage: simctl runtime <operation> <arguments> match list' allow(Open3).to receive(:capture3).with('xcrun simctl runtime -h').and_return([nil, help_output, nil]) sdks_output = 'unexpected output' status = double('status', "success?": true) allow(Open3).to receive(:capture2).with('xcodebuild -showsdks -json').and_return([sdks_output, status]) expect do Scan::DetectValues.default_os_version('iOS') end.to raise_error(FastlaneCore::Interface::FastlaneError) end it 'returns an error if `xcodebuild -showsdks -json` exits unsuccessfully' do help_output = 'Usage: simctl runtime <operation> <arguments> match list' allow(Open3).to receive(:capture3).with('xcrun simctl runtime -h').and_return([nil, help_output, nil]) sdks_output = File.read('./scan/spec/fixtures/XcodebuildSdksOutput15') status = double('status', "success?": false) allow(Open3).to receive(:capture2).with('xcodebuild -showsdks -json').and_return([sdks_output, status]) expect do Scan::DetectValues.default_os_version('iOS') end.to raise_error(FastlaneCore::Interface::FastlaneError) end it 'returns an error if `xcrun simctl runtime match list -j` is broken' do help_output = 'Usage: simctl runtime <operation> <arguments> match list' allow(Open3).to receive(:capture3).with('xcrun simctl runtime -h').and_return([nil, help_output, nil]) sdks_output = File.read('./scan/spec/fixtures/XcodebuildSdksOutput15') status = double('status', "success?": true) allow(Open3).to receive(:capture2).with('xcodebuild -showsdks -json').and_return([sdks_output, status]) runtime_output = 'unexpected output' allow(Open3).to receive(:capture2).with('xcrun simctl runtime match list -j').and_return([runtime_output, status]) expect do Scan::DetectValues.default_os_version('iOS') end.to raise_error(FastlaneCore::Interface::FastlaneError) end it 'returns an error if `xcrun simctl runtime match list -j` exits unsuccessfully' do help_output = 'Usage: simctl runtime <operation> <arguments> match list' allow(Open3).to receive(:capture3).with('xcrun simctl runtime -h').and_return([nil, help_output, nil]) sdks_output = File.read('./scan/spec/fixtures/XcodebuildSdksOutput15') success_status = double('status', "success?": true) allow(Open3).to receive(:capture2).with('xcodebuild -showsdks -json').and_return([sdks_output, success_status]) fail_status = double('fail_status', "success?": false) runtime_output = File.read('./scan/spec/fixtures/XcrunSimctlRuntimeMatchListOutput15') allow(Open3).to receive(:capture2).with('xcrun simctl runtime match list -j').and_return([runtime_output, fail_status]) expect do Scan::DetectValues.default_os_version('iOS') end.to raise_error(FastlaneCore::Interface::FastlaneError) end build_os_versions = { "21J353" => "17.0", "21R355" => "10.0", "21A342" => "17.0.1" } actual_os_versions = { "tvOS" => "17.0", "watchOS" => "10.0", "iOS" => "17.0.1" } %w[iOS tvOS watchOS].each do |os_type| it "retrieves the correct runtime build for #{os_type}" do help_output = 'Usage: simctl runtime <operation> <arguments> match list' allow(Open3).to receive(:capture3).with('xcrun simctl runtime -h').and_return([nil, help_output, nil]) sdks_output = File.read('./scan/spec/fixtures/XcodebuildSdksOutput15') status = double('status', "success?": true) allow(Open3).to receive(:capture2).with('xcodebuild -showsdks -json').and_return([sdks_output, status]) runtime_output = File.read('./scan/spec/fixtures/XcrunSimctlRuntimeMatchListOutput15') allow(Open3).to receive(:capture2).with('xcrun simctl runtime match list -j').and_return([runtime_output, status]) allow(FastlaneCore::DeviceManager).to receive(:runtime_build_os_versions).and_return(build_os_versions) expect(Scan::DetectValues.default_os_version(os_type)).to eq(Gem::Version.new(actual_os_versions[os_type])) end end end describe "#detect_simulator" do it 'returns simulators for requested devices', requires_xcodebuild: true do simctl_list_devices_output = double('xcrun simctl list devices', read: File.read("./scan/spec/fixtures/XcrunSimctlListDevicesOutput15")) allow(Open3).to receive(:popen3).with("xcrun simctl list devices").and_yield(nil, simctl_list_devices_output, nil, nil) allow(Scan::DetectValues).to receive(:default_os_version).with('iOS').and_return(Gem::Version.new('17.0')) allow(Scan::DetectValues).to receive(:default_os_version).with('tvOS').and_return(Gem::Version.new('17.0')) allow(Scan::DetectValues).to receive(:default_os_version).with('watchOS').and_return(Gem::Version.new('10.0')) devices = ['iPhone 14 Pro Max', 'Apple TV 4K (3rd generation)', 'Apple Watch Ultra (49mm)'] simulators = Scan::DetectValues.detect_simulator(devices, '', '', '', nil) expect(simulators.count).to eq(3) expect(simulators[0]).to have_attributes( name: "iPhone 14 Pro Max", os_type: "iOS", os_version: "17.0" ) expect(simulators[1]).to have_attributes( name: "Apple TV 4K (3rd generation)", os_type: "tvOS", os_version: "17.0" ) expect(simulators[2]).to have_attributes( name: "Apple Watch Ultra (49mm)", os_type: "watchOS", os_version: "10.0" ) end it 'filters out simulators newer than what the current Xcode SDK supports', requires_xcodebuild: true do simctl_list_devices_output = double('xcrun simctl list devices', read: File.read("./scan/spec/fixtures/XcrunSimctlListDevicesOutput14")) allow(Open3).to receive(:popen3).with("xcrun simctl list devices").and_yield(nil, simctl_list_devices_output, nil, nil) allow(Scan::DetectValues).to receive(:default_os_version).with('iOS').and_return(Gem::Version.new('16.4')) allow(Scan::DetectValues).to receive(:default_os_version).with('tvOS').and_return(Gem::Version.new('16.4')) allow(Scan::DetectValues).to receive(:default_os_version).with('watchOS').and_return(Gem::Version.new('9.4')) devices = ['iPhone 14 Pro Max', 'iPad Pro (12.9-inch) (6th generation) (16.1)', 'Apple TV 4K (3rd generation)', 'Apple Watch Ultra (49mm)'] simulators = Scan::DetectValues.detect_simulator(devices, '', '', '', nil) expect(simulators.count).to eq(4) expect(simulators[0]).to have_attributes( name: "iPhone 14 Pro Max", os_type: "iOS", os_version: "16.4" ) expect(simulators[1]).to have_attributes( name: "iPad Pro (12.9-inch) (6th generation)", os_type: "iOS", os_version: "16.1" ) expect(simulators[2]).to have_attributes( name: "Apple TV 4K (3rd generation)", os_type: "tvOS", os_version: "16.4" ) expect(simulators[3]).to have_attributes( name: "Apple Watch Ultra (49mm)", os_type: "watchOS", os_version: "9.4" ) end end describe "#detect_destination" do it "ios", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:destination].first).to match(/platform=iOS/) end context "catalyst" do it "ios", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj" } expect_any_instance_of(FastlaneCore::Project).not_to receive(:supports_mac_catalyst?) Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:destination].first).to match(/platform=iOS/) end it "mac", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", catalyst_platform: "macos" } expect_any_instance_of(FastlaneCore::Project).to receive(:supports_mac_catalyst?).and_return(true) Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:destination].first).to match(/platform=macOS,variant=Mac Catalyst/) end end context ":run_rosetta_simulator" do it "adds arch=x86_64 if true", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", run_rosetta_simulator: true } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:destination].first).to match(/platform=iOS/) expect(Scan.config[:destination].first).to match(/,arch=x86_64/) end it "does not add arch=x86_64 if false", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", run_rosetta_simulator: false } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:destination].first).to match(/platform=iOS/) expect(Scan.config[:destination].first).to_not(match(/,arch=x86_64/)) end it "does not add arch=x86_64 by default", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:destination].first).to match(/platform=iOS/) expect(Scan.config[:destination].first).to_not(match(/,arch=x86_64/)) end end end describe "validation" do before(:each) do allow(Fastlane::Helper::XcodebuildFormatterHelper).to receive(:xcbeautify_installed?).and_return(false) end it "advises of problems with multiple output_types and a custom_report_file_name", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", # use default output types custom_report_file_name: 'report.xml' } expect(FastlaneCore::UI).to receive(:user_error!).with("Using a :custom_report_file_name with multiple :output_types (html,junit) will lead to unexpected results. Use :output_files instead.") Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end it "does not advise of a problem with one output_type and a custom_report_file_name", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", output_types: 'junit', custom_report_file_name: 'report.xml' } expect(FastlaneCore::UI).not_to(receive(:user_error!)) Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) end end describe "value coercion" do it "coerces only_testing to be an array", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", only_testing: "Bundle/SuiteA" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:only_testing]).to eq(["Bundle/SuiteA"]) end it "coerces skip_testing to be an array", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", skip_testing: "Bundle/SuiteA,Bundle/SuiteB" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:skip_testing]).to eq(["Bundle/SuiteA", "Bundle/SuiteB"]) end it "leaves skip_testing as an array", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", skip_testing: ["Bundle/SuiteA", "Bundle/SuiteB"] } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:skip_testing]).to eq(["Bundle/SuiteA", "Bundle/SuiteB"]) end it "coerces only_test_configurations to be an array", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", only_test_configurations: "ConfigurationA" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:only_test_configurations]).to eq(["ConfigurationA"]) end it "coerces skip_test_configurations to be an array", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", skip_test_configurations: "ConfigurationA,ConfigurationB" } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:skip_test_configurations]).to eq(["ConfigurationA", "ConfigurationB"]) end it "leaves skip_test_configurations as an array", requires_xcodebuild: true do options = { project: "./scan/examples/standard/app.xcodeproj", skip_test_configurations: ["ConfigurationA", "ConfigurationB"] } Scan.config = FastlaneCore::Configuration.create(Scan::Options.available_options, options) expect(Scan.config[:skip_test_configurations]).to eq(["ConfigurationA", "ConfigurationB"]) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/spec/spec_helper.rb
scan/spec/spec_helper.rb
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan.rb
scan/lib/scan.rb
require_relative 'scan/manager' require_relative 'scan/options' require_relative 'scan/runner' require_relative 'scan/detect_values' require_relative 'scan/test_command_generator' require_relative 'scan/xcpretty_reporter_options_generator.rb' require_relative 'scan/test_result_parser' require_relative 'scan/error_handler' require_relative 'scan/slack_poster' require_relative 'scan/module'
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/test_command_generator.rb
scan/lib/scan/test_command_generator.rb
require_relative 'xcpretty_reporter_options_generator' module Scan # Responsible for building the fully working xcodebuild command class TestCommandGenerator def generate parts = prefix parts << Scan.config[:xcodebuild_command] parts += options parts += actions parts += suffix parts += pipe parts end def prefix prefixes = ["set -o pipefail &&"] package_path = Scan.config[:package_path] prefixes << "cd #{package_path} &&" if package_path.to_s != "" prefixes 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 unless Scan.config[:package_path].nil? params = [] params << "-scheme #{Scan.config[:scheme].shellescape}" if Scan.config[:scheme] params << "-workspace #{Scan.config[:workspace].shellescape}" if Scan.config[:workspace] return params end proj = Scan.project.xcodebuild_parameters return proj if proj.count > 0 UI.user_error!("No project/workspace found") end def options # rubocop:disable Metrics/PerceivedComplexity config = Scan.config options = [] options += project_path_array unless config[:xctestrun] options << "-sdk '#{config[:sdk]}'" if config[:sdk] options << destination if destination # generated in `detect_values` options << "-toolchain '#{config[:toolchain]}'" if config[:toolchain] if config[:derived_data_path] && !options.include?("-derivedDataPath #{config[:derived_data_path].shellescape}") options << "-derivedDataPath #{config[:derived_data_path].shellescape}" end if config[:use_system_scm] && !options.include?("-scmProvider system") options << "-scmProvider system" end if config[:result_bundle_path] options << "-resultBundlePath #{config[:result_bundle_path].shellescape}" Scan.cache[:result_bundle_path] = config[:result_bundle_path] elsif config[:result_bundle] options << "-resultBundlePath #{result_bundle_path(true).shellescape}" end if FastlaneCore::Helper.xcode_at_least?(10) options << "-parallel-testing-enabled #{config[:parallel_testing] ? 'YES' : 'NO'}" unless config[:parallel_testing].nil? options << "-parallel-testing-worker-count #{config[:concurrent_workers]}" if config[:concurrent_workers] options << "-maximum-concurrent-test-simulator-destinations #{config[:max_concurrent_simulators]}" if config[:max_concurrent_simulators] options << "-disable-concurrent-testing" if config[:disable_concurrent_testing] end options << "-enableCodeCoverage #{config[:code_coverage] ? 'YES' : 'NO'}" unless config[:code_coverage].nil? options << "-enableAddressSanitizer #{config[:address_sanitizer] ? 'YES' : 'NO'}" unless config[:address_sanitizer].nil? options << "-enableThreadSanitizer #{config[:thread_sanitizer] ? 'YES' : 'NO'}" unless config[:thread_sanitizer].nil? if FastlaneCore::Helper.xcode_at_least?(11) if config[:cloned_source_packages_path] && !options.include?("-clonedSourcePackagesDirPath #{config[:cloned_source_packages_path].shellescape}") options << "-clonedSourcePackagesDirPath #{config[:cloned_source_packages_path].shellescape}" end if config[:package_cache_path] && !options.include?("-packageCachePath #{config[:package_cache_path].shellescape}") options << "-packageCachePath #{config[:package_cache_path].shellescape}" end options << "-testPlan '#{config[:testplan]}'" if config[:testplan] # detect_values will ensure that these values are present as Arrays if # they are present at all options += config[:only_test_configurations].map { |name| "-only-test-configuration '#{name}'" } if config[:only_test_configurations] options += config[:skip_test_configurations].map { |name| "-skip-test-configuration '#{name}'" } if config[:skip_test_configurations] end options << "-xctestrun '#{config[:xctestrun]}'" if config[:xctestrun] options << config[:xcargs] if config[:xcargs] # Number of retries does not equal xcodebuild's -test-iterations number # It needs include 1 iteration by default number_of_retries = config[:number_of_retries] + 1 if number_of_retries > 1 && FastlaneCore::Helper.xcode_at_least?(13) options << "-retry-tests-on-failure" options << "-test-iterations #{number_of_retries}" end # 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] options end def actions config = Scan.config actions = [] actions << :clean if config[:clean] if config[:build_for_testing] actions << "build-for-testing" elsif config[:test_without_building] || config[:xctestrun] actions << "test-without-building" else actions << :build unless config[:skip_build] actions << :test end actions end def suffix suffix = [] suffix end def pipe pipe = ["| tee '#{xcodebuild_log_path}'"] # disable_xcpretty is now deprecated and directs to use output_style of raw if Scan.config[:disable_xcpretty] || Scan.config[:output_style] == 'raw' return pipe end formatter = Scan.config[:xcodebuild_formatter].chomp options = legacy_xcpretty_options if 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 return pipe end def pipe_xcbeautify formatter = ['| xcbeautify'] if FastlaneCore::Helper.colors_disabled? formatter << '--disable-colored-output' end return formatter.join(' ') end def legacy_xcpretty_options options = [] options << "formatter" if Scan.config[:formatter] options << "xcpretty_formatter" if Scan.config[:xcpretty_formatter] options << "output_style" if Scan.config[:output_style] options << "output_types" if (Scan.config[:output_types] || "").include?("json-compilation-database") options << "custom_report_file_name" if Scan.config[:custom_report_file_name] return options end def pipe_xcpretty formatter = [] if (custom_formatter = Scan.config[:xcpretty_formatter] || Scan.config[:formatter]) if custom_formatter.end_with?(".rb") formatter << "-f '#{custom_formatter}'" else formatter << "-f `#{custom_formatter}`" end elsif FastlaneCore::Env.truthy?("TRAVIS") formatter << "-f `xcpretty-travis-formatter`" UI.success("Automatically switched to Travis formatter") end if Helper.colors_disabled? formatter << "--no-color" end if Scan.config[:output_style] == 'basic' formatter << "--no-utf" end if Scan.config[:output_style] == 'rspec' formatter << "--test" end @reporter_options_generator = XCPrettyReporterOptionsGenerator.new(Scan.config[:open_report], Scan.config[:output_types], Scan.config[:output_files] || Scan.config[:custom_report_file_name], Scan.config[:output_directory], Scan.config[:use_clang_report_name], Scan.config[:xcpretty_args]) reporter_options = @reporter_options_generator.generate_reporter_options reporter_xcpretty_args = @reporter_options_generator.generate_xcpretty_args_options return "| xcpretty #{formatter.join(' ')} #{reporter_options.join(' ')} #{reporter_xcpretty_args}" end # Store the raw file def xcodebuild_log_path parts = [] if Scan.config[:app_name] parts << Scan.config[:app_name] elsif Scan.project parts << Scan.project.app_name end parts << Scan.config[:scheme] if Scan.config[:scheme] file_name = "#{parts.join('-')}.log" containing = File.expand_path(Scan.config[:buildlog_path]) FileUtils.mkdir_p(containing) return File.join(containing, file_name) end # Generate destination parameters def destination unless Scan.cache[:destination] Scan.cache[:destination] = [*Scan.config[:destination]].map { |dst| "-destination '#{dst}'" }.join(' ') end Scan.cache[:destination] end # The path to set the Derived Data to def build_path unless Scan.cache[:build_path] day = Time.now.strftime("%F") # e.g. 2015-08-07 Scan.cache[:build_path] = File.expand_path("~/Library/Developer/Xcode/Archives/#{day}/") FileUtils.mkdir_p(Scan.cache[:build_path]) end Scan.cache[:build_path] end # The path to the result bundle def result_bundle_path(use_output_directory) root_dir = use_output_directory ? Scan.config[:output_directory] : Dir.mktmpdir retry_count = Scan.cache[:retry_attempt] || 0 attempt = retry_count > 0 ? "-#{retry_count}" : "" ext = FastlaneCore::Helper.xcode_version.to_i >= 11 ? '.xcresult' : '.test_result' path = File.join([root_dir, Scan.config[:scheme]].compact) + attempt + ext Scan.cache[:result_bundle_path] = path # The result bundle path will be in the package path directory if specified delete_path = path delete_path = File.join(Scan.config[:package_path], path) if Scan.config[:package_path].to_s != "" FileUtils.remove_dir(delete_path) if File.directory?(delete_path) return path end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/options.rb
scan/lib/scan/options.rb
require 'fastlane_core/configuration/config_item' require 'fastlane/helper/xcodebuild_formatter_helper' require 'credentials_manager/appfile_config' require_relative 'module' # rubocop:disable Metrics/ClassLength module Scan 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 containing = FastlaneCore::Helper.fastlane_enabled_folder_path [ # app to test FastlaneCore::ConfigItem.new(key: :workspace, short_option: "-w", env_name: "SCAN_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) end), FastlaneCore::ConfigItem.new(key: :project, short_option: "-p", optional: true, env_name: "SCAN_PROJECT", description: "Path to the project file", conflicting_options: [:package_path], 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: :package_path, short_option: "-P", optional: true, env_name: "SCAN_PACKAGE_PATH", description: "Path to the Swift Package", conflicting_options: [:project], verify_block: proc do |value| v = File.expand_path(value.to_s) UI.user_error!("Package path not found at path '#{v}'") unless File.exist?(v) UI.user_error!("Package path invalid") unless File.directory?(v) end), FastlaneCore::ConfigItem.new(key: :scheme, short_option: "-s", optional: true, env_name: "SCAN_SCHEME", description: "The project's scheme. Make sure it's marked as `Shared`"), # device (simulator) to use for testing FastlaneCore::ConfigItem.new(key: :device, short_option: "-a", optional: true, is_string: true, env_name: "SCAN_DEVICE", description: "The name of the simulator type you want to run tests on (e.g. 'iPhone 6' or 'iPhone SE (2nd generation) (14.5)')", conflicting_options: [:devices], conflict_block: proc do |value| UI.user_error!("You can't use 'device' and 'devices' options in one run") end), FastlaneCore::ConfigItem.new(key: :devices, optional: true, is_string: false, env_name: "SCAN_DEVICES", type: Array, description: "Array of devices to run the tests on (e.g. ['iPhone 6', 'iPad Air', 'iPhone SE (2nd generation) (14.5)'])", conflicting_options: [:device], conflict_block: proc do |value| UI.user_error!("You can't use 'device' and 'devices' options in one run") end), FastlaneCore::ConfigItem.new(key: :skip_detect_devices, description: "Should skip auto detecting of devices if none were specified", default_value: false, type: Boolean, optional: true), FastlaneCore::ConfigItem.new(key: :ensure_devices_found, description: "Should fail if devices not found", default_value: false, type: Boolean, optional: true), # simulator management FastlaneCore::ConfigItem.new(key: :force_quit_simulator, env_name: 'SCAN_FORCE_QUIT_SIMULATOR', description: "Enabling this option will automatically killall Simulator processes before the run", default_value: false, type: Boolean), FastlaneCore::ConfigItem.new(key: :reset_simulator, env_name: 'SCAN_RESET_SIMULATOR', description: "Enabling this option will automatically erase the simulator before running the application", default_value: false, type: Boolean), FastlaneCore::ConfigItem.new(key: :disable_slide_to_type, env_name: 'SCAN_DISABLE_SLIDE_TO_TYPE', description: "Enabling this option will disable the simulator from showing the 'Slide to type' prompt", default_value: true, type: Boolean), FastlaneCore::ConfigItem.new(key: :prelaunch_simulator, env_name: 'SCAN_PRELAUNCH_SIMULATOR', description: "Enabling this option will launch the first simulator prior to calling any xcodebuild command", default_value: ENV['FASTLANE_EXPLICIT_OPEN_SIMULATOR'], optional: true, type: Boolean), FastlaneCore::ConfigItem.new(key: :reinstall_app, env_name: 'SCAN_REINSTALL_APP', description: "Enabling this option will automatically uninstall the application before running it", default_value: false, type: Boolean), FastlaneCore::ConfigItem.new(key: :app_identifier, env_name: 'SCAN_APP_IDENTIFIER', optional: true, description: "The bundle identifier of the app to uninstall (only needed when enabling reinstall_app)", code_gen_sensitive: true, default_value: CredentialsManager::AppfileConfig.try_fetch_value(:app_identifier), default_value_dynamic: true), # tests to run FastlaneCore::ConfigItem.new(key: :only_testing, env_name: "SCAN_ONLY_TESTING", description: "Array of test identifiers to run. Expected format: TestTarget[/TestSuite[/TestCase]]", 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: "SCAN_SKIP_TESTING", description: "Array of test identifiers to skip. Expected format: TestTarget[/TestSuite[/TestCase]]", optional: true, is_string: false, verify_block: proc do |value| verify_type('skip_testing', [Array, String], value) end), # test plans to run FastlaneCore::ConfigItem.new(key: :testplan, env_name: "SCAN_TESTPLAN", description: "The testplan associated with the scheme that should be used for testing", is_string: true, optional: true), FastlaneCore::ConfigItem.new(key: :only_test_configurations, env_name: "SCAN_ONLY_TEST_CONFIGURATIONS", description: "Array of strings matching test plan configurations to run", optional: true, is_string: false, verify_block: proc do |value| verify_type('only_test_configurations', [Array, String], value) end), FastlaneCore::ConfigItem.new(key: :skip_test_configurations, env_name: "SCAN_SKIP_TEST_CONFIGURATIONS", description: "Array of strings matching test plan configurations to skip", optional: true, is_string: false, verify_block: proc do |value| verify_type('skip_test_configurations', [Array, String], value) end), # other test options FastlaneCore::ConfigItem.new(key: :xctestrun, short_option: "-X", env_name: "SCAN_XCTESTRUN", description: "Run tests using the provided `.xctestrun` file", conflicting_options: [:build_for_testing], is_string: true, optional: true), FastlaneCore::ConfigItem.new(key: :toolchain, env_name: "SCAN_TOOLCHAIN", conflicting_options: [:xctestrun], 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, is_string: false), FastlaneCore::ConfigItem.new(key: :clean, short_option: "-c", env_name: "SCAN_CLEAN", description: "Should the project be cleaned before building it?", is_string: false, default_value: false), FastlaneCore::ConfigItem.new(key: :code_coverage, env_name: "SCAN_CODE_COVERAGE", description: "Should code coverage be generated? (Xcode 7 and up)", is_string: false, type: Boolean, optional: true), FastlaneCore::ConfigItem.new(key: :address_sanitizer, description: "Should the address sanitizer be turned on?", is_string: false, type: Boolean, optional: true, conflicting_options: [:thread_sanitizer], conflict_block: proc do |value| UI.user_error!("You can't use 'address_sanitizer' and 'thread_sanitizer' options in one run") end), FastlaneCore::ConfigItem.new(key: :thread_sanitizer, description: "Should the thread sanitizer be turned on?", is_string: false, type: Boolean, optional: true, conflicting_options: [:address_sanitizer], conflict_block: proc do |value| UI.user_error!("You can't use 'thread_sanitizer' and 'address_sanitizer' options in one run") end), # output FastlaneCore::ConfigItem.new(key: :open_report, short_option: "-g", env_name: "SCAN_OPEN_REPORT", description: "Should the HTML report be opened when tests are completed?", is_string: false, default_value: false), FastlaneCore::ConfigItem.new(key: :output_directory, short_option: "-o", env_name: "SCAN_OUTPUT_DIRECTORY", description: "The directory in which all reports will be stored", code_gen_sensitive: true, code_gen_default_value: "./test_output", default_value: File.join(containing, "test_output"), default_value_dynamic: true), FastlaneCore::ConfigItem.new(key: :output_style, short_option: "-b", env_name: "SCAN_OUTPUT_STYLE", description: "Define how the output should look like. Valid values are: standard, basic, rspec, or raw (disables xcpretty during xcodebuild)", optional: true, verify_block: proc do |value| UI.user_error!("Invalid output_style #{value}") unless ['standard', 'basic', 'rspec', 'raw'].include?(value) end), FastlaneCore::ConfigItem.new(key: :output_types, short_option: "-f", env_name: "SCAN_OUTPUT_TYPES", description: "Comma separated list of the output types (e.g. html, junit, json-compilation-database)", default_value: "html,junit"), FastlaneCore::ConfigItem.new(key: :output_files, env_name: "SCAN_OUTPUT_FILES", description: "Comma separated list of the output files, corresponding to the types provided by :output_types (order should match). If specifying an output type of json-compilation-database with :use_clang_report_name enabled, that option will take precedence", conflicting_options: [:custom_report_file_name], optional: true, default_value: nil), FastlaneCore::ConfigItem.new(key: :buildlog_path, short_option: "-l", env_name: "SCAN_BUILDLOG_PATH", description: "The directory where to store the raw log", default_value: "#{FastlaneCore::Helper.buildlog_path}/scan", default_value_dynamic: true), FastlaneCore::ConfigItem.new(key: :include_simulator_logs, env_name: "SCAN_INCLUDE_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: :suppress_xcode_output, env_name: "SCAN_SUPPRESS_XCODE_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: ["SCAN_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: :output_remove_retry_attempts, env_names: ["SCAN_OUTPUT_REMOVE_RETRY_ATTEMPS", "SCAN_OUTPUT_REMOVE_RETRY_ATTEMPTS"], # The version with typo must be deprecated description: "Remove retry attempts from test results table and the JUnit report (if not using xcpretty)", type: Boolean, default_value: false), # xcpretty FastlaneCore::ConfigItem.new(key: :disable_xcpretty, env_name: "SCAN_DISABLE_XCPRETTY", deprecated: "Use `output_style: 'raw'` instead", description: "Disable xcpretty formatting of build, similar to `output_style='raw'` but this will also skip the test results table", type: Boolean, optional: true), FastlaneCore::ConfigItem.new(key: :formatter, short_option: "-n", env_name: "SCAN_FORMATTER", deprecated: "Use 'xcpretty_formatter' instead", description: "A custom xcpretty formatter to use", optional: true), FastlaneCore::ConfigItem.new(key: :xcpretty_formatter, short_option: "-N", env_name: "SCAN_XCPRETTY_FORMATTER", description: "A custom xcpretty formatter to use", optional: true), FastlaneCore::ConfigItem.new(key: :xcpretty_args, env_name: "SCAN_XCPRETTY_ARGS", description: "Pass in xcpretty additional command line arguments (e.g. '--test --no-color' or '--tap --no-utf')", type: String, optional: true), FastlaneCore::ConfigItem.new(key: :derived_data_path, short_option: "-j", env_name: "SCAN_DERIVED_DATA_PATH", description: "The directory where build products and other derived data will go", optional: true), FastlaneCore::ConfigItem.new(key: :should_zip_build_products, short_option: "-Z", env_name: "SCAN_SHOULD_ZIP_BUILD_PRODUCTS", description: "Should zip the derived data build products and place in output path?", optional: true, is_string: false, default_value: false), FastlaneCore::ConfigItem.new(key: :output_xctestrun, type: Boolean, env_name: "SCAN_OUTPUT_XCTESTRUN", description: "Should provide additional copy of .xctestrun file (settings.xctestrun) and place in output path?", default_value: false), FastlaneCore::ConfigItem.new(key: :result_bundle_path, env_name: "SCAN_RESULT_BUNDLE_PATH", description: "Custom path for the result bundle, overrides result_bundle", type: String, optional: true), FastlaneCore::ConfigItem.new(key: :result_bundle, short_option: "-z", env_name: "SCAN_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: :use_clang_report_name, description: "Generate the json compilation database with clang naming convention (compile_commands.json)", is_string: false, default_value: false), # concurrency FastlaneCore::ConfigItem.new(key: :parallel_testing, type: Boolean, env_name: "SCAN_PARALLEL_TESTING", description: "Optionally override the per-target setting in the scheme for running tests in parallel. Equivalent to -parallel-testing-enabled", optional: true), FastlaneCore::ConfigItem.new(key: :concurrent_workers, type: Integer, env_name: "SCAN_CONCURRENT_WORKERS", description: "Specify the exact number of test runners that will be spawned during parallel testing. Equivalent to -parallel-testing-worker-count", optional: true), FastlaneCore::ConfigItem.new(key: :max_concurrent_simulators, type: Integer, env_name: "SCAN_MAX_CONCURRENT_SIMULATORS", description: "Constrain the number of simulator devices on which to test concurrently. Equivalent to -maximum-concurrent-test-simulator-destinations", optional: true), FastlaneCore::ConfigItem.new(key: :disable_concurrent_testing, type: Boolean, default_value: false, env_name: "SCAN_DISABLE_CONCURRENT_TESTING", description: "Do not run test bundles in parallel on the specified destinations. Testing will occur on each destination serially. Equivalent to -disable-concurrent-testing", optional: true), # build FastlaneCore::ConfigItem.new(key: :skip_build, description: "Should debug build be skipped before test build?", short_option: "-r", env_name: "SCAN_SKIP_BUILD", is_string: false, type: Boolean, default_value: false), FastlaneCore::ConfigItem.new(key: :test_without_building, short_option: "-T", env_name: "SCAN_TEST_WITHOUT_BUILDING", description: "Test without building, requires a derived data path", is_string: false, type: Boolean, conflicting_options: [:build_for_testing], optional: true), FastlaneCore::ConfigItem.new(key: :build_for_testing, short_option: "-B", env_name: "SCAN_BUILD_FOR_TESTING", description: "Build for testing only, does not run tests", conflicting_options: [:test_without_building], is_string: false, type: Boolean, optional: true), FastlaneCore::ConfigItem.new(key: :sdk, short_option: "-k", env_name: "SCAN_SDK", description: "The SDK that should be used for building the application", optional: true), FastlaneCore::ConfigItem.new(key: :configuration, short_option: "-q", env_name: "SCAN_CONFIGURATION", description: "The configuration to use when building the app. Defaults to 'Release'", default_value_dynamic: true, optional: true), FastlaneCore::ConfigItem.new(key: :xcargs, short_option: "-x", env_name: "SCAN_XCARGS", description: "Pass additional arguments to xcodebuild. 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: "SCAN_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), # build settings FastlaneCore::ConfigItem.new(key: :app_name, env_name: "SCAN_APP_NAME", optional: true, description: "App name to use in slack message and logfile name", is_string: true), FastlaneCore::ConfigItem.new(key: :deployment_target_version, env_name: "SCAN_DEPLOYMENT_TARGET_VERSION", optional: true, description: "Target version of the app being build or tested. Used to filter out simulator version", is_string: true), # slack FastlaneCore::ConfigItem.new(key: :slack_url, short_option: "-i", env_name: "SLACK_URL", sensitive: true, description: "Create an Incoming WebHook for your Slack group to post results there", optional: true, verify_block: proc do |value| if !value.to_s.empty? && !value.start_with?("https://") UI.user_error!("Invalid URL, must start with https://") end end), FastlaneCore::ConfigItem.new(key: :slack_channel, short_option: "-e", env_name: "SCAN_SLACK_CHANNEL", description: "#channel or @username", optional: true), FastlaneCore::ConfigItem.new(key: :slack_message, short_option: "-m", env_name: "SCAN_SLACK_MESSAGE", description: "The message included with each message posted to slack", optional: true), FastlaneCore::ConfigItem.new(key: :slack_use_webhook_configured_username_and_icon, env_name: "SCAN_SLACK_USE_WEBHOOK_CONFIGURED_USERNAME_AND_ICON", description: "Use webhook's default username and icon settings? (true/false)", default_value: false, type: Boolean, optional: true), FastlaneCore::ConfigItem.new(key: :slack_username, env_name: "SCAN_SLACK_USERNAME", description: "Overrides the webhook's username property if slack_use_webhook_configured_username_and_icon is false", default_value: "fastlane", is_string: true, optional: true), FastlaneCore::ConfigItem.new(key: :slack_icon_url, env_name: "SCAN_SLACK_ICON_URL", description: "Overrides the webhook's image property if slack_use_webhook_configured_username_and_icon is false", default_value: "https://fastlane.tools/assets/img/fastlane_icon.png", is_string: true, optional: true), FastlaneCore::ConfigItem.new(key: :skip_slack, env_name: "SCAN_SKIP_SLACK", description: "Don't publish to slack, even when an URL is given", is_string: false, default_value: false), FastlaneCore::ConfigItem.new(key: :slack_only_on_failure, env_name: "SCAN_SLACK_ONLY_ON_FAILURE", description: "Only post on Slack if the tests fail", is_string: false, default_value: false),
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
true
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/slack_poster.rb
scan/lib/scan/slack_poster.rb
require 'fastlane/action' require 'fastlane/actions/slack' require 'fastlane_core/configuration/configuration' require_relative 'module' module Scan class SlackPoster def run(results) return if Scan.config[:skip_slack] return if Scan.config[:slack_only_on_failure] && results[:failures] == 0 return if Scan.config[:slack_url].to_s.empty? if Scan.config[:slack_channel].to_s.length > 0 channel = Scan.config[:slack_channel] channel = ('#' + channel) unless ['#', '@'].include?(channel[0]) # send message to channel by default end username = Scan.config[:slack_use_webhook_configured_username_and_icon] ? nil : Scan.config[:slack_username] icon_url = Scan.config[:slack_use_webhook_configured_username_and_icon] ? nil : Scan.config[:slack_icon_url] fields = [] if results[:build_errors] fields << { title: 'Build Errors', value: results[:build_errors].to_s, short: true } end if results[:failures] fields << { title: 'Test Failures', value: results[:failures].to_s, short: true } end if results[:tests] && results[:failures] fields << { title: 'Successful Tests', value: (results[:tests] - results[:failures]).to_s, short: true } end options = FastlaneCore::Configuration.create(Fastlane::Actions::SlackAction.available_options, { message: "#{Scan.config[:app_name] || Scan.project.app_name} Tests:\n#{Scan.config[:slack_message]}", channel: channel, slack_url: Scan.config[:slack_url].to_s, success: results[:build_errors].to_i == 0 && results[:failures].to_i == 0, username: username, icon_url: icon_url, payload: {}, default_payloads: Scan.config[:slack_default_payloads], attachment_properties: { fields: fields } }) Fastlane::Actions::SlackAction.run(options) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/detect_values.rb
scan/lib/scan/detect_values.rb
require 'fastlane_core/device_manager' require 'fastlane_core/project' require 'pathname' require 'set' require_relative 'module' module Scan # This class detects all kinds of default values class DetectValues PLATFORMS = { 'iOS' => { simulator: 'iphonesimulator', name: 'com.apple.platform.iphoneos' }, 'tvOS' => { simulator: 'appletvsimulator', name: 'com.apple.platform.appletvos' }, 'watchOS' => { simulator: 'watchsimulator', name: 'com.apple.platform.watchos' }, 'visionOS' => { simulator: 'xrsimulator', name: 'com.apple.platform.xros' } }.freeze # This is needed as these are more complex default values # Returns the finished config object def self.set_additional_default_values config = Scan.config # First, try loading the Scanfile from the current directory config.load_configuration_file(Scan.scanfile_name) prevalidate # Detect the project if not SPM package if Scan.config[:package_path].nil? FastlaneCore::Project.detect_projects(config) Scan.project = FastlaneCore::Project.new(config) # Go into the project's folder, as there might be a Snapfile there imported_path = File.expand_path(Scan.scanfile_name) Dir.chdir(File.expand_path("..", Scan.project.path)) do config.load_configuration_file(Scan.scanfile_name) unless File.expand_path(Scan.scanfile_name) == imported_path end Scan.project.select_scheme end devices = Scan.config[:devices] || Array(Scan.config[:device]) # important to use Array(nil) for when the value is nil if devices.count > 0 detect_simulator(devices, '', '', '', nil) elsif Scan.project if Scan.project.ios? # An iPhone 5s is a reasonably small and useful default for tests detect_simulator(devices, 'iOS', 'IPHONEOS_DEPLOYMENT_TARGET', 'iPhone 5s', nil) elsif Scan.project.tvos? detect_simulator(devices, 'tvOS', 'TVOS_DEPLOYMENT_TARGET', 'Apple TV 1080p', 'TV') end end detect_destination default_derived_data coerce_to_array_of_strings(:only_testing) coerce_to_array_of_strings(:skip_testing) coerce_to_array_of_strings(:only_test_configurations) coerce_to_array_of_strings(:skip_test_configurations) return config end def self.prevalidate output_types = Scan.config[:output_types] has_multiple_report_types = output_types && output_types.split(',').size > 1 if has_multiple_report_types && Scan.config[:custom_report_file_name] UI.user_error!("Using a :custom_report_file_name with multiple :output_types (#{output_types}) will lead to unexpected results. Use :output_files instead.") end end def self.coerce_to_array_of_strings(config_key) config_value = Scan.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) Scan.config[config_key] = config_value.map(&:to_s) end def self.default_derived_data return unless Scan.project return unless Scan.config[:derived_data_path].to_s.empty? default_path = Scan.project.build_settings(key: "BUILT_PRODUCTS_DIR") # => /Users/.../Library/Developer/Xcode/DerivedData/app-bqrfaojicpsqnoglloisfftjhksc/Build/Products/Release-iphoneos # We got 3 folders up to point to ".../DerivedData/app-[random_chars]/" default_path = File.expand_path("../../..", default_path) UI.verbose("Detected derived data path '#{default_path}'") Scan.config[:derived_data_path] = default_path end def self.filter_simulators(simulators, operator = :greater_than_or_equal, deployment_target) deployment_target_version = Gem::Version.new(deployment_target) simulators.select do |s| sim_version = Gem::Version.new(s.os_version) if operator == :greater_than_or_equal sim_version >= deployment_target_version elsif operator == :equal sim_version == deployment_target_version else false # this will show an error message in the detect_simulator method end end end def self.default_os_version(os_type) @os_versions ||= {} @os_versions[os_type] ||= begin UI.crash!("Unknown platform: #{os_type}") unless PLATFORMS.key?(os_type) platform = PLATFORMS[os_type] _, error, = Open3.capture3('xcrun simctl runtime -h') unless error.include?('Usage: simctl runtime <operation> <arguments>') UI.error("xcrun simctl runtime broken, run 'xcrun simctl runtime' and make sure it works") UI.user_error!("xcrun simctl runtime not working.") end # `match list` subcommand added in Xcode 15 if error.include?('match list') # list SDK version for currently running Xcode sdks_output, status = Open3.capture2('xcodebuild -showsdks -json') sdk_version = begin raise status unless status.success? JSON.parse(sdks_output).find { |e| e['platform'] == platform[:simulator] }['sdkVersion'] rescue StandardError => e UI.error(e) UI.error("xcodebuild CLI broken, please run `xcodebuild` and make sure it works") UI.user_error!("xcodebuild not working") end # Get runtime build from SDK version runtime_output, status = Open3.capture2('xcrun simctl runtime match list -j') runtime_build = begin raise status unless status.success? JSON.parse(runtime_output).values.find { |elem| elem['platform'] == platform[:name] && elem['sdkVersion'] == sdk_version }['chosenRuntimeBuild'] rescue StandardError => e UI.error(e) UI.error("xcrun simctl runtime broken, please verify that `xcrun simctl runtime match list` and `xcrun simctl runtime list` work") UI.user_error!("xcrun simctl runtime not working") end # Get OS version corresponding to build Gem::Version.new(FastlaneCore::DeviceManager.runtime_build_os_versions[runtime_build]) end end end def self.clear_cache @os_versions = nil end def self.compatibility_constraint(sim, device_name) latest_os = default_os_version(sim.os_type) sim.name == device_name && (latest_os.nil? || Gem::Version.new(sim.os_version) <= latest_os) end def self.highest_compatible_simulator(simulators, device_name) simulators .select { |sim| compatibility_constraint(sim, device_name) } .reverse .sort_by! { |sim| Gem::Version.new(sim.os_version) } .last end def self.regular_expression_for_split_on_whitespace_followed_by_parenthesized_version # %r{ # \s # a whitespace character # (?= # followed by -- using lookahead # \( # open parenthesis # [\d\.]+ # our version -- one or more digits or full stops # \) # close parenthesis # $ # end of line # ) # end of lookahead # } /\s(?=\([\d\.]+\)$)/ end def self.detect_simulator(devices, requested_os_type, deployment_target_key, default_device_name, simulator_type_descriptor) clear_cache deployment_target_version = get_deployment_target_version(deployment_target_key) simulators = filter_simulators( FastlaneCore::DeviceManager.simulators(requested_os_type).tap do |array| if array.empty? UI.user_error!(['No', simulator_type_descriptor, 'simulators found on local machine'].reject(&:nil?).join(' ')) end end, :greater_than_or_equal, deployment_target_version ).tap do |sims| if sims.empty? UI.error("No simulators found that are greater than or equal to the version of deployment target (#{deployment_target_version})") end end # At this point we have all simulators for the given deployment target (or higher) # We create 2 lambdas, which we iterate over later on # If the first lambda `matches` found a simulator to use # we'll never call the second one matches = lambda do set_of_simulators = devices.inject( Set.new # of simulators ) do |set, device_string| pieces = device_string.split(regular_expression_for_split_on_whitespace_followed_by_parenthesized_version) display_device = "'#{device_string}'" set + ( if pieces.count == 0 [] # empty array elsif pieces.count == 1 [ highest_compatible_simulator(simulators, pieces.first) ].compact else # pieces.count == 2 -- mathematically, because of the 'end of line' part of our regular expression version = pieces[1].tr('()', '') display_device = "'#{pieces[0]}' with version #{version}" potential_emptiness_error = lambda do |sims| if sims.empty? UI.error("No simulators found that are equal to the version " \ "of specifier (#{version}) and greater than or equal to the version " \ "of deployment target (#{deployment_target_version})") end end filter_simulators(simulators, :equal, version).tap(&potential_emptiness_error).select { |sim| sim.name == pieces.first } end ).tap do |array| if array.empty? UI.test_failure!("No device found with name #{display_device}") if Scan.config[:ensure_devices_found] UI.error("Ignoring '#{device_string}', couldn't find matching simulator") end end end set_of_simulators.to_a end unless Scan.config[:skip_detect_devices] default = lambda do UI.error("Couldn't find any matching simulators for '#{devices}' - falling back to default simulator") if (devices || []).count > 0 result = [ highest_compatible_simulator(simulators, default_device_name) || simulators.first ] UI.message("Found simulator \"#{result.first.name} (#{result.first.os_version})\"") if result.first result end end # Convert array to lazy enumerable (evaluate map only when needed) # grab the first unempty evaluated array Scan.devices = [matches, default].lazy.reject(&:nil?).map { |x| arr = x.call arr unless arr.empty? }.reject(&:nil?).first end def self.min_xcode8? Helper.xcode_at_least?("8.0") end def self.detect_destination if Scan.config[:destination] # No need to show below warnings message(s) for xcode13+, because # Apple recommended to have destination in all xcodebuild commands # otherwise, Apple will generate warnings in console logs # see: https://github.com/fastlane/fastlane/issues/19579 return if Helper.xcode_at_least?("13.0") UI.important("It's not recommended to set the `destination` value directly") UI.important("Instead use the other options available in `fastlane scan --help`") UI.important("Using your value '#{Scan.config[:destination]}' for now") UI.important("because I trust you know what you're doing...") return end # building up the destination now if Scan.building_mac_catalyst_for_mac? Scan.config[:destination] = ["platform=macOS,variant=Mac Catalyst"] elsif Scan.devices && Scan.devices.count > 0 # Explicitly run simulator in Rosetta (needed for Xcode 14.3 and up) # Fixes https://github.com/fastlane/fastlane/issues/21194 arch = "" if Scan.config[:run_rosetta_simulator] arch = ",arch=x86_64" end Scan.config[:destination] = Scan.devices.map { |d| "platform=#{d.os_type} Simulator,id=#{d.udid}" + arch } elsif Scan.project && Scan.project.mac_app? Scan.config[:destination] = min_xcode8? ? ["platform=macOS"] : ["platform=OS X"] end end # get deployment target version def self.get_deployment_target_version(deployment_target_key) version = Scan.config[:deployment_target_version] version ||= Scan.project.build_settings(key: deployment_target_key) if Scan.project version ||= 0 return version end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/test_result_parser.rb
scan/lib/scan/test_result_parser.rb
require_relative 'module' module Scan class TestResultParser def parse_result(output) unless output return { tests: 0, failures: 0 } end # e.g. ...<testsuites tests='2' failures='1'>... matched = output.scan(/<testsuites\b(?=[^<>]*\s+tests='(\d+)')(?=[^<>]*\s+failures='(\d+)')[^<>]+>/) if matched && matched.length == 1 && matched[0].length == 2 tests = matched[0][0].to_i failures = matched[0][1].to_i { tests: tests, failures: failures } else UI.error("Couldn't parse the number of tests from the output") { tests: 0, failures: 0 } end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/commands_generator.rb
scan/lib/scan/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 Scan 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, 'scan' program :version, Fastlane::VERSION program :description, Scan::DESCRIPTION program :help, "Author", "Felix Krause <scan@krausefx.com>" program :help, "Website", "https://fastlane.tools" program :help, "Documentation", "https://docs.fastlane.tools/actions/scan/" program :help_formatter, FastlaneCore::HelpFormatter global_option("--verbose") { FastlaneCore::Globals.verbose = true } command :tests do |c| c.syntax = "fastlane scan" c.description = Scan::DESCRIPTION FastlaneCore::CommanderGenerator.new.generate(Scan::Options.available_options, command: c) c.action do |_args, options| config = FastlaneCore::Configuration.create(Scan::Options.available_options, convert_options(options)) Scan::Manager.new.work(config) end end command :init do |c| c.syntax = "fastlane scan init" c.description = "Creates a new Scanfile for you" c.action do |args, options| containing = FastlaneCore::Helper.fastlane_enabled_folder_path path = File.join(containing, Scan.scanfile_name) UI.user_error!("Scanfile already exists").yellow if File.exist?(path) is_swift_fastfile = args.include?("swift") if is_swift_fastfile path = File.join(containing, Scan.scanfile_name + ".swift") UI.user_error!("Scanfile.swift already exists") if File.exist?(path) end if is_swift_fastfile template = File.read("#{Scan::ROOT}/lib/assets/ScanfileTemplate.swift") else template = File.read("#{Scan::ROOT}/lib/assets/ScanfileTemplate") end File.write(path, template) UI.success("Successfully created '#{path}'. Open the file using a code editor.") end end default_command(:tests) run! end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/xcpretty_reporter_options_generator.rb
scan/lib/scan/xcpretty_reporter_options_generator.rb
require_relative 'module' module Scan class XCPrettyReporterOptionsGenerator SUPPORTED_REPORT_TYPES = %w(html junit json-compilation-database) def self.generate_from_scan_config self.new(Scan.config[:open_report], Scan.config[:output_types], Scan.config[:output_files] || Scan.config[:custom_report_file_name], Scan.config[:output_directory], Scan.config[:use_clang_report_name], Scan.config[:xcpretty_args]) end # Initialize with values from Scan.config matching these param names def initialize(open_report, output_types, output_files, output_directory, use_clang_report_name, xcpretty_args) @open_report = open_report @output_types = output_types @output_files = output_files @output_directory = output_directory @use_clang_report_name = use_clang_report_name @xcpretty_args = xcpretty_args # might already be an array when passed via fastlane @output_types = @output_types.split(',') if @output_types.kind_of?(String) if @output_files.nil? @output_files = @output_types.map { |type| "report.#{type}" } elsif @output_files.kind_of?(String) # might already be an array when passed via fastlane @output_files = @output_files.split(',') end unless @output_types.length == @output_files.length UI.important("WARNING: output_types and output_files do not have the same number of items. Default values will be substituted as needed.") end (@output_types - SUPPORTED_REPORT_TYPES).each do |type| UI.error("Couldn't find reporter '#{type}', available #{SUPPORTED_REPORT_TYPES.join(', ')}") end end def generate_reporter_options reporter = [] valid_types = @output_types & SUPPORTED_REPORT_TYPES valid_types.each do |raw_type| type = raw_type.strip output_path = File.join(File.expand_path(@output_directory), determine_output_file_name(type)) reporter << "--report #{type}" reporter << "--output '#{output_path}'" if type == "html" && @open_report Scan.cache[:open_html_report_path] = output_path end end # adds another junit reporter in case the user does not specify one # this will be used to generate a results table and then discarded require 'tempfile' @temp_junit_report = Tempfile.new("junit_report") Scan.cache[:temp_junit_report] = @temp_junit_report.path reporter << "--report junit" reporter << "--output '#{Scan.cache[:temp_junit_report]}'" return reporter end def generate_xcpretty_args_options return @xcpretty_args end private def determine_output_file_name(type) if @use_clang_report_name && type == "json-compilation-database" return "compile_commands.json" end index = @output_types.index(type) file = @output_files[index] file || "report.#{type}" end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/error_handler.rb
scan/lib/scan/error_handler.rb
require_relative 'module' module Scan # 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, log_path) # The order of the handling below is important instruction = 'See the log' location = Scan.config[:suppress_xcode_output] ? "here: '#{log_path}'" : "above" details = "#{instruction} #{location}." case output 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") when /Testing failed on/ # This is important because xcbeautify and raw output will print: # Testing failed on 'iPhone 13 Pro Max' # when multiple devices are use. # xcpretty hides this output so its not an issue with xcpretty. # We need to catch "Testing failed on" before "Test failed" # so that an error isn't raised. # Raising an error prevents trainer from processing the xcresult return when /Testing failed/ UI.build_failure!("Error building the application. #{details}") when /Executed/, /Failing tests:/ # this is *really* important: # we don't want to raise an exception here # as we handle this in runner.rb at a later point # after parsing the actual test results # ------------------------------------------------ # For the "Failing tests:" case, this covers Xcode # 10 parallel testing failure, which doesn't # print out the "Executed" line that would show # test summary (number of tests passed, etc.). # Instead, it just prints "Failing tests:" # followed by a list of tests that failed. return end UI.build_failure!("Error building/testing the application. #{details}") end private # Just to make things easier def print(text) UI.error(text) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/runner.rb
scan/lib/scan/runner.rb
require 'open3' require 'fileutils' require 'terminal-table' require 'shellwords' require 'fastlane_core/env' require 'fastlane_core/device_manager' require_relative 'module' require_relative 'xcpretty_reporter_options_generator' require_relative 'test_result_parser' require_relative 'slack_poster' require_relative 'test_command_generator' require_relative 'error_handler' module Scan class Runner def initialize @test_command_generator = TestCommandGenerator.new @device_boot_datetime = DateTime.now end def run @xcresults_before_run = find_xcresults_in_derived_data return handle_results(test_app) end def test_app force_quit_simulator_processes if Scan.config[:force_quit_simulator] if Scan.devices if Scan.config[:reset_simulator] Scan.devices.each do |device| FastlaneCore::Simulator.reset(udid: device.udid) end end if Scan.config[:disable_slide_to_type] Scan.devices.each do |device| FastlaneCore::Simulator.disable_slide_to_type(udid: device.udid) end end end prelaunch_simulators if Scan.config[:reinstall_app] app_identifier = Scan.config[:app_identifier] app_identifier ||= UI.input("App Identifier: ") Scan.devices.each do |device| FastlaneCore::Simulator.uninstall_app(app_identifier, device.name, device.udid) end end retries = Scan.config[:number_of_retries] execute(retries: retries) end def execute(retries: 0) # Set retries to 0 if Xcode 13 because TestCommandGenerator will set '-retry-tests-on-failure -test-iterations' if Helper.xcode_at_least?(13) retries = 0 Scan.cache[:retry_attempt] = 0 else Scan.cache[:retry_attempt] = Scan.config[:number_of_retries] - retries end command = @test_command_generator.generate prefix_hash = [ { prefix: "Running Tests: ", block: proc do |value| value.include?("Touching") end } ] exit_status = 0 FastlaneCore::CommandExecutor.execute(command: command, print_all: true, print_command: true, prefix: prefix_hash, loading: "Loading...", suppress_output: Scan.config[:suppress_xcode_output], error: proc do |error_output| begin exit_status = $?.exitstatus if retries > 0 # If there are retries remaining, run the tests again return retry_execute(retries: retries, error_output: error_output) else ErrorHandler.handle_build_error(error_output, @test_command_generator.xcodebuild_log_path) end rescue => ex SlackPoster.new.run({ build_errors: 1 }) raise ex end end) exit_status end def retry_execute(retries:, error_output: "") tests = retryable_tests(error_output) if tests.empty? UI.build_failure!("Failed to find failed tests to retry (could not parse error output)") end Scan.config[:only_testing] = tests UI.important("Retrying tests: #{Scan.config[:only_testing].join(', ')}") retries -= 1 UI.important("Number of retries remaining: #{retries}") return execute(retries: retries) end def retryable_tests(input) input = Helper.strip_ansi_colors(input) retryable_tests = [] failing_tests = input.split("Failing tests:\n").fetch(1, []) .split("\n\n").first suites = failing_tests.split(/(?=\n\s+[\w\s]+:\n)/) suites.each do |suite| suite_name = suite.match(/\s*([\w\s\S]+):/).captures.first test_cases = suite.split(":\n").fetch(1, []).split("\n").each .select { |line| line.match?(/^\s+/) } .map { |line| line.strip.gsub(/[\s\.]/, "/").gsub(/[\-\[\]\(\)]/, "") } .map { |line| suite_name + "/" + line } retryable_tests += test_cases end return retryable_tests.uniq end def find_filename(type) index = Scan.config[:output_types].split(',').index(type) return nil if index.nil? return (Scan.config[:output_files] || "").split(',')[index] end def output_html? return Scan.config[:output_types].split(',').include?('html') end def output_junit? return Scan.config[:output_types].split(',').include?('junit') end def output_json_compilation_database? return Scan.config[:output_types].split(',').include?('json-compilation-database') end def output_html_filename return find_filename('html') end def output_junit_filename return find_filename('junit') end def output_json_compilation_database_filename return find_filename('json-compilation-database') end def find_xcresults_in_derived_data derived_data_path = Scan.config[:derived_data_path] return [] if derived_data_path.nil? # Swift packages might not have derived data xcresults_path = File.join(derived_data_path, "Logs", "Test", "*.xcresult") return Dir[xcresults_path] end def trainer_test_results require "trainer" results = { number_of_tests: 0, number_of_failures: 0, number_of_retries: 0, number_of_skipped: 0, number_of_tests_excluding_retries: 0, number_of_failures_excluding_retries: 0 } result_bundle_path = Scan.cache[:result_bundle_path] # Looks for xcresult file in derived data if not specifically set if result_bundle_path.nil? xcresults = find_xcresults_in_derived_data new_xcresults = xcresults - @xcresults_before_run if new_xcresults.size != 1 UI.build_failure!("Cannot find .xcresult in derived data which is needed to determine test results. This is an issue within scan. File an issue on GitHub or try setting option `result_bundle: true`") end result_bundle_path = new_xcresults.first Scan.cache[:result_bundle_path] = result_bundle_path end output_path = Scan.config[:output_directory] || Dir.mktmpdir output_path = File.absolute_path(output_path) UI.build_failure!("A -resultBundlePath is needed to parse the test results. This should not have happened. Please file an issue.") unless result_bundle_path params = { path: result_bundle_path, output_remove_retry_attempts: Scan.config[:output_remove_retry_attempts], silent: !FastlaneCore::Globals.verbose? } formatter = Scan.config[:xcodebuild_formatter].chomp show_output_types_tip = false if output_html? && formatter != 'xcpretty' UI.important("Skipping HTML... only available with `xcodebuild_formatter: 'xcpretty'` right now") show_output_types_tip = true end if output_json_compilation_database? && formatter != 'xcpretty' UI.important("Skipping JSON Compilation Database... only available with `xcodebuild_formatter: 'xcpretty'` right now") show_output_types_tip = true end if show_output_types_tip UI.important("Your 'xcodebuild_formatter' doesn't support these 'output_types'. Change your 'output_types' to prevent these warnings from showing...") end if output_junit? if formatter == 'xcpretty' UI.verbose("Generating junit report with xcpretty") else UI.verbose("Generating junit report with trainer") params[:output_filename] = output_junit_filename || "report.junit" params[:output_directory] = output_path end end resulting_paths = Trainer::TestParser.auto_convert(params) resulting_paths.each do |path, data| results[:number_of_tests] += data[:number_of_tests] results[:number_of_failures] += data[:number_of_failures] results[:number_of_tests_excluding_retries] += data[:number_of_tests_excluding_retries] results[:number_of_failures_excluding_retries] += data[:number_of_failures_excluding_retries] results[:number_of_skipped] += data[:number_of_skipped] || 0 results[:number_of_retries] += data[:number_of_retries] end return results end def handle_results(tests_exit_status) copy_simulator_logs zip_build_products copy_xctestrun return nil if Scan.config[:build_for_testing] results = trainer_test_results number_of_retries = results[:number_of_retries] number_of_skipped = results[:number_of_skipped] number_of_tests = results[:number_of_tests_excluding_retries] number_of_failures = results[:number_of_failures_excluding_retries] SlackPoster.new.run({ tests: number_of_tests, failures: number_of_failures }) if number_of_failures > 0 failures_str = number_of_failures.to_s.red else failures_str = number_of_failures.to_s.green end retries_str = case number_of_retries when 0 "" when 1 " (and 1 retry)" else " (and #{number_of_retries} retries)" end puts(Terminal::Table.new({ title: "Test Results", rows: [ ["Number of tests", "#{number_of_tests}#{retries_str}"], number_of_skipped > 0 ? ["Number of tests skipped", number_of_skipped] : nil, ["Number of failures", failures_str] ].compact })) puts("") if number_of_failures > 0 open_report if Scan.config[:fail_build] UI.test_failure!("Tests have failed") else UI.error("Tests have failed") end end unless tests_exit_status == 0 if Scan.config[:fail_build] UI.test_failure!("Test execution failed. Exit status: #{tests_exit_status}") else UI.error("Test execution failed. Exit status: #{tests_exit_status}") end end open_report return results end def open_report if !Helper.ci? && Scan.cache[:open_html_report_path] `open --hide '#{Scan.cache[:open_html_report_path]}'` end end def zip_build_products return unless Scan.config[:should_zip_build_products] # Gets :derived_data_path/Build/Products directory for zipping zip derived_data_path = Scan.config[:derived_data_path] path = File.join(derived_data_path, "Build/Products") # Gets absolute path of output directory output_directory = File.absolute_path(Scan.config[:output_directory]) output_path = File.join(output_directory, "build_products.zip") # Caching path for action to put into lane_context Scan.cache[:zip_build_products_path] = output_path # Zips build products and moves it to output directory UI.message("Zipping build products") FastlaneCore::Helper.zip_directory(path, output_path, contents_only: true, overwrite: true, print: false) UI.message("Successfully zipped build products: #{output_path}") end def copy_xctestrun return unless Scan.config[:output_xctestrun] # Gets :derived_data_path/Build/Products directory for coping .xctestrun file derived_data_path = Scan.config[:derived_data_path] path = File.join(derived_data_path, "Build", "Products") # Gets absolute path of output directory output_directory = File.absolute_path(Scan.config[:output_directory]) output_path = File.join(output_directory, "settings.xctestrun") # Caching path for action to put into lane_context Scan.cache[:output_xctestrun] = output_path # Copy .xctestrun file and moves it to output directory UI.message("Copying .xctestrun file") xctestrun_file = Dir.glob("#{path}/*.xctestrun").first if xctestrun_file FileUtils.cp(xctestrun_file, output_path) UI.message("Successfully copied xctestrun file: #{output_path}") else UI.user_error!("Could not find .xctestrun file to copy") end end def test_results temp_junit_report = Scan.cache[:temp_junit_report] return File.read(temp_junit_report) if temp_junit_report && File.file?(temp_junit_report) # Something went wrong with the temp junit report for the test success/failures count. # We'll have to regenerate from the xcodebuild log, like we did before version 2.34.0. UI.message("Generating test results. This may take a while for large projects.") reporter_options_generator = XCPrettyReporterOptionsGenerator.new(false, [], [], "", false, nil) reporter_options = reporter_options_generator.generate_reporter_options xcpretty_args_options = reporter_options_generator.generate_xcpretty_args_options cmd = "cat #{@test_command_generator.xcodebuild_log_path.shellescape} | xcpretty #{reporter_options.join(' ')} #{xcpretty_args_options} &> /dev/null" system(cmd) File.read(Scan.cache[:temp_junit_report]) end def prelaunch_simulators return unless Scan.devices.to_a.size > 0 # no devices selected, no sims to launch # Return early unless the user wants to prelaunch simulators. Or if the user wants simulator logs # then we must prelaunch simulators because Xcode's headless # mode launches and shuts down the simulators before we can collect the logs. return unless Scan.config[:prelaunch_simulator] || Scan.config[:include_simulator_logs] devices_to_shutdown = [] Scan.devices.each do |device| devices_to_shutdown << device if device.state == "Shutdown" device.boot end at_exit do devices_to_shutdown.each(&:shutdown) end end def copy_simulator_logs return unless Scan.config[:include_simulator_logs] UI.header("Collecting system logs") Scan.devices.each do |device| log_identity = "#{device.name}_#{device.os_type}_#{device.os_version}" FastlaneCore::Simulator.copy_logs(device, log_identity, Scan.config[:output_directory], @device_boot_datetime) end end def force_quit_simulator_processes # Silently execute and kill, verbose flags will show this command occurring Fastlane::Actions.sh("killall Simulator &> /dev/null || true", log: false) end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/manager.rb
scan/lib/scan/manager.rb
require 'fastlane_core/print_table' require_relative 'module' require_relative 'runner' module Scan class Manager attr_accessor :plist_files_before def work(options) Scan.config = options # we set this here to auto-detect missing values, which we need later on unless options[:derived_data_path].to_s.empty? self.plist_files_before = test_summary_filenames(Scan.config[:derived_data_path]) end # Also print out the path to the used Xcode installation # We go 2 folders up, to not show "Contents/Developer/" values = Scan.config.values(ask: false) values[:xcode_path] = File.expand_path("../..", FastlaneCore::Helper.xcode_path) FastlaneCore::PrintTable.print_values(config: values, hide_keys: [:destination, :slack_url], title: "Summary for scan #{Fastlane::VERSION}") return Runner.new.run end def test_summary_filenames(derived_data_path) files = [] # Xcode < 10 files += Dir["#{derived_data_path}/**/Logs/Test/*TestSummaries.plist"] # Xcode 10 files += Dir["#{derived_data_path}/**/Logs/Test/*.xcresult/TestSummaries.plist"] return files end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/scan/lib/scan/module.rb
scan/lib/scan/module.rb
require 'fastlane_core/helper' require 'fastlane/boolean' require_relative 'detect_values' module Scan class << self attr_accessor :config attr_accessor :project attr_accessor :cache attr_accessor :devices def config=(value) @config = value DetectValues.set_additional_default_values @cache = {} end def scanfile_name "Scanfile" end def building_mac_catalyst_for_mac? return false unless Scan.project Scan.config[:catalyst_platform] == "macos" && Scan.project.supports_mac_catalyst? 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 = "The easiest way to run tests of your iOS and Mac app" end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/rubocop/is_string_usage.rb
rubocop/is_string_usage.rb
require 'rubocop' module RuboCop module Cop module Lint class IsStringUsage < RuboCop::Cop::Cop MSG = 'is_string key in used in FastlaneCore::ConfigItem. Replace with `type: <Integer|Float|String|Boolean|Array|Hash>`'.freeze def on_hash(node) pairs = node.pairs return if pairs.empty? pairs.each do |pair| key = pair.key value = pair.value next unless key.source.to_sym == :is_string && (value.source.to_s == "false" || value.source.to_s == "true") if node.parent.children[0].source == "FastlaneCore::ConfigItem" add_offense(pair, location: :expression) 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/rubocop/fork_usage.rb
rubocop/fork_usage.rb
require 'rubocop' module RuboCop module CrossPlatform class ForkUsage < RuboCop::Cop::Cop MSG = "Using `fork`, which does not work on all platforms. Wrap in `if Process.respond_to?(:fork)` to silence.".freeze def_node_matcher :bad_fork, <<-PATTERN (send _ :fork) PATTERN def_node_matcher :good_fork, <<-PATTERN (if (send (const _ :Process) :respond_to? (sym :fork)) ...) PATTERN attr_writer :good_nodes def good_nodes @good_nodes ||= [] end def mark_good_recursively(node) return unless node.kind_of?(RuboCop::AST::Node) self.good_nodes << node node.children.each { |c| mark_good_recursively(c) } end def on_if(node) return unless good_fork(node) mark_good_recursively(node) end def on_send(node) return unless bad_fork(node) return if self.good_nodes.include?(node) add_offense(node, location: :expression, message: MSG) end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false
fastlane/fastlane
https://github.com/fastlane/fastlane/blob/d1f6eb6228644936997aae1956d8036ea62cd5b4/rubocop/missing_keys_on_shared_area.rb
rubocop/missing_keys_on_shared_area.rb
require 'rubocop' module RuboCop module Lint class MissingKeysOnSharedArea < RuboCop::Cop::Cop MISSING_KEYS_MSG = "Found %<key>s in 'SharedValues' but not in 'output' method. Keys in the 'output' method: %<list>s".freeze MISSING_OUTPUT_METHOD_MSG = "There are declared keys on the shared area 'SharedValues', but 'output' method has not been found".freeze MISSING_CONST_DEFINITION_MSG = "Found setting a value for `SharedValues` in a function but the const is not declared in `SharedValues` module".freeze def_node_search :extract_const_assignment, <<-PATTERN (casgn nil? $_ ...) PATTERN def_node_matcher :find_output_method, <<-PATTERN (defs (self) :output ...) PATTERN def_node_matcher :extract_shared_values_key?, <<-PATTERN (const (const nil? :SharedValues) $_) PATTERN attr_writer :shared_values_constants def shared_values_constants @shared_values_constants ||= [] end def on_module(node) name, body = *node return unless name.source == 'SharedValues' return if body.nil? consts = extract_const_assignment(node) consts.each { |const| self.shared_values_constants << const.to_s } end def on_defs(node) return if self.shared_values_constants.empty? return unless find_output_method(node) _definee, _method_name, _args, body = *node return add_offense(node, location: :expression, message: format(MISSING_KEYS_MSG, key: self.shared_values_constants.join(', '), list: [])) if body.nil? return add_offense(node, location: :expression, message: format(MISSING_KEYS_MSG, key: self.shared_values_constants.join(', '), list: [])) unless body.array_type? children = body.children.select(&:array_type?) keys = children.map { |child| child.children.first.source.to_s.gsub(/\s|"|'/, '') } add_offense(node, location: :expression, message: format(MISSING_KEYS_MSG, key: self.shared_values_constants.join(', '), list: keys.join(', '))) unless self.shared_values_constants.to_set == keys.to_set end def on_class(node) _name, superclass, body = *node return unless superclass return unless superclass.loc.name.source == 'Action' add_offense(node, location: :expression, message: MISSING_OUTPUT_METHOD_MSG) if body.nil? && self.shared_values_constants.any? return if body.nil? has_output_method?(body) end def on_send(node) return unless node.arguments? _, _, *arg_nodes = *node return unless arg_nodes.count == 2 key = extract_shared_values_key?(node.first_argument) return if key.nil? contains_key = self.shared_values_constants.include?(key.to_s) add_offense(node, location: :expression, message: MISSING_CONST_DEFINITION_MSG) unless contains_key end def has_output_method?(node) return if node.nil? return if self.shared_values_constants.empty? if node.defs_type? # A single method add_offense(node, location: :expression, message: MISSING_OUTPUT_METHOD_MSG) unless output_method?(node) elsif node.begin_type? # Multiple methods outputs = node.each_child_node(:defs).select { |n| output_method?(n) } add_offense(node, location: :expression, message: MISSING_OUTPUT_METHOD_MSG) if outputs.empty? end end def output_method?(node) _definee, method_name, _args, _body = *node method_name.to_s == 'output' end end end end
ruby
MIT
d1f6eb6228644936997aae1956d8036ea62cd5b4
2026-01-04T15:37:27.371479Z
false