Sha256: f2d0a46c5ec8c941752d1bdba415fea7ff098d4aa73e3dd0f196e41a3296c54b

Contents?: true

Size: 1.44 KB

Versions: 2

Compression:

Stored size: 1.44 KB

Contents

class Terraspace::CLI::Fmt
  class Runner
    include Terraspace::CLI::Concerns::SourceDirs
    include Terraspace::Util::Logging
    SKIP_PATTERN = /\.skip$/

    def initialize(dir)
      @dir = dir
    end

    def format!
      logger.info @dir.color(:green)

      exit_status = nil
      Dir.chdir(@dir) do
        skip_rename
        begin
          exit_status = terraform_fmt
        ensure
          restore_rename
        end
      end
      exit_status
    end

    def skip_rename
      tf_files.each do |path|
        if !skip?(path) && erb?(path)
          FileUtils.mv(path, "#{path}.skip")
        end
      end
    end

    def terraform_fmt
      sh "terraform fmt"
    end

    def sh(command)
      logger.debug("=> #{command}")
      success = system(command)
      unless success
        logger.info "WARN: There were some errors running terraform fmt for files in #{@dir}:".color(:yellow)
        logger.info "The errors are shown above"
      end
      $?.exitstatus
    end

    def restore_rename
      tf_files.each do |path|
        if skip?(path) && erb?(path)
          FileUtils.mv(path, path.sub(SKIP_PATTERN, '')) # original name
        end
      end
    end

  private
    def skip?(path)
      !!(path =~ SKIP_PATTERN)
    end

    def erb?(path)
      IO.readlines(path).detect { |l| l.include?('<%') }
    end

    def tf_files
      Dir.glob("#{Terraspace.root}/#{@dir}/**/*.{tf,skip}").select { |p| File.file?(p) }
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
terraspace-2.2.8 lib/terraspace/cli/fmt/runner.rb
terraspace-2.2.7 lib/terraspace/cli/fmt/runner.rb