code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def extract_mixins(config:) # Get mixins config hash _mixins = config[:mixins] # If no :mixins section, return: # - Empty enabled list # - Empty load paths return [], [] if _mixins.nil? # Build list of load paths # Configured load paths are higher in search path ordering load_paths = _mixins[:load_paths] || [] # Get list of mixins enabled = _mixins[:enabled] || [] enabled = enabled.clone # Ensure it's a copy of configuration section # Handle any inline Ruby string expansion load_paths.each do |load_path| load_path.replace( @system_wrapper.module_eval( load_path ) ) if (load_path =~ PATTERNS::RUBY_STRING_REPLACEMENT) end enabled.each do |mixin| mixin.replace( @system_wrapper.module_eval( mixin ) ) if (mixin =~ PATTERNS::RUBY_STRING_REPLACEMENT) end # Remove the :mixins section of the configuration config.delete( :mixins ) return enabled, load_paths end
Pick apart a :mixins projcet configuration section and return components Layout mirrors :plugins section
extract_mixins
ruby
ThrowTheSwitch/Ceedling
bin/projectinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/bin/projectinator.rb
MIT
def build_step(msg, heading: true, &block) if heading msg = @reportinator.generate_heading( @loginator.decorate( msg, LogLabels::RUN ) ) else # Progress message msg = "\n" + @reportinator.generate_progress( @loginator.decorate( msg, LogLabels::RUN ) ) end @loginator.log( msg ) yield # Execute build step block end
Neaten up a build step with progress message and some scope encapsulation
build_step
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/build_batchinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/build_batchinator.rb
MIT
def exec(workload:, things:, &block) workers = 0 case workload when :compile workers = @configurator.project_compile_threads when :test workers = @configurator.project_test_threads else raise NameError.new("Unrecognized batch workload type: #{workload}") end # Enqueue all the items the block will execute against things.each { |thing| @queue << thing } # Choose lesser of max workers or number of things to process & redefine workers # (It's neater and more efficient to avoid workers we won't use) workers = [1, [workers, things.size].min ].max threads = (1..workers).collect do thread = Thread.new do Thread.handle_interrupt(Exception => :never) do begin Thread.handle_interrupt(Exception => :immediate) do # Run tasks until there are no more enqueued loop do # pop(true) is non-blocking and raises ThreadError when queue is empty yield @queue.pop(true) end end # First, handle thread exceptions (should always be due to empty queue) rescue ThreadError => e # Typical case: do nothing and allow thread to wind down # ThreadError outside scope of expected empty queue condition unless e.message.strip.casecmp("queue empty") # Shutdown all worker threads shutdown_threads(threads) # Raise exception again after intervening raise(e) end # Second, catch every other kind of exception so we can intervene with thread cleanup. # Generally speaking, catching Exception is a no-no, but we must in this case. # Raise the exception again so that: # 1. Calling code knows something bad happened and handles appropriately # 2. Ruby runtime can handle most serious problems rescue Exception => e # Shutdown all worker threads shutdown_threads(threads) # Raise exception again after intervening raise(e) end end end # Hand thread to Enumerable collect() routine thread.abort_on_exception = true thread end # Hand worker threads to scheduler / wait for them to finish threads.each { |thread| thread.join } end
Parallelize work to be done: - Enqueue things (thread-safe) - Spin up a number of worker threads within constraints of project file config and amount of work - Each worker thread consumes one item from queue and runs the block against its details - When the queue is empty, the worker threads wind down
exec
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/build_batchinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/build_batchinator.rb
MIT
def shutdown_threads(workers) workers.each do |thread| next if thread == Thread.current thread.terminate end end
Terminate worker threads other than ourselves (we're already winding down)
shutdown_threads
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/build_batchinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/build_batchinator.rb
MIT
def inspect # TODO: When identifying information is added to constructor, insert it into `inspect()` string return this.class.name end
Override to prevent exception handling from walking & stringifying the object variables. Object variables are gigantic and produce a flood of output.
inspect
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator.rb
MIT
def set_verbosity(config) # PROJECT_VERBOSITY and PROJECT_DEBUG set at command line processing before Ceedling is loaded if (!!defined?(PROJECT_DEBUG) and PROJECT_DEBUG) eval("def project_debug() return true end", binding()) else eval("def project_debug() return false end", binding()) end if !!defined?(PROJECT_VERBOSITY) eval("def project_verbosity() return #{PROJECT_VERBOSITY} end", binding()) end end
Set up essential flattened config related to verbosity. We do this because early config validation failures may need access to verbosity, but the accessors won't be available until after configuration is validated.
set_verbosity
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator.rb
MIT
def merge_tools_defaults(config, default_config) msg = @reportinator.generate_progress( 'Collecting default tool configurations' ) @loginator.log( msg, Verbosity::OBNOXIOUS ) # config[:project] is guaranteed to exist / validated to exist but may not include elements referenced below # config[:test_build] and config[:release_build] are optional in a user project configuration release_build, _ = @config_walkinator.fetch_value( :project, :release_build, hash:config, default: DEFAULT_CEEDLING_PROJECT_CONFIG[:project][:release_build] ) test_preprocessing, _ = @config_walkinator.fetch_value( :project, :use_test_preprocessor, hash:config, default: DEFAULT_CEEDLING_PROJECT_CONFIG[:project][:use_test_preprocessor] ) backtrace, _ = @config_walkinator.fetch_value( :project, :use_backtrace, hash:config, default: DEFAULT_CEEDLING_PROJECT_CONFIG[:project][:use_backtrace] ) release_assembly, _ = @config_walkinator.fetch_value( :release_build, :use_assembly, hash:config, default: DEFAULT_CEEDLING_PROJECT_CONFIG[:release_build][:use_assembly] ) test_assembly, _ = @config_walkinator.fetch_value( :test_build, :use_assembly, hash:config, default: DEFAULT_CEEDLING_PROJECT_CONFIG[:test_build][:use_assembly] ) default_config.deep_merge( DEFAULT_TOOLS_TEST.deep_clone() ) default_config.deep_merge( DEFAULT_TOOLS_TEST_PREPROCESSORS.deep_clone() ) if (test_preprocessing != :none) default_config.deep_merge( DEFAULT_TOOLS_TEST_ASSEMBLER.deep_clone() ) if test_assembly default_config.deep_merge( DEFAULT_TOOLS_TEST_GDB_BACKTRACE.deep_clone() ) if (backtrace == :gdb) default_config.deep_merge( DEFAULT_TOOLS_RELEASE.deep_clone() ) if release_build default_config.deep_merge( DEFAULT_TOOLS_RELEASE_ASSEMBLER.deep_clone() ) if (release_build and release_assembly) end
The default tools (eg. DEFAULT_TOOLS_TEST) are merged into default config hash
merge_tools_defaults
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator.rb
MIT
def populate_tools_config(config) msg = @reportinator.generate_progress( 'Populating tool definition settings and expanding any string replacements' ) @loginator.log( msg, Verbosity::OBNOXIOUS ) config[:tools].each_key do |name| tool = config[:tools][name] if not tool.is_a?(Hash) raise CeedlingException.new( "Expected configuration for tool :#{name} is a Hash but found #{tool.class}" ) end # Populate name if not given tool[:name] = name.to_s if (tool[:name].nil?) # Populate $stderr redirect option tool[:stderr_redirect] = StdErrRedirect::NONE if (tool[:stderr_redirect].nil?) # Populate optional option to control verification of executable in search paths tool[:optional] = false if (tool[:optional].nil?) end end
Process our tools - :tools entries - Insert missing names for - Handle needed defaults - Configure test runner from backtrace configuration
populate_tools_config
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator.rb
MIT
def populate_tools_shortcuts(config) msg = @reportinator.generate_progress( 'Processing tool definition shortcuts' ) @loginator.log( msg, Verbosity::OBNOXIOUS ) prefix = 'tools_' config[:tools].each do |name, tool| # Lookup shortcut tool definition (:tools_<name>) shortcut = (prefix + name.to_s).to_sym # Logging message to be built up msg = '' # Try to lookup the executable from user config executable, _ = @config_walkinator.fetch_value(shortcut, :executable, hash:config ) # Try to lookup arguments from user config args_to_add, _ = @config_walkinator.fetch_value(shortcut, :arguments, hash:config, default: [] ) # If either tool definition modification is happening, start building the logging message if !args_to_add.empty? or !executable.nil? msg += " > #{name}\n" end # Log the executable and redefine the tool config if !executable.nil? msg += " executable: \"#{executable}\"\n" tool[:executable] = executable end # Log the arguments and add to the tool config if !args_to_add.empty? msg += " arguments: " + args_to_add.map{|arg| "\"#{arg}\""}.join( ', ' ) + "\n" tool[:arguments].concat( args_to_add ) end # Log @loginator.log( msg, Verbosity::DEBUG ) if !msg.empty? end end
Process any tool definition shortcuts - Append extra arguments - Redefine executable :tools_<name> :arguments: [...] :executable: '...'
populate_tools_shortcuts
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator.rb
MIT
def eval_environment_variables(config) return if config[:environment].nil? msg = @reportinator.generate_progress( 'Processing environment variables' ) @loginator.log( msg, Verbosity::OBNOXIOUS ) config[:environment].each do |hash| key = hash.keys[0] # Get first (should be only) environment variable entry value = hash[key] # Get associated value items = [] # Special case handling for :path environment variable entry # File::PATH_SEPARATOR => ':' (Unix-ish) or ';' (Windows) interstitial = ((key == :path) ? File::PATH_SEPARATOR : ' ') # Create an array container for the value of this entry # - If the value is an array, get it # - Otherwise, place value in a single item array items = ((value.class == Array) ? hash[key] : [value]) # Process value array items.each do |item| # Process each item for Ruby string replacement if item.is_a? String and item =~ PATTERNS::RUBY_STRING_REPLACEMENT item.replace( @system_wrapper.module_eval( item ) ) end end # Join any value items (become a flattened string) # - With path separator if the key was :path # - With space otherwise hash[key] = items.join( interstitial ) # Set the environment variable for our session @system_wrapper.env_set( key.to_s.upcase, hash[key] ) @loginator.log( " - #{key.to_s.upcase}: \"#{hash[key]}\"", Verbosity::DEBUG ) end end
Process environment variables set in configuration file (Each entry within the :environment array is a hash)
eval_environment_variables
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator.rb
MIT
def flattenify(config) new_hash = {} config.each_key do | parent | # Gracefully handle empty top-level entries next if (config[parent].nil?) case config[parent] when Array config[parent].each do |hash| key = "#{parent.to_s.downcase}_#{hash.keys[0].to_s.downcase}".to_sym new_hash[key] = hash[hash.keys[0]] end when Hash config[parent].each_pair do | child, value | key = "#{parent.to_s.downcase}_#{child.to_s.downcase}".to_sym new_hash[key] = value end # Handle entries with no children, only values else new_hash["#{parent.to_s.downcase}".to_sym] = config[parent] end end return new_hash end
create a flattened hash from the original configuration structure
flattenify
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_builder.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_builder.rb
MIT
def populate_with_defaults(config, defaults) defaults.each do |key, value| # If config is missing the same key, copy in the default entry if config[key].nil? config[key] = value.is_a?(Hash) ? value.deep_clone : value # Continue recursively for hash entries elsif config[key].is_a?(Hash) && value.is_a?(Hash) populate_with_defaults(config[key], value) end end end
If config lacks an entry present in defaults posseses, add the default entry Processes recursively
populate_with_defaults
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_builder.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_builder.rb
MIT
def inspect # TODO: When identifying information is added to constructor, insert it into `inspect()` string return this.class.name end
Override to prevent exception handling from walking & stringifying the object variables. Object variables are gigantic and produce a flood of output.
inspect
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_plugins.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_plugins.rb
MIT
def find_rake_plugins(config, plugin_paths) @rake_plugins = [] plugins_with_path = [] config[:plugins][:enabled].each do |plugin| if path = plugin_paths[(plugin + '_path').to_sym] rake_plugin_path = File.join(path, "#{plugin}.rake") if @file_wrapper.exist?( rake_plugin_path ) @rake_plugins << {:plugin => plugin, :path => rake_plugin_path} end end end return @rake_plugins end
Gather up and return .rake filepaths that exist in plugin paths
find_rake_plugins
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_plugins.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_plugins.rb
MIT
def find_programmatic_plugins(config, plugin_paths) @programmatic_plugins = [] config[:plugins][:enabled].each do |plugin| if path = plugin_paths[(plugin + '_path').to_sym] plugin_path = File.join( path, "lib", "#{plugin}.rb" ) if @file_wrapper.exist?( plugin_path ) @programmatic_plugins << {:plugin => plugin, :root_path => path} end end end return @programmatic_plugins end
Gather up names of .rb `Plugin` subclasses and root paths that exist in plugin paths + lib/
find_programmatic_plugins
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_plugins.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_plugins.rb
MIT
def find_config_plugins(config, plugin_paths) @config_plugins = [] plugins_with_path = [] config[:plugins][:enabled].each do |plugin| if path = plugin_paths[(plugin + '_path').to_sym] config_plugin_path = File.join(path, "config", "#{plugin}.yml") if @file_wrapper.exist?( config_plugin_path ) @config_plugins << {:plugin => plugin, :path => config_plugin_path} end end end return @config_plugins end
Gather up and return config .yml filepaths that exist in plugin paths + config/
find_config_plugins
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_plugins.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_plugins.rb
MIT
def find_plugin_yml_defaults(config, plugin_paths) defaults_with_path = {} config[:plugins][:enabled].each do |plugin| if path = plugin_paths[(plugin + '_path').to_sym] default_path = File.join(path, 'config', 'defaults.yml') if @file_wrapper.exist?( default_path ) defaults_with_path[plugin.to_sym] = default_path @plugin_yml_defaults << plugin end end end return defaults_with_path end
Gather up and return default .yml filepaths that exist on-disk
find_plugin_yml_defaults
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_plugins.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_plugins.rb
MIT
def find_plugin_hash_defaults(config, plugin_paths) defaults_hash = {} config[:plugins][:enabled].each do |plugin| if path = plugin_paths[(plugin + '_path').to_sym] default_path = File.join(path, "config", "defaults_#{plugin}.rb") if @file_wrapper.exist?( default_path ) @system_wrapper.require_file( "defaults_#{plugin}.rb" ) object = eval("get_default_config()") defaults_hash[plugin.to_sym()] = object @plugin_hash_defaults << plugin end end end return defaults_hash end
Gather up and return defaults generated by Ruby code in plugin paths + config/
find_plugin_hash_defaults
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_plugins.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_plugins.rb
MIT
def inspect # TODO: When identifying information is added to constructor, insert it into `inspect()` string return this.class.name end
Override to prevent exception handling from walking & stringifying the object variables. Object variables are gigantic and produce a flood of output.
inspect
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_setup.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_setup.rb
MIT
def exists?(config, *keys) hash, _ = @config_walkinator.fetch_value( *keys, hash:config ) exist = !hash.nil? if (not exist) walk = @reportinator.generate_config_walk( keys ) @loginator.log( "Required config file entry #{walk} does not exist.", Verbosity::ERRORS ) end return exist end
Walk into config hash verify existence of data at key depth
exists?
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_validator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_validator.rb
MIT
def validate_path_list(config, *keys) exist = true list, depth = @config_walkinator.fetch_value( *keys, hash:config ) # Return early if we couldn't walk into hash and find a value return false if (list.nil?) list.each do |path| # Trim add/subtract notation & glob specifiers _path = FilePathUtils::no_decorators( path ) next if _path.empty? # Path begins with or is entirely a glob, skip it # If (partial) path does not exist, complain if (not @file_wrapper.exist?( _path )) walk = @reportinator.generate_config_walk( keys, depth ) @loginator.log( "Config path #{walk} => '#{_path}' does not exist in the filesystem.", Verbosity::ERRORS ) exist = false end end return exist end
Walk into config hash. verify existence of path(s) at given key depth. Paths are either full simple paths or a simple portion of a path up to a glob.
validate_path_list
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_validator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_validator.rb
MIT
def validate_paths_entries(config, key) valid = true keys = [:paths, key] walk = @reportinator.generate_config_walk( keys ) list, _ = @config_walkinator.fetch_value( *keys, hash:config ) # Return early if we couldn't walk into hash and find a value return false if (list.nil?) list.each do |path| dirs = [] # Working list # Trim add/subtract notation _path = FilePathUtils::no_aggregation_decorators( path ) if @file_wrapper.exist?( _path ) and !@file_wrapper.directory?( _path ) # Path is a simple filepath (not a directory) warning = "#{walk} => '#{_path}' is a filepath and will be ignored (FYI :paths is directory-oriented while :files is file-oriented)" @loginator.log( warning, Verbosity::COMPLAIN ) next # Skip to next path end # Expand paths using Ruby's Dir.glob() # - A simple path will yield that path # - A path glob will expand to one or more paths _reformed = FilePathUtils::reform_subdirectory_glob( _path ) @file_wrapper.directory_listing( _reformed ).each do |entry| # For each result, add it to the working list *if* it's a directory dirs << entry if @file_wrapper.directory?(entry) end # Handle edge case of subdirectories glob but not subdirectories # (Containing parent directory will still exist) next if dirs.empty? and _path =~ /\/\*{1,2}$/ # Path did not work -- must be malformed glob or glob referencing path that does not exist. # (An earlier step validates all simple directory paths). if dirs.empty? error = "#{walk} => '#{_path}' yielded no directories -- matching glob is malformed or directories do not exist" @loginator.log( error, Verbosity::ERRORS ) valid = false end end return valid end
Validate :paths entries, exercising each entry as Ceedling directory glob (variation of Ruby glob)
validate_paths_entries
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_validator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_validator.rb
MIT
def validate_files_entries(config, key) valid = true keys = [:files, key] walk = @reportinator.generate_config_walk( keys ) list, _ = @config_walkinator.fetch_value( *keys, hash:config ) # Return early if we couldn't walk into hash and find a value return false if (list.nil?) list.each do |path| # Trim add/subtract notation _path = FilePathUtils::no_aggregation_decorators( path ) if @file_wrapper.exist?( _path ) and @file_wrapper.directory?( _path ) # Path is a simple directory path (and is naturally ignored by FileList without a glob pattern) warning = "#{walk} => '#{_path}' is a directory path and will be ignored (FYI :files is file-oriented while :paths is directory-oriented)" @loginator.log( warning, Verbosity::COMPLAIN ) next # Skip to next path end filelist = @file_wrapper.instantiate_file_list(_path) # If file list is empty, complain if (filelist.size == 0) error = "#{walk} => '#{_path}' yielded no files -- matching glob is malformed or files do not exist" @loginator.log( error, Verbosity::ERRORS ) valid = false end end return valid end
Validate :files entries, exercising each entry as FileList glob
validate_files_entries
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/configurator_validator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/configurator_validator.rb
MIT
def defines(topkey:@topkey, subkey:, filepath:nil, default:[]) defines = @config_matchinator.get_config(primary:topkey, secondary:subkey) if defines == nil then return default # Flatten to handle list-nested YAML aliasing (should have already been flattened during validation) elsif defines.is_a?(Array) then return defines.flatten elsif defines.is_a?(Hash) arg_hash = { hash: defines, filepath: filepath, section: topkey, context: subkey } return @config_matchinator.matches?(**arg_hash) end # Handle unexpected config element type return [] end
Defaults to inspecting configurations beneath top-level :defines (But, we can also lookup defines symbol lists within framework configurations--:unity, :cmock, :cexception)
defines
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/defineinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/defineinator.rb
MIT
def generate_test_definition(filepath:) defines = [] if @configurator.defines_use_test_definition # Get filename with no path or extension test_def = File.basename(filepath, '.*').strip # Replace any non-ASCII characters with underscores test_def = test_def.clean_encoding('_') # Replace all non-alphanumeric characters (including spaces/punctuation but excluding underscores) with underscores test_def.gsub!(/[^0-9a-z_]/i, '_') # Convert to all caps test_def.upcase! # Add leading and trailiing underscores unless they already exist test_def = test_def.start_with?('_') ? test_def : ('_' + test_def) test_def = test_def.end_with?('_') ? test_def : (test_def + '_') # Add the test filename as a #define symbol to the array defines << test_def end return defines end
Optionally create a command line compilation symbol that is a test file's sanitized/converted name
generate_test_definition
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/defineinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/defineinator.rb
MIT
def find_test_file_from_filepath(filepath) # Strip filepath down to filename and remove file extension name = File.basename( filepath ).ext('') return find_test_file_from_name( name ) end
Find test filepath from another filepath (e.g. test executable with same base name, a/path/test_foo.exe)
find_test_file_from_filepath
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/file_finder.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/file_finder.rb
MIT
def find_test_file_from_name(name) test_file = name + @configurator.extension_source found_path = @file_finder_helper.find_file_in_collection(test_file, @configurator.collection_all_tests, :error, name) return found_path end
Find test filepath from only the base name of a test file (e.g. 'test_foo')
find_test_file_from_name
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/file_finder.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/file_finder.rb
MIT
def collect_paths(paths) plus = Set.new # All real, expanded directory paths to add minus = Set.new # All real, expanded paths to exclude # Iterate each path possibly decorated with aggregation modifiers and/or containing glob characters paths.each do |path| dirs = [] # Working list for evaluated directory paths # Get path stripped of any +:/-: aggregation modifier _path = FilePathUtils.no_aggregation_decorators( path ) # If it's a glob, modify it for Ceedling's recursive subdirectory convention _reformed = FilePathUtils::reform_subdirectory_glob( _path ) # Expand paths using Ruby's Dir.glob() # - A simple path will yield that path # - A path glob will expand to one or more paths # Note: `sort()` because of Github Issue #860 @file_wrapper.directory_listing( _reformed ).sort.each do |entry| # For each result, add it to the working list *only* if it's a directory # Previous validation has already made warnings about filepaths in the list dirs << entry if @file_wrapper.directory?(entry) end # For recursive directory glob at end of a path, collect parent directories too. # Ceedling's recursive glob convention includes parent directories (unlike Ruby's glob). if path.end_with?('/**') or path.end_with?('/*') parents = [] dirs.each {|dir| parents << File.join(dir, '..')} # Handle edge case of subdirectory glob but no subdirectories and therefore no parents # (Containing parent directory still exists) parents << FilePathUtils.no_decorators( _path ) if dirs.empty? dirs = parents + dirs end # Based on aggregation modifiers, add entries to plus and minus sets. # Use full, absolute paths to ensure logical paths are compared properly. # './<path>' is logically equivalent to '<path>' but is not equivalent as strings. # Because plus and minus are sets, each insertion eliminates any duplicates # (such as the parent directories for each directory as added above). dirs.each do |dir| abs_path = File.expand_path( dir ) if FilePathUtils.add_path?( path ) plus << abs_path else minus << abs_path end end end # Use Set subtraction operator to remove any excluded paths paths = (plus - minus).to_a paths.map! {|path| shortest_path_from_working(path) } return paths end
Build up a directory path list from one or more strings or arrays of (+:/-:) simple paths & globs
collect_paths
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/file_path_collection_utils.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/file_path_collection_utils.rb
MIT
def revise_filelist(list, revisions) plus = Set.new # All real, expanded directory paths to add minus = Set.new # All real, expanded paths to exclude # Build base plus set for revised path list.each do |path| # Start with expanding all list entries to absolute paths plus << File.expand_path( path ) end revisions.each do |revision| # Include or exclude revisions in file list path = FilePathUtils.no_aggregation_decorators( revision ) # Working list of revisions filepaths = [] # Expand path by pattern as needed and add only filepaths to working list @file_wrapper.directory_listing( path ).each do |entry| filepaths << File.expand_path( entry ) if !@file_wrapper.directory?( entry ) end # Handle +: / -: revisions if FilePathUtils.add_path?( revision ) plus.merge( filepaths ) else minus.merge( filepaths ) end end # Use Set subtraction operator to remove any excluded paths paths = (plus - minus).to_a paths.map! {|path| shortest_path_from_working(path) } return FileList.new( paths ) end
Given a file list, add to it or remove from it considering (+:/-:) aggregation operators. Rake's FileList does not robustly handle relative filepaths and patterns. So, we rebuild the FileList ourselves and return it. TODO: Replace FileList with our own, better version.
revise_filelist
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/file_path_collection_utils.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/file_path_collection_utils.rb
MIT
def ceedling_form_filepath(destination_path, original_filepath, new_extension=nil) filename = File.basename(original_filepath) filename.replace(filename.ext(new_extension)) if (!new_extension.nil?) return File.join( destination_path.gsub(/\\/, '/'), filename ) end
global utility methods (for plugins, project files, etc.)
ceedling_form_filepath
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/file_path_utils.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/file_path_utils.rb
MIT
def directory?(path) return File.directory?(path) end
Is path a directory and does it exist?
directory?
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/file_wrapper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/file_wrapper.rb
MIT
def filter_test_cases(test_cases) _test_cases = test_cases.clone # Filter tests which contain test_case_name passed by `--test_case` argument if [email protected]_test_case.empty? _test_cases.delete_if { |i| !(i[:test] =~ /#{@configurator.include_test_case}/) } end # Filter tests which contain test_case_name passed by `--exclude_test_case` argument if [email protected]_test_case.empty? _test_cases.delete_if { |i| i[:test] =~ /#{@configurator.exclude_test_case}/ } end return _test_cases end
Filter list of test cases: --test_case --exclude_test_case @return Array - list of the test_case hashses {:test, :line_number}
filter_test_cases
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/generator_test_results.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/generator_test_results.rb
MIT
def regenerate_test_executable_stdout(total:, failed:, ignored:, output:[]) values = { :total => total, :failed => failed, :ignored => ignored, :output => output.map {|line| line.strip()}.join("\n"), :result => (failed > 0) ? 'FAIL' : 'OK' } return UNITY_TEST_RESULTS_TEMPLATE % values end
Fill out a template to mimic Unity's test executable output
regenerate_test_executable_stdout
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/generator_test_results.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/generator_test_results.rb
MIT
def initialize(config:, test_file_contents:, preprocessed_file_contents:nil) @unity_runner_generator = UnityTestRunnerGenerator.new( config ) # Reduced information set @test_cases = [] # Full information set used for runner generation @test_cases_internal = [] parse_test_file( test_file_contents, preprocessed_file_contents ) end
This class is not within any DIY context. It is instantiated on demand for each test file processed in a build.
initialize
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/generator_test_runner.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/generator_test_runner.rb
MIT
def load(fn) open(fn) do |mf| lines = mf.read lines.gsub!(/#[^\n]*\n/m, "") # remove comments lines.gsub!(/\\\n/, ' ') # string together line continuations into single line lines.split("\n").each do |line| process_line(line) end end end
Load the makefile dependencies in +fn+.
load
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/makefile.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/makefile.rb
MIT
def process_line(line) # split on presence of task demaractor followed by space (i.e don't get confused by a colon in a win path) file_tasks, args = line.split(/:\s/) return if args.nil? # split at non-escaped space boundary between files (i.e. escaped spaces in paths are left alone) dependents = args.split(/\b\s+/) # replace escaped spaces and clean up any extra whitespace dependents.map! { |path| path.gsub(/\\ /, ' ').strip } file_tasks.strip.split.each do |file_task| file file_task => dependents end end
Process one logical line of makefile data.
process_line
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/makefile.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/makefile.rb
MIT
def code_lines(input) comment_block = false full_line = '' input.each_line do |line| m = line.match /(.*)\\\s*$/ if (!m.nil?) full_line += m[1] elsif full_line.empty? _line, comment_block = clean_code_line( line, comment_block ) yield( _line ) else _line, comment_block = clean_code_line( full_line + line, comment_block ) yield( _line ) full_line = '' end end end
This parser accepts a collection of lines which it will sweep through and tidy, giving the purified lines to the block (one line at a time) for further analysis. It analyzes a single line at a time, which is far more memory efficient and faster for large files. However, this requires it to also handle backslash line continuations as a single line at this point.
code_lines
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/parsing_parcels.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/parsing_parcels.rb
MIT
def inspect return this.class.name end
Override to prevent exception handling from walking & stringifying the object variables. Plugin's object variables are gigantic and produce a flood of output.
inspect
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/plugin.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/plugin.rb
MIT
def assemble_test_results(results_list, options={:boom => false}) aggregated_results = new_results() results_list.each do |result_path| results = @plugin_reportinator_helper.fetch_results( result_path, options ) @plugin_reportinator_helper.process_results(aggregated_results, results) end return aggregated_results end
# # Sample Test Results Output File (YAML) # ====================================== # # TestUsartModel.fail: # --- # :source: # :file: test/TestUsartModel.c # :dirname: test # :basename: TestUsartModel.c # :successes: # - :test: testGetBaudRateRegisterSettingShouldReturnAppropriateBaudRateRegisterSetting # :line: 24 # :message: '' # :unity_test_time: 0 # - :test: testGetFormattedTemperatureFormatsTemperatureFromCalculatorAppropriately # :line: 49 # :message: '' # :unity_test_time: 0 # - :test: testShouldReturnErrorMessageUponInvalidTemperatureValue # :line: 55 # :message: '' # :unity_test_time: 0 # - :test: testShouldReturnWakeupMessage # :line: 61 # :message: '' # :unity_test_time: 0 # :failures: # - :test: testFail # :line: 39 # :message: Expected 2 Was 3 # :unity_test_time: 0 # :ignores: # - :test: testIgnore # :line: 34 # :message: '' # :unity_test_time: 0 # :counts: # :total: 6 # :passed: 4 # :failed: 1 # :ignored: 1 # :stdout: [] # :time: 0.006512000225484371
assemble_test_results
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/plugin_reportinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/plugin_reportinator.rb
MIT
def extract_file_as_array_from_expansion(input, filepath) ## ## Iterate through all lines and alternate between extract and ignore modes. ## All lines between a '#' line containing the filepath to extract (a line marker) and the next '#' line should be extracted. ## ## GCC preprocessor output line marker format: `# <linenum> "<filename>" <flags>` ## ## Documentation on line markers in GCC preprocessor output: ## https://gcc.gnu.org/onlinedocs/gcc-3.0.2/cpp_9.html ## ## Notes: ## 1. Successive blocks can all be from the same source text file without a different, intervening '#' line. ## Multiple back-to-back blocks could all begin with '# 99 "path/file.c"'. ## 2. The first line of the file could start a text block we care about. ## 3. End of file could end a text block. ## 4. Usually, the first line marker contains no trailing flag. ## 5. Different preprocessors conforming to the GCC output standard may use different trailiing flags. ## 6. Our simple ping-pong-between-line-markers extraction technique does not require decoding flags. ## # Expand filepath under inspection to ensure proper match extaction_filepath = File.expand_path( filepath ) # Preprocessor directive blocks generally take the form of '# <digits> <text> [optional digits]' directive = /^# \d+ \"/ # Line markers have the specific form of '# <digits> "path/filename.ext" [optional digits]' (see above) line_marker = /^#\s\d+\s\"(.+)\"/ # Boolean to ping pong between line-by-line extract/ignore extract = false # Collection of extracted lines lines = [] # Use `each_line()` instead of `readlines()` (chomp removes newlines). # `each_line()` processes the IO buffer one line at a time instead of ingesting lines in an array. # At large buffer sizes needed for potentially lengthy preprocessor output this is far more memory efficient and faster. input.each_line( chomp:true ) do |line| # Clean up any oddball characters in an otherwise ASCII document line = line.clean_encoding # Handle expansion extraction if the line is not a preprocessor directive if extract and not line =~ directive # Strip a line so we can omit useless blank lines _line = line.strip() # Restore text with left-side whitespace if previous stripping left some text _line = line.rstrip() if !_line.empty? # Collect extracted lines lines << _line # Otherwise the line contained a preprocessor directive; drop out of extract mode else extract = false end # Enter extract mode if the line is a preprocessor line marker with filepath of interest matches = line.match( line_marker ) if matches and matches.size() > 1 filepath = File.expand_path( matches[1].strip() ) extract = true if extaction_filepath == filepath end end return lines end
# # Preprocessor Expansion Output Handling # ====================================== # # Preprocessing expands macros, eliminates comments, strips out #ifdef code, etc. # However, it also expands in place each #include'd file. So, we must extract # only the lines of the file that belong to the file originally preprocessed. # # We do this by examininig each line and ping-ponging between extracting and # ignoring text based on preprocessor statements referencing the file we're # seeking to reassemble. # # Note that the same text handling approach applies to full preprocessor # expansion as directives only expansion. # # Example preprocessed expansion output # -------------------------------------- # # # 14 "test/TestUsartModel.c" 2 # # void setUp(void) # { # } # # void tearDown(void) # { # } # # void testUsartModelInit(void) # { # TemperatureFilter_Init_CMockExpect(26); # # UsartModel_Init(); # } # # 55 "test/TestUsartModel.c" # void testGetBaudRateRegisterSettingShouldReturnAppropriateBaudRateRegisterSetting(void) # { # uint8 dummyRegisterSetting = 17; # UsartModel_CalculateBaudRateRegisterSetting_CMockExpectAndReturn(58, 48054857, 115200, dummyRegisterSetting); # # UnityAssertEqualNumber((UNITY_INT)(UNITY_UINT8 )((dummyRegisterSetting)), (UNITY_INT)(UNITY_UINT8 )((UsartModel_GetBaudRateRegisterSetting())), (((void*)0)), (UNITY_UINT)(60), UNITY_DISPLAY_STYLE_UINT8); # } # # void testIgnore(void) # { # UnityIgnore( (((void*)0)), (UNITY_UINT)(65)); # } # # 75 "test/TestUsartModel.c" # void testGetFormattedTemperatureFormatsTemperatureFromCalculatorAppropriately(void) # { # TemperatureFilter_GetTemperatureInCelcius_CMockExpectAndReturn(77, 25.0f); # UnityAssertEqualString((const char*)(("25.0 C\n")), (const char*)((UsartModel_GetFormattedTemperature())), (((void*)0)), (UNITY_UINT)(78)); # } # # void testShouldReturnErrorMessageUponInvalidTemperatureValue(void) # { # TemperatureFilter_GetTemperatureInCelcius_CMockExpectAndReturn(83, -__builtin_huge_valf()); # UnityAssertEqualString((const char*)(("Temperature sensor failure!\n")), (const char*)((UsartModel_GetFormattedTemperature())), (((void*)0)), (UNITY_UINT)(84)); # } # # void testShouldReturnWakeupMessage(void) # { # UnityAssertEqualString((const char*)(("It's Awesome Time!\n")), (const char*)((UsartModel_GetWakeupMessage())), (((void*)0)), (UNITY_UINT)(89)); # } `input` must have the interface of IO -- StringIO for testing or File in typical use
extract_file_as_array_from_expansion
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/preprocessinator_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/preprocessinator_extractor.rb
MIT
def extract_file_as_string_from_expansion(input, filepath) return extract_file_as_array_from_expansion(input, filepath).join( "\n" ) end
Simple variation of preceding that returns file contents as single string
extract_file_as_string_from_expansion
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/preprocessinator_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/preprocessinator_extractor.rb
MIT
def extract_test_directive_macro_calls(file_contents) # Look for TEST_SOURCE_FILE("...") and TEST_INCLUDE_PATH("...") in a string (i.e. a file's contents as a string) regexes = [ /(#{PATTERNS::TEST_SOURCE_FILE})/, /(#{PATTERNS::TEST_INCLUDE_PATH})/ ] return extract_tokens_by_regex_list( file_contents, *regexes ).map(&:first) end
Extract all test directive macros as a list from a file as string
extract_test_directive_macro_calls
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/preprocessinator_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/preprocessinator_extractor.rb
MIT
def extract_pragmas(file_contents) return extract_multiline_directives( file_contents, 'pragma' ) end
Extract all pragmas as a list from a file as string
extract_pragmas
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/preprocessinator_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/preprocessinator_extractor.rb
MIT
def extract_include_guard(file_contents) # Look for first occurrence of #ifndef <sring> followed by #define <string> regex = /#\s*ifndef\s+(\w+)(?:\s*\n)+\s*#\s*define\s+(\w+)/ matches = file_contents.match( regex ) # Return if no match results return nil if matches.nil? # Return if match results are not expected size return nil if matches.size != 3 # Return if #ifndef <string> does not match #define <string> return nil if matches[1] != matches[2] # Return string in common return matches[1] end
Find include guard in file contents as string
extract_include_guard
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/preprocessinator_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/preprocessinator_extractor.rb
MIT
def extract_macro_defs(file_contents, include_guard) macro_definitions = extract_multiline_directives( file_contents, 'define' ) # Remove an include guard if provided macro_definitions.reject! {|macro| macro.include?( include_guard ) } if !include_guard.nil? return macro_definitions end
Extract all macro definitions as a list from a file as string
extract_macro_defs
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/preprocessinator_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/preprocessinator_extractor.rb
MIT
def generate_banner(message, width=nil) # --------- # <Message> # --------- dash_count = ((width.nil?) ? Unicode::DisplayWidth.of( message.strip ) : width) return "#{'-' * dash_count}\n#{message}\n#{'-' * dash_count}\n" end
# Generates a banner for a message based on the length of the message or a given width. ==== Attributes * _message_: The message to put. * _width_: The width of the message. If nil the size of the banner is determined by the length of the message. ==== Examples rp = Reportinator.new rp.generate_banner("Hello world!") => "------------\nHello world!\n------------\n" rp.generate_banner("Hello world!", 3) => "---\nHello world!\n---\n"
generate_banner
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/reportinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/reportinator.rb
MIT
def inspect # TODO: When identifying information is added to constructor, insert it into `inspect()` string return this.class.name end
Override to prevent exception handling from walking & stringifying the object variables. Object variables are gigantic and produce a flood of output.
inspect
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/setupinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/setupinator.rb
MIT
def do_setup( app_cfg ) @config_hash = app_cfg[:project_config] ## ## 1. Miscellaneous handling and essential configuration prep ## # Set special purpose test case filters (from command line) @configurator.include_test_case = app_cfg[:include_test_case] @configurator.exclude_test_case = app_cfg[:exclude_test_case] # Verbosity handling @configurator.set_verbosity( config_hash ) # Logging configuration @loginator.set_logfile( app_cfg[:log_filepath] ) @configurator.project_logging = @loginator.project_logging log_step( 'Validating configuration contains minimum required sections', heading:false ) # Complain early about anything essential that's missing @configurator.validate_essential( config_hash ) # Merge any needed runtime settings into user configuration @configurator.merge_ceedling_runtime_config( config_hash, CEEDLING_RUNTIME_CONFIG.deep_clone ) ## ## 2. Handle basic configuration ## log_step( 'Base configuration handling', heading:false ) # Evaluate environment vars before plugin configurations that might reference with inline Ruby string expansion @configurator.eval_environment_variables( config_hash ) # Standardize paths and add to Ruby load paths plugins_paths_hash = @configurator.prepare_plugins_load_paths( app_cfg[:ceedling_plugins_path], config_hash ) ## ## 3. Plugin Handling ## log_step( 'Plugin Handling' ) # Plugin handling @configurator.discover_plugins( plugins_paths_hash, config_hash ) @configurator.merge_config_plugins( config_hash ) @configurator.populate_plugins_config( plugins_paths_hash, config_hash ) ## ## 4. Collect and apply defaults to user configuration ## log_step( 'Assembling Default Settings' ) # Assemble defaults defaults_hash = DEFAULT_CEEDLING_PROJECT_CONFIG.deep_clone() @configurator.merge_tools_defaults( config_hash, defaults_hash ) @configurator.populate_cmock_defaults( config_hash, defaults_hash ) @configurator.merge_plugins_defaults( plugins_paths_hash, config_hash, defaults_hash ) # Set any missing essential or plugin values in configuration with assembled default values @configurator.populate_with_defaults( config_hash, defaults_hash ) ## ## 5. Fill out / modify remaining configuration from user configuration + defaults ## log_step( 'Completing Project Configuration' ) # Populate Unity configuration with values to tie vendor tool configurations together @configurator.populate_unity_config( config_hash ) # Populate CMock configuration with values to tie vendor tool configurations together @configurator.populate_cmock_config( config_hash ) # Configure test runner generation @configurator.populate_test_runner_generation_config( config_hash ) # Automagically enable use of exceptions based on CMock settings @configurator.populate_exceptions_config( config_hash ) # Evaluate environment vars again before subsequent configurations that might reference with inline Ruby string expansion @configurator.eval_environment_variables( config_hash ) # Standardize values and expand inline Ruby string substitutions @configurator.eval_paths( config_hash ) @configurator.eval_flags( config_hash ) @configurator.eval_defines( config_hash ) @configurator.standardize_paths( config_hash ) # Fill out any missing tool config value @configurator.populate_tools_config( config_hash ) # From any tool definition shortcuts: # - Redefine executable if set # - Add arguments from tool definition shortcuts if set @configurator.populate_tools_shortcuts( config_hash ) # Configure test runner build & runtime options @test_runner_manager.configure_build_options( config_hash ) @test_runner_manager.configure_runtime_options( app_cfg[:include_test_case], app_cfg[:exclude_test_case] ) ## ## 6. Validate configuration ## log_step( 'Validating final project configuration', heading:false ) @configurator.validate_final( config_hash, app_cfg ) ## ## 7. Flatten configuration + process it into globals and accessors ## # Skip logging this step as the end user doesn't care about this internal preparation # Partially flatten config + build Configurator accessors and globals @configurator.build( app_cfg[:ceedling_lib_path], app_cfg[:logging_path], config_hash, :environment ) ## ## 8. Final plugins handling ## # Detailed logging already happend for plugin processing log_step( 'Loading Plugins' ) @configurator.insert_rake_plugins( @configurator.rake_plugins ) # Merge in any environment variables that plugins specify after the main build @plugin_manager.load_programmatic_plugins( @configurator.programmatic_plugins, @ceedling ) do |env| # Evaluate environment vars that plugins may have added @configurator.eval_environment_variables( env ) @configurator.build_supplement( config_hash, env ) end # Inject dependencies for plugin needs @plugin_reportinator.set_system_objects( @ceedling ) end
Load up all the constants and accessors our rake files, objects, & external scripts will need.
do_setup
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/setupinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/setupinator.rb
MIT
def log_step(msg, heading:true) if heading msg = @reportinator.generate_heading( @loginator.decorate( msg, LogLabels::CONSTRUCT ) ) else # Progress message msg = "\n" + @reportinator.generate_progress( @loginator.decorate( msg, LogLabels::CONSTRUCT ) ) end @loginator.log( msg, Verbosity::OBNOXIOUS ) end
Neaten up a build step with progress message and some scope encapsulation
log_step
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/setupinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/setupinator.rb
MIT
def tcsh_shell? # once run a single time, return state determined at that execution return @tcsh_shell unless @tcsh_shell.nil? result = @system_wrapper.shell_backticks(command:'echo $version') if ((result[:exit_code] == 0) and (result[:output].strip =~ /^tcsh/)) @tcsh_shell = true else @tcsh_shell = false end return @tcsh_shell end
# Checks the system shell to see if it a tcsh shell.
tcsh_shell?
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/system_utils.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/system_utils.rb
MIT
def windows? return SystemWrapper.windows? end
class method so as to be mockable for tests
windows?
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/system_wrapper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/system_wrapper.rb
MIT
def shell_capture3(command:, boom:false) # Beginning with later versions of Ruby2, simple exit codes were replaced # by the more capable and robust Process::Status. # Parts of Process::Status's behavior is similar to an integer exit code in # some operations but not all. exit_code = 0 stdout = '' # Safe initialization defaults stderr = '' # Safe initialization defaults status = nil # Safe initialization default # Use popen3 instead to control the IO reading, as Capture3 has blocking / locking potential Open3.popen3(command) do |stdin, out, err, wait_thread| # Close stdin since we don't use it stdin.close readers = [out, err] writers = [] start_time = Time.now out_chunks = [] err_chunks = [] # Read from pipes until process exits and pipes are empty while !readers.empty? # Wait up to 1 second for data on either pipe ready = IO.select(readers, writers, [], 1) next unless ready ready[0].each do |io| begin chunk = io.read_nonblock(4096) if io == out out_chunks << chunk else err_chunks << chunk end rescue EOFError # Remove finished streams from monitoring readers.delete(io) io.close rescue IO::WaitReadable # Nothing available right now, will try again next end end end status = wait_thread.value stdout = out_chunks.join stderr = err_chunks.join end # If boom, then capture the actual exit code. # Otherwise, leave it as zero as though execution succeeded. exit_code = status.exitstatus.freeze if boom and !status.nil? # (Re)set the global system exit code so everything matches $exit_code = exit_code return { # Combine stdout & stderr streams for complete output output: (stdout + stderr).to_s.freeze, # Individual streams for detailed logging stdout: stdout.freeze, stderr: stderr.freeze, # Relay full Process::Status status: status.freeze, # Provide simple exit code accessor exit_code: exit_code.freeze } end
If set, `boom` allows a non-zero exit code in results. Otherwise, disabled `boom` forces a success exit code but collects errors.
shell_capture3
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/system_wrapper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/system_wrapper.rb
MIT
def collect_simple_context( filepath, input, *args ) all_options = [ :build_directive_include_paths, :build_directive_source_files, :includes, :test_runner_details ] # Code error check--bad context symbol argument args.each do |context| next if context == :all msg = "Unrecognized test context for collection :#{context}" raise CeedlingException.new( msg ) if !all_options.include?( context ) end # Handle the :all shortcut to redefine list to include all contexts args = all_options if args.include?( :all ) include_paths = [] source_extras = [] includes = [] @parsing_parcels.code_lines( input ) do |line| if args.include?( :build_directive_include_paths ) # Scan for build directives: TEST_INCLUDE_PATH() include_paths += extract_build_directive_include_paths( line ) end if args.include?( :build_directive_source_files ) # Scan for build directives: TEST_SOURCE_FILE() source_extras += extract_build_directive_source_files( line ) end if args.include?( :includes ) # Scan for contents of #include directives includes += _extract_includes( line ) end end collect_build_directive_include_paths( filepath, include_paths ) if args.include?( :build_directive_include_paths ) collect_build_directive_source_files( filepath, source_extras ) if args.include?( :build_directive_source_files ) collect_includes( filepath, includes ) if args.include?( :includes ) # Different code processing pattern for test runner if args.include?( :test_runner_details ) # Go back to beginning of IO object for a full string extraction input.rewind() # Ultimately, we rely on Unity's runner generator that processes file contents as a single string _collect_test_runner_details( filepath, input.read() ) end end
`input` must have the interface of IO -- StringIO for testing or File in typical use
collect_simple_context
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_context_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_context_extractor.rb
MIT
def extract_includes(input) includes = [] @parsing_parcels.code_lines( input ) {|line| includes += _extract_includes( line ) } return includes.uniq end
Scan for all includes. Unlike other extract() calls, extract_includes() is public to be called externally. `input` must have the interface of IO -- StringIO for testing or File in typical use
extract_includes
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_context_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_context_extractor.rb
MIT
def lookup_full_header_includes_list(filepath) val = nil @lock.synchronize do val = @all_header_includes[form_file_key( filepath )] || [] end return val end
All header includes .h of test file
lookup_full_header_includes_list
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_context_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_context_extractor.rb
MIT
def lookup_header_includes_list(filepath) val = nil @lock.synchronize do val = @header_includes[form_file_key( filepath )] || [] end return val end
Header includes .h (minus mocks & framework headers) in test file
lookup_header_includes_list
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_context_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_context_extractor.rb
MIT
def lookup_include_paths_list(filepath) val = nil @lock.synchronize do val = @include_paths[form_file_key( filepath )] || [] end return val end
Include paths of test file specified with TEST_INCLUDE_PATH()
lookup_include_paths_list
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_context_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_context_extractor.rb
MIT
def lookup_build_directive_sources_list(filepath) val = nil @lock.synchronize do val = @source_extras[form_file_key( filepath )] || [] end return val end
Source extras via TEST_SOURCE_FILE() within test file
lookup_build_directive_sources_list
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_context_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_context_extractor.rb
MIT
def lookup_raw_mock_list(filepath) val = nil @lock.synchronize do val = @mocks[form_file_key( filepath )] || [] end return val end
Mocks within test file with no file extension
lookup_raw_mock_list
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_context_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_context_extractor.rb
MIT
def ingest_includes(filepath, includes) mock_prefix = @configurator.cmock_mock_prefix file_key = form_file_key( filepath ) mocks = [] all_headers = [] headers = [] sources = [] includes.each do |include| # <*.h> if include =~ /#{Regexp.escape(@configurator.extension_header)}$/ # Check if include is a mock with regex match that extracts only mock name (no .h) scan_results = include.scan(/([^\s]*\b#{mock_prefix}.+)#{Regexp.escape(@configurator.extension_header)}/) if (scan_results.size > 0) # Collect mock name mocks << scan_results[0][0] else # If not a mock or framework file, collect tailored header filename headers << include unless VENDORS_FILES.include?( include.ext('') ) end # Add to .h includes list all_headers << include # <*.c> elsif include =~ /#{Regexp.escape(@configurator.extension_source)}$/ # Add to .c includes list sources << include end end @lock.synchronize do @mocks[file_key] = mocks @all_header_includes[file_key] = all_headers @header_includes[file_key] = headers @source_includes[file_key] = sources end end
Unlike other ingest() calls, ingest_includes() can be called externally.
ingest_includes
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_context_extractor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_context_extractor.rb
MIT
def find_header_input_for_mock(mock, search_paths) return @file_finder.find_header_input_for_mock( mock ) end
TODO: Use search_paths to find/match header file from which to generate mock Today, this is just a pass-through wrapper
find_header_input_for_mock
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_invoker_helper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_invoker_helper.rb
MIT
def form_mock_filenames(mocklist) return mocklist.map {|mock| mock + @configurator.extension_source} end
Transform list of mock names into filenames with source extension
form_mock_filenames
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_invoker_helper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_invoker_helper.rb
MIT
def convert_libraries_to_arguments() args = ((@configurator.project_config_hash[:libraries_test] || []) + ((defined? LIBRARIES_SYSTEM) ? LIBRARIES_SYSTEM : [])).flatten if (defined? LIBRARIES_FLAG) args.map! {|v| LIBRARIES_FLAG.gsub(/\$\{1\}/, v) } end return args end
Convert libraries configuration form YAML configuration into a string that can be given to the compiler.
convert_libraries_to_arguments
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_invoker_helper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_invoker_helper.rb
MIT
def collect_cmdline_args() return [ @test_case_incl, @test_case_excl ].compact() end
Return test case arguments (empty if not set)
collect_cmdline_args
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_runner_manager.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_runner_manager.rb
MIT
def collect_defines() return @test_runner_defines end
Return ['UNITY_USE_COMMAND_LINE_ARGS'] #define required by Unity to enable cmd line arguments
collect_defines
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/test_runner_manager.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/test_runner_manager.rb
MIT
def build_command_line(tool_config, extra_params, *args) command = {} command[:name] = tool_config[:name] command[:executable] = tool_config[:executable] command[:options] = {} # Blank to hold options set before `exec()` processes # Basic premise is to iterate top to bottom through arguments using '$' as # a string replacement indicator to expand globals or inline yaml arrays # into command line arguments via substitution strings. executable = @tool_executor_helper.osify_path_separators( expandify_element(tool_config[:name], tool_config[:executable], *args) ) command[:line] = [ executable, extra_params.join(' ').strip, build_arguments(tool_config[:name], tool_config[:arguments], *args), ].reject{|s| s.nil? || s.empty?}.join(' ').strip # Log command as is @loginator.log( "Command: #{command}", Verbosity::DEBUG ) # Update executable after any expansion command[:executable] = executable return command end
build up a command line from yaml provided config @param extra_params is an array of parameters to append to executable (prepend to rest of command line)
build_command_line
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/tool_executor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/tool_executor.rb
MIT
def exec(command, args=[]) options = command[:options] options[:boom] = true if (options[:boom].nil?) options[:stderr_redirect] = StdErrRedirect::NONE if (options[:stderr_redirect].nil?) # Build command line command_line = [ command[:line].strip, args, @tool_executor_helper.stderr_redirect_cmdline_append( options ), ].flatten.compact.join(' ') shell_result = {} # Wrap system level tool execution in exception handling begin time = Benchmark.realtime do shell_result = @system_wrapper.shell_capture3( command:command_line, boom:options[:boom] ) end shell_result[:time] = time # Ultimately, re-raise the exception as ShellException populated with the exception message rescue => error raise ShellException.new( name:pretty_tool_name( command ), message: error.message ) # Be sure to log what we can ensure # Scrub the string for illegal output unless shell_result[:output].nil? shell_result[:output] = shell_result[:output].scrub if "".respond_to?(:scrub) shell_result[:output].gsub!(/\033\[\d\dm/,'') end @tool_executor_helper.log_results( command_line, shell_result ) end # Go boom if exit code is not 0 and that code means a fatal error # (Sometimes we don't want a non-0 exit code to cause an exception as the exit code may not mean a build-ending failure) if ((shell_result[:exit_code] != 0) and options[:boom]) raise ShellException.new( shell_result:shell_result, name:pretty_tool_name( command ) ) end return shell_result end
shell out, execute command, and return response
exec
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/tool_executor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/tool_executor.rb
MIT
def expandify_element(tool_name, element, *args) match = // to_process = nil args_index = 0 # handle ${#} input replacement if (element =~ PATTERNS::TOOL_EXECUTOR_ARGUMENT_REPLACEMENT) args_index = ($2.to_i - 1) if (args.nil? or args[args_index].nil?) error = "Tool '#{tool_name}' expected valid argument data to accompany replacement operator #{$1}." raise CeedlingException.new( error ) end match = /#{Regexp.escape($1)}/ to_process = args[args_index] end # simple string argument: replace escaped '\$' and strip element.sub!(/\\\$/, '$') element.strip! build_string = '' # handle array or anything else passed into method to be expanded in place of replacement operators case (to_process) when Array then to_process.each {|value| build_string.concat( "#{element.sub(match, value.to_s)} " ) } if (to_process.size > 0) else build_string.concat( element.sub(match, to_process.to_s) ) end # handle inline ruby string substitution if (build_string =~ PATTERNS::RUBY_STRING_REPLACEMENT) build_string.replace(@system_wrapper.module_eval(build_string)) end return build_string.strip end
handle simple text string argument & argument array string replacement operators
expandify_element
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/tool_executor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/tool_executor.rb
MIT
def dehashify_argument_elements(tool_name, hash) build_string = '' elements = [] # grab the substitution string (hash key) substitution = hash.keys[0].to_s # grab the string(s) to squirt into the substitution string (hash value) expand = hash[hash.keys[0]] if (expand.nil?) error = "Tool '#{tool_name}' could not expand nil elements for substitution string '#{substitution}'." raise CeedlingException.new( error ) end # array-ify expansion input if only a single string expansion = ((expand.class == String) ? [expand] : expand) expansion.each do |item| # String eval substitution if (item =~ PATTERNS::RUBY_STRING_REPLACEMENT) elements << @system_wrapper.module_eval(item) # Global constants elsif (@system_wrapper.constants_include?(item)) const = Object.const_get(item) if (const.nil?) error = "Tool '#{tool_name}' found constant '#{item}' to be nil." raise CeedlingException.new( error ) else elements << const end elsif (item.class == Array) elements << item elsif (item.class == String) error = "Tool '#{tool_name}' cannot expand nonexistent value '#{item}' for substitution string '#{substitution}'." raise CeedlingException.new( error ) else error = "Tool '#{tool_name}' cannot expand value having type '#{item.class}' for substitution string '#{substitution}'." raise CeedlingException.new( error ) end end # expand elements (whether string or array) into substitution string & replace escaped '\$' elements.flatten! elements.each do |element| build_string.concat( substitution.sub(/([^\\]*)\$/, "\\1#{element}") ) # don't replace escaped '\$' but allow us to replace just a lonesome '$' build_string.gsub!(/\\\$/, '$') build_string.concat(' ') end return build_string.strip end
handle argument hash: keys are substitution strings, values are data to be expanded within substitution strings
dehashify_argument_elements
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/tool_executor.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/tool_executor.rb
MIT
def osify_path_separators(executable) return executable.gsub(/\//, '\\') if (@system_wrapper.windows?) return executable end
# Modifies an executables path based on platform. ==== Attributes * _executable_: The executable's path.
osify_path_separators
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/tool_executor_helper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/tool_executor_helper.rb
MIT
def stderr_redirect_cmdline_append(tool_config) return nil if (tool_config.nil? || tool_config[:stderr_redirect].nil?) config_redirect = tool_config[:stderr_redirect] redirect = StdErrRedirect::NONE if (config_redirect == StdErrRedirect::AUTO) if (@system_wrapper.windows?) redirect = StdErrRedirect::WIN elsif (@system_utils.tcsh_shell?) redirect = StdErrRedirect::TCSH else redirect = StdErrRedirect::UNIX end end case redirect when StdErrRedirect::NONE then nil when StdErrRedirect::WIN then '2>&1' when StdErrRedirect::UNIX then '2>&1' when StdErrRedirect::TCSH then '|&' else redirect.to_s end end
# Returns the stderr redirect append based on the config. ==== Attributes * _tool_config_: A hash containing config information.
stderr_redirect_cmdline_append
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/tool_executor_helper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/tool_executor_helper.rb
MIT
def log_results(command_str, shell_result) # No logging unless we're at least at Obnoxious return if [email protected]_output?( Verbosity::OBNOXIOUS ) output = "> Shell executed command:\n" output += "`#{command_str}`\n" if !shell_result.empty? # Detailed debug logging if @verbosinator.should_output?( Verbosity::DEBUG ) output += "> With $stdout: " output += shell_result[:stdout].empty? ? "<empty>\n" : "\n#{shell_result[:stdout].strip()}\n" output += "> With $stderr: " output += shell_result[:stderr].empty? ? "<empty>\n" : "\n#{shell_result[:stderr].strip()}\n" output += "> And terminated with status: #{shell_result[:status]}\n" @loginator.log( '', Verbosity::DEBUG ) @loginator.log( output, Verbosity::DEBUG ) @loginator.log( '', Verbosity::DEBUG ) return # Bail out end # Slightly less verbose obnoxious logging if !shell_result[:output].empty? output += "> Produced output: " output += shell_result[:output].strip().empty? ? "<empty>\n" : "\n#{shell_result[:output].strip()}\n" end if !shell_result[:exit_code].nil? output += "> And terminated with exit code: [#{shell_result[:exit_code]}]\n" else output += "> And exited prematurely\n" end end @loginator.log( '', Verbosity::OBNOXIOUS ) @loginator.log( output, Verbosity::OBNOXIOUS ) @loginator.log( '', Verbosity::OBNOXIOUS ) end
# Logs tool execution results ==== Attributes * _command_str_: The command ran. * _shell_results_: The outputs of the command including exit code and output.
log_results
ruby
ThrowTheSwitch/Ceedling
lib/ceedling/tool_executor_helper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/lib/ceedling/tool_executor_helper.rb
MIT
def validate_config(config) unless config.is_a?(Hash) name = @reportinator.generate_config_walk([COMMAND_HOOKS_SYM]) error = "Expected configuration #{name} to be a Hash but found #{config.class}" raise CeedlingException.new(error) end unrecognized_hooks = config.keys - COMMAND_HOOKS_LIST unrecognized_hooks.each do |not_a_hook| name = @reportinator.generate_config_walk( [COMMAND_HOOKS_SYM, not_a_hook] ) error = "Unrecognized Command Hook: #{name}" @loginator.log( error, Verbosity::ERRORS ) end unless unrecognized_hooks.empty? error = "Unrecognized hooks found in Command Hooks plugin configuration" raise CeedlingException.new(error) end end
# Validate plugin configuration. :args: - config: :command_hooks section from project config hash
validate_config
ruby
ThrowTheSwitch/Ceedling
plugins/command_hooks/lib/command_hooks.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/command_hooks/lib/command_hooks.rb
MIT
def validate_hook(config, *keys) walk = [COMMAND_HOOKS_SYM, *keys] name = @reportinator.generate_config_walk( walk ) entry, _ = @walkinator.fetch_value( *walk, hash:config ) if entry.nil? raise CeedlingException.new( "Missing Command Hook plugin configuration for #{name}" ) end unless entry.is_a?(Hash) error = "Expected configuration #{name} for Command Hooks plugin to be a Hash but found #{entry.class}" raise CeedlingException.new( error ) end # Validate the Ceedling tool components of the hook entry config @tool_validator.validate( tool: entry, name: name, boom: true ) # Default logging configuration config[:logging] = false if config[:logging].nil? end
# Validate given hook :args: - config: Project configuration hash - keys: Key and index of hook inside :command_hooks configuration
validate_hook
ruby
ThrowTheSwitch/Ceedling
plugins/command_hooks/lib/command_hooks.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/command_hooks/lib/command_hooks.rb
MIT
def run_hook(which_hook, name="") if (@config[which_hook]) msg = "Running Command Hook :#{which_hook}" msg = @reportinator.generate_progress( msg ) @loginator.log( msg ) # Single tool config if (@config[which_hook].is_a? Hash) run_hook_step( which_hook, @config[which_hook], name ) # Multiple tool configs elsif (@config[which_hook].is_a? Array) @config[which_hook].each do |hook| run_hook_step( which_hook, hook, name ) end # Tool config is bad else msg = "The tool config for Command Hook #{which_hook} was poorly formed and not run" @loginator.log( msg, Verbosity::COMPLAIN ) end end end
# Run a hook if its available. If __which_hook__ is an array, run each of them sequentially. :args: - which_hook: Name of the hook to run - name: Name of file
run_hook
ruby
ThrowTheSwitch/Ceedling
plugins/command_hooks/lib/command_hooks.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/command_hooks/lib/command_hooks.rb
MIT
def run_hook_step(which_hook, hook, name="") if (hook[:executable]) # Handle argument replacemant ({$1}), and get commandline cmd = @ceedling[:tool_executor].build_command_line( hook, [], name ) shell_result = @ceedling[:tool_executor].exec( cmd ) # If hook logging is enabled if hook[:logging] # Skip debug logging -- allow normal tool debug logging to do its thing return if @verbosinator.should_output?( Verbosity::DEBUG ) output = shell_result[:output].strip # Set empty output to empty string if we're in OBNOXIOUS logging mode output = '<empty>' if output.empty? and @verbosinator.should_output?( Verbosity::OBNOXIOUS ) # Don't add to logging output if there's nothing to output return if output.empty? # NORMAL and OBNOXIOUS logging @loginator.log( "Command Hook :#{which_hook} output >> #{output}" ) end end end
# Run a hook if its available. :args: - hook: Name of the hook to run - name: Name of file (default: "") :return: shell_result.
run_hook_step
ruby
ThrowTheSwitch/Ceedling
plugins/command_hooks/lib/command_hooks.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/command_hooks/lib/command_hooks.rb
MIT
def setup @ceedling[:loginator].log( "Using Fake Function Framework (fff)...", Verbosity::OBNOXIOUS ) end
Set up Ceedling to use this plugin
setup
ruby
ThrowTheSwitch/Ceedling
plugins/fff/lib/fff.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/fff/lib/fff.rb
MIT
def automatic_reporting_enabled? return (@project_config[:gcov_report_task] == false) end
Called within class and also externally by plugin Rakefile No parameters enables the opportunity for latter mechanism
automatic_reporting_enabled?
ruby
ThrowTheSwitch/Ceedling
plugins/gcov/lib/gcov.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/gcov/lib/gcov.rb
MIT
def generate_coverage_reports() return if not @reports_enabled @reportinators.each do |reportinator| # Create the artifacts output directory. @file_wrapper.mkdir( reportinator.artifacts_path ) # Generate reports reportinator.generate_reports( @configurator.project_config_hash ) end end
Called within class and also externally by conditionally regnerated Rake task No parameters enables the opportunity for latter mechanism
generate_coverage_reports
ruby
ThrowTheSwitch/Ceedling
plugins/gcov/lib/gcov.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/gcov/lib/gcov.rb
MIT
def generate_reports(opts) # Get the gcovr version number. gcovr_version = get_gcovr_version() # Get gcovr options from project configuration options gcovr_opts = get_gcovr_opts(opts) # Extract exception_on_fail setting exception_on_fail = !!gcovr_opts[:exception_on_fail] # Build the common gcovr arguments. args_common = args_builder_common( gcovr_opts, gcovr_version ) msg = @reportinator.generate_heading( "Running Gcovr Coverage Reports" ) @loginator.log( msg ) # gcovr version 4.2 and later supports generating multiple reports with a single call. if min_version?( gcovr_version, 4, 2 ) reports = [] args = args_common args += (_args = args_builder_cobertura(opts, false)) reports << "Cobertura XML" if not _args.empty? args += (_args = args_builder_sonarqube(opts, false)) reports << "SonarQube" if not _args.empty? args += (_args = args_builder_json(opts, true)) reports << "JSON" if not _args.empty? # As of gcovr version 4.2, the --html argument must appear last. args += (_args = args_builder_html(opts, false)) reports << "HTML" if not _args.empty? reports.each do |report| msg = @reportinator.generate_progress("Generating #{report} coverage report in '#{GCOV_GCOVR_ARTIFACTS_PATH}'") @loginator.log( msg ) end # Generate the report(s). # only if one of the previous done checks for: # # - args_builder_cobertura # - args_builder_sonarqube # - args_builder_json # - args_builder_html # # updated the args variable. In other case, no need to run GCOVR for current setup. if !(args == args_common) run( gcovr_opts, args, exception_on_fail ) end # gcovr version 4.1 and earlier supports HTML and Cobertura XML reports. # It does not support SonarQube and JSON reports. # Reports must also be generated separately. else args_cobertura = args_builder_cobertura(opts, true) args_html = args_builder_html(opts, true) if args_html.length > 0 msg = @reportinator.generate_progress("Generating an HTML coverage report in '#{GCOV_GCOVR_ARTIFACTS_PATH}'") @loginator.log( msg ) # Generate the HTML report. run( gcovr_opts, (args_common + args_html), exception_on_fail ) end if args_cobertura.length > 0 msg = @reportinator.generate_progress("Generating an Cobertura XML coverage report in '#{GCOV_GCOVR_ARTIFACTS_PATH}'") @loginator.log( msg ) # Generate the Cobertura XML report. run( gcovr_opts, (args_common + args_cobertura), exception_on_fail ) end end # Determine if the gcovr text report is enabled. Defaults to disabled. if report_enabled?(opts, ReportTypes::TEXT) generate_text_report( opts, args_common, exception_on_fail ) end # White space log line @loginator.log( '' ) end
Generate the gcovr report(s) specified in the options.
generate_reports
ruby
ThrowTheSwitch/Ceedling
plugins/gcov/lib/gcovr_reportinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/gcov/lib/gcovr_reportinator.rb
MIT
def generate_reports(opts) shell_result = nil total_time = Benchmark.realtime do rg_opts = get_opts(opts) msg = @reportinator.generate_heading( "Running ReportGenerator Coverage Reports" ) @loginator.log( msg ) opts[:gcov_reports].each do |report| msg = @reportinator.generate_progress("Generating #{report} coverage report in '#{GCOV_REPORT_GENERATOR_ARTIFACTS_PATH}'") @loginator.log( msg ) end # Cleanup any existing .gcov files to avoid reporting old coverage results. for gcov_file in Dir.glob("*.gcov") File.delete(gcov_file) end gcno_exclude_str = "" # Avoid running gcov on custom specified .gcno files. for gcno_exclude_expression in rg_opts[:gcov_exclude] if !(gcno_exclude_expression.nil?) && !(gcno_exclude_expression.empty?) # We want to filter .gcno files, not .gcov files. # We will generate .gcov files from .gcno files. gcno_exclude_expression = gcno_exclude_expression.chomp("\\.gcov") gcno_exclude_expression = gcno_exclude_expression.chomp(".gcov") # The .gcno extension will be added later as we create the regex. gcno_exclude_expression = gcno_exclude_expression.chomp("\\.gcno") gcno_exclude_expression = gcno_exclude_expression.chomp(".gcno") # Append the custom expression. gcno_exclude_str += "|#{gcno_exclude_expression}" end end gcno_exclude_regex = /(\/|\\)(#{gcno_exclude_str})\.gcno/ # Generate .gcov files by running gcov on gcov notes files (*.gcno). for gcno_filepath in Dir.glob(File.join(GCOV_BUILD_PATH, "**", "*.gcno")) if not (gcno_filepath =~ gcno_exclude_regex) # Skip path that matches exclude pattern # Ensure there is a matching gcov data file. if File.file?(gcno_filepath.gsub(".gcno", ".gcda")) run_gcov("\"#{gcno_filepath}\"") end end end if Dir.glob("*.gcov").length > 0 # Build the command line arguments. args = args_builder(opts) # Generate the report(s). begin shell_result = run(args) rescue ShellException => ex shell_result = ex.shell_result # Re-raise raise ex ensure # Cleanup .gcov files. for gcov_file in Dir.glob("*.gcov") File.delete(gcov_file) end end else @loginator.log( "No matching .gcno coverage files found", Verbosity::COMPLAIN ) end end if shell_result shell_result[:time] = total_time @reportinator_helper.print_shell_result(shell_result) end # White space log line @loginator.log( '' ) end
Generate the ReportGenerator report(s) specified in the options.
generate_reports
ruby
ThrowTheSwitch/Ceedling
plugins/gcov/lib/reportgenerator_reportinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/gcov/lib/reportgenerator_reportinator.rb
MIT
def get_opts(opts) return opts[REPORT_GENERATOR_SETTING_PREFIX.to_sym] end
Get the ReportGenerator options from the project options.
get_opts
ruby
ThrowTheSwitch/Ceedling
plugins/gcov/lib/reportgenerator_reportinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/gcov/lib/reportgenerator_reportinator.rb
MIT
def run(args) command = @tool_executor.build_command_line(TOOLS_GCOV_REPORTGENERATOR_REPORT, [], args) return @tool_executor.exec( command ) end
Run ReportGenerator with the given arguments.
run
ruby
ThrowTheSwitch/Ceedling
plugins/gcov/lib/reportgenerator_reportinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/gcov/lib/reportgenerator_reportinator.rb
MIT
def run_gcov(args) command = @tool_executor.build_command_line(TOOLS_GCOV_REPORT, [], args) return @tool_executor.exec( command ) end
Run gcov with the given arguments.
run_gcov
ruby
ThrowTheSwitch/Ceedling
plugins/gcov/lib/reportgenerator_reportinator.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/gcov/lib/reportgenerator_reportinator.rb
MIT
def print_shell_result(shell_result) if !(shell_result.nil?) msg = "Done in %.3f seconds." % shell_result[:time] @loginator.log(msg, Verbosity::NORMAL) if !(shell_result[:output].nil?) && (shell_result[:output].length > 0) @loginator.log(shell_result[:output], Verbosity::OBNOXIOUS) end end end
Output the shell result to the console.
print_shell_result
ruby
ThrowTheSwitch/Ceedling
plugins/gcov/lib/reportinator_helper.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/gcov/lib/reportinator_helper.rb
MIT
def process_output(context, output, hash) # If $stderr/$stdout does not contain "warning", bail out return if !(output =~ /warning/i) # Store warning message @mutex.synchronize do hash[context][:collection] << output end end
Extract warning messages and store to hash in thread-safe manner
process_output
ruby
ThrowTheSwitch/Ceedling
plugins/report_build_warnings_log/lib/report_build_warnings_log.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_build_warnings_log/lib/report_build_warnings_log.rb
MIT
def write_logs( warnings, filename ) msg = @reportinator.generate_heading( "Running Warnings Report" ) @loginator.log( msg ) empty = false @mutex.synchronize { empty = warnings.empty? } if empty @loginator.log( "Build produced no warnings.\n" ) return end @mutex.synchronize do warnings.each do |context, hash| log_filepath = form_log_filepath( context, filename ) msg = @reportinator.generate_progress( "Generating artifact #{log_filepath}" ) @loginator.log( msg ) File.open( log_filepath, 'w' ) do |f| hash[:collection].each { |warning| f << warning } end end end # White space at command line after progress messages @loginator.log( '' ) end
Walk warnings hash and write contents to log file(s)
write_logs
ruby
ThrowTheSwitch/Ceedling
plugins/report_build_warnings_log/lib/report_build_warnings_log.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_build_warnings_log/lib/report_build_warnings_log.rb
MIT
def post_test_fixture_execute(arg_hash) # Thread-safe manipulation since test fixtures can be run in child processes # spawned within multiple test execution threads. @mutex.synchronize do @result_list << arg_hash[:result_file] end end
`Plugin` build step hook -- collect result file paths after each test fixture execution
post_test_fixture_execute
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_gtestlike_stdout/lib/report_tests_gtestlike_stdout.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_gtestlike_stdout/lib/report_tests_gtestlike_stdout.rb
MIT
def post_build() # Ensure a test task was invoked as part of the build return if not (@ceedling[:task_invoker].test_invoked?) results = @ceedling[:plugin_reportinator].assemble_test_results( @result_list ) hash = { :header => TEST_SYM.upcase(), :results => results } @ceedling[:plugin_reportinator].run_test_results_report(hash) end
`Plugin` build step hook -- render a report immediately upon build completion (that invoked tests)
post_build
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_gtestlike_stdout/lib/report_tests_gtestlike_stdout.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_gtestlike_stdout/lib/report_tests_gtestlike_stdout.rb
MIT
def summary() # Build up the list of passing results from all tests result_list = @ceedling[:file_path_utils].form_pass_results_filelist( PROJECT_TEST_RESULTS_PATH, COLLECTION_ALL_TESTS ) hash = { :header => TEST_SYM.upcase(), # Collect all existing test results (success or failing) in the filesystem, # limited to our test collection :results => @ceedling[:plugin_reportinator].assemble_test_results( result_list, {:boom => false} ) } @ceedling[:plugin_reportinator].run_test_results_report( hash ) end
`Plugin` build step hook -- render a test results report on demand using results from a previous build
summary
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_gtestlike_stdout/lib/report_tests_gtestlike_stdout.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_gtestlike_stdout/lib/report_tests_gtestlike_stdout.rb
MIT
def post_test_fixture_execute(arg_hash) # Thread-safe manipulation since test fixtures can be run in child processes # spawned within multiple test execution threads. @mutex.synchronize do @result_list << arg_hash[:result_file] end end
`Plugin` build step hook -- collect result file paths after each test fixture execution
post_test_fixture_execute
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_ide_stdout/lib/report_tests_ide_stdout.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_ide_stdout/lib/report_tests_ide_stdout.rb
MIT
def post_build() # Ensure a test task was invoked as part of the build return if (not @ceedling[:task_invoker].test_invoked?) results = @ceedling[:plugin_reportinator].assemble_test_results( @result_list ) hash = { :header => '', :results => results } @ceedling[:plugin_reportinator].run_test_results_report( hash ) do message = '' message = 'Unit test failures.' if (hash[:results][:counts][:failed] > 0) message end end
`Plugin` build step hook -- render a report immediately upon build completion (that invoked tests)
post_build
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_ide_stdout/lib/report_tests_ide_stdout.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_ide_stdout/lib/report_tests_ide_stdout.rb
MIT
def summary() # Build up the list of passing results from all tests result_list = @ceedling[:file_path_utils].form_pass_results_filelist( PROJECT_TEST_RESULTS_PATH, COLLECTION_ALL_TESTS ) hash = { :header => '', # Collect all existing test results (success or failing) in the filesystem, # limited to our test collection :results => @ceedling[:plugin_reportinator].assemble_test_results( result_list, {:boom => false} ) } @ceedling[:plugin_reportinator].run_test_results_report( hash ) end
`Plugin` build step hook -- render a test results report on demand using results from a previous build
summary
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_ide_stdout/lib/report_tests_ide_stdout.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_ide_stdout/lib/report_tests_ide_stdout.rb
MIT
def reorganize_results( results ) # Create structure of hash with default values suites = Hash.new() do |h,k| h[k] = { collection: [], total: 0, success: 0, failed: 0, ignored: 0, errors: 0, time: 0, stdout: [] } end results[:successes].each do |result| # Extract filepath source = result[:source][:file] # Filepath minus file extension name = source.sub( /#{File.extname(source)}$/, '' ) # Sanitize: Ensure no nil elements result[:collection].compact! # Sanitize: Ensure no empty test result hashes result[:collection].select! {|test| !test.empty?() } # Add success test cases to full test case collection and update statistics suites[name][:collection] += result[:collection].map{|test| test.merge(result: :success)} suites[name][:total] += result[:collection].length suites[name][:success] += result[:collection].length suites[name][:time] = results[:times][source] end results[:failures].each do |result| # Extract filepath source = result[:source][:file] # Filepath minus file extension name = source.sub( /#{File.extname(source)}$/, '' ) # Sanitize: Ensure no nil elements result[:collection].compact! # Sanitize: Ensure no empty test result hashes result[:collection].select! {|test| !test.empty?() } # Add failure test cases to full test case collection and update statistics suites[name][:collection] += result[:collection].map{|test| test.merge(result: :failed)} suites[name][:total] += result[:collection].length suites[name][:failed] += result[:collection].length suites[name][:time] = results[:times][source] end results[:ignores].each do |result| # Extract filepath source = result[:source][:file] # Filepath minus file extension name = source.sub( /#{File.extname(source)}$/, '' ) # Sanitize: Ensure no nil elements result[:collection].compact! # Sanitize: Ensure no empty test result hashes result[:collection].select! {|test| !test.empty?() } # Add ignored test cases to full test case collection and update statistics suites[name][:collection] += result[:collection].map{|test| test.merge(result: :ignored)} suites[name][:total] += result[:collection].length suites[name][:ignored] += result[:collection].length suites[name][:time] = results[:times][source] end results[:stdout].each do |result| # Extract filepath source = result[:source][:file] # Filepath minus file extension name = source.sub( /#{File.extname(source)}$/, '' ) # Add $stdout messages to collection suites[name][:stdout] += result[:collection] end # Add name to suite hashes (duplicating the key for suites) suites.map{|name, data| data.merge(name: name) } end
Reorganize test results by test executable instead of by result category Original success structure: successeses { file => test_cases[] } Reorganized test results: file => test_cases[{... result: :success}]
reorganize_results
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_log_factory/lib/junit_tests_reporter.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_log_factory/lib/junit_tests_reporter.rb
MIT
def post_test_fixture_execute(arg_hash) # Do nothing if no reports configured return if not @enabled # Get context from test run context = arg_hash[:context] @mutex.synchronize do # Create an empty array if context does not already exist as a key @results[context] = [] if @results[context].nil? # Add results filepath to array at context key @results[context] << arg_hash[:result_file] end end
`Plugin` build step hook -- collect context:results_filepath after test fixture runs
post_test_fixture_execute
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_log_factory/lib/report_tests_log_factory.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_log_factory/lib/report_tests_log_factory.rb
MIT
def post_build # Do nothing if no reports configured return if not @enabled empty = false @mutex.synchronize { empty = @results.empty? } # Do nothing if no results were generated (e.g. not a test build) return if empty msg = @reportinator.generate_heading( "Running Test Suite Reports" ) @loginator.log( msg ) @mutex.synchronize do # For each configured reporter, generate a test suite report per test context @results.each do |context, results_filepaths| # Assemble results from all results filepaths collected _results = @ceedling[:plugin_reportinator].assemble_test_results( results_filepaths ) # Provide results to each Reporter @reporters.each do |reporter| filepath = File.join( PROJECT_BUILD_ARTIFACTS_ROOT, context.to_s, reporter.filename ) msg = @reportinator.generate_progress( "Generating artifact #{filepath}" ) @loginator.log( msg ) reporter.write( filepath: filepath, results: _results ) end end end # White space at command line after progress messages @loginator.log( '' ) end
`Plugin` build step hook -- process results into log files after test build completes
post_build
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_log_factory/lib/report_tests_log_factory.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_log_factory/lib/report_tests_log_factory.rb
MIT
def post_test_fixture_execute(arg_hash) # Thread-safe manipulation since test fixtures can be run in child processes # spawned within multiple test execution threads. @mutex.synchronize do @result_list << arg_hash[:result_file] end end
`Plugin` build step hook -- collect result file paths after each test fixture execution
post_test_fixture_execute
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_pretty_stdout/lib/report_tests_pretty_stdout.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_pretty_stdout/lib/report_tests_pretty_stdout.rb
MIT
def post_build() # Ensure a test task was invoked as part of the build return if not (@ceedling[:task_invoker].test_invoked?) results = @ceedling[:plugin_reportinator].assemble_test_results( @result_list ) hash = { :header => '', :results => results } @ceedling[:plugin_reportinator].run_test_results_report(hash) do message = '' message = 'Unit test failures.' if (results[:counts][:failed] > 0) message end end
`Plugin` build step hook -- render a report immediately upon build completion (that invoked tests)
post_build
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_pretty_stdout/lib/report_tests_pretty_stdout.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_pretty_stdout/lib/report_tests_pretty_stdout.rb
MIT
def summary() # Build up the list of passing results from all tests result_list = @ceedling[:file_path_utils].form_pass_results_filelist( PROJECT_TEST_RESULTS_PATH, COLLECTION_ALL_TESTS ) hash = { :header => '', # Collect all existing test results (success or failing) in the filesystem, # limited to our test collection :results => @ceedling[:plugin_reportinator].assemble_test_results( result_list, {:boom => false} ) } @ceedling[:plugin_reportinator].run_test_results_report( hash ) end
`Plugin` build step hook -- render a test results report on demand using results from a previous build
summary
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_pretty_stdout/lib/report_tests_pretty_stdout.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_pretty_stdout/lib/report_tests_pretty_stdout.rb
MIT
def extract_output(raw_output) output = [] raw_output.each_line do |line| # Skip blank lines next if line =~ /^\s*\n$/ # Skip test case reporting lines next if line =~ /^.+:\d+:.+:(IGNORE|PASS|FAIL)/ # Return early if we get to test results summary footer return output if line =~/^-+\n$/ # Capture all other console output from the test runner, including `printf()`-style debugging statements output << line end return output end
Pick apart test executable console output to find any lines not specific to a test case
extract_output
ruby
ThrowTheSwitch/Ceedling
plugins/report_tests_raw_output_log/lib/report_tests_raw_output_log.rb
https://github.com/ThrowTheSwitch/Ceedling/blob/master/plugins/report_tests_raw_output_log/lib/report_tests_raw_output_log.rb
MIT