---
##
# Figure out what's going on with helpers, which are files like
# 
#     <gem_root>/spec/*_helper.rb
# 
# They may be auto-required in `<gem_root>/.rspec` with lines like
# 
#     --require spec_helper.rb
# 
# These tasks determine what helpers a generated spec file should require.
# 
# Expects:
# 
# @var [str] spec_abs_dir
#   Absolute path to the target gem's spec directory.
# 
# @var [list<str>?] require
#   Optional list of string names to require in spec files. If not defined,
#   it will be set - see details below.
#   
# 
# Provides:
# 
# @var [list<str>] available_helpers
#   List of "requirable" strings pulled from any `<spec_dir>/*_helper.rb` files
#   found.
# 
# @var [list<str>] auto_require_helpers
#   List of "auto-required" helpers parsed from `--require *_helper` lines in
#   `<gem_root>/.rspec` (if it exists). Will be `[]` if `.rspec` doesn't exist
#   or has not `--require *_helper` lines.
# 
# @var [list<str>] require
#   List of string names to require in spec files. If this variables is *not*
#   defined it will be set to all available helpers that are *not* 
#   auto-required in `.rspec`.
# 
##

- name: >-
    Get a list of available `*_helper.rb` files in 
    `spec_abs_dir={{ spec_abs_dir }}`
  find:
    paths: >-
      {{ spec_abs_dir }}
    patterns: '*_helper.rb'
  register: found_helpers


- name: >-
    Set `available_helpers` to the extension-less basenames of each file in
    `found_helpers.files`
  set_fact:
    available_helpers: >-
      {{
        found_helpers.files
        | map( attribute='path' )
        | map( 'basename' )
        | map( 'splitext' )
        | map( 'first' )
        | list
      }}


- name: >-
    Set `auto_require_helpers` to the list of spec helpers files that are 
    auto-required via `--require <name>_helper` lines in `<gem_root>/.rspec`
  set_fact_with_ruby:
    var_name: auto_require_helpers
    bind:
      gem_root: >-
        {{ gem_root }}
    src: |
      require 'pathname'
      
      path = Pathname.new( gem_root ) / '.rspec'
      
      if path.file?
        path.read.scan( /^\-\-require(?:\ |\=)(.*_helper)$/ ).map &:first
      else
        []
      end


- when: require is not defined
  name: >-
    Set `require` to all the `available_helpers` that are not 
    `auto_require_helpers={{ auto_require_helpers }}`
  set_fact:
    require: >-
      {{ available_helpers | difference( auto_require_helpers ) }}


# - debug: var=require