Sha256: eed74c4dd3d63ec71cef46eb32b6969cb70b2a0e7dc90156ee14fc138eafcc93

Contents?: true

Size: 1.35 KB

Versions: 56

Compression:

Stored size: 1.35 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)
      Dir.chdir(@dir) do
        skip_rename
        begin
          terraform_fmt
        ensure
          restore_rename
        end
      end
    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)
      return if 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

    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

56 entries across 56 versions & 1 rubygems

Version Path
terraspace-2.2.6 lib/terraspace/cli/fmt/runner.rb
terraspace-2.2.5 lib/terraspace/cli/fmt/runner.rb
terraspace-2.2.4 lib/terraspace/cli/fmt/runner.rb
terraspace-2.2.3 lib/terraspace/cli/fmt/runner.rb
terraspace-2.2.2 lib/terraspace/cli/fmt/runner.rb
terraspace-2.2.1 lib/terraspace/cli/fmt/runner.rb
terraspace-2.2.0 lib/terraspace/cli/fmt/runner.rb
terraspace-2.1.7 lib/terraspace/cli/fmt/runner.rb
terraspace-2.1.6 lib/terraspace/cli/fmt/runner.rb
terraspace-2.1.5 lib/terraspace/cli/fmt/runner.rb
terraspace-2.1.4 lib/terraspace/cli/fmt/runner.rb
terraspace-2.1.3 lib/terraspace/cli/fmt/runner.rb
terraspace-2.1.2 lib/terraspace/cli/fmt/runner.rb
terraspace-2.1.1 lib/terraspace/cli/fmt/runner.rb
terraspace-2.1.0 lib/terraspace/cli/fmt/runner.rb
terraspace-2.0.3 lib/terraspace/cli/fmt/runner.rb
terraspace-2.0.2 lib/terraspace/cli/fmt/runner.rb
terraspace-2.0.1 lib/terraspace/cli/fmt/runner.rb
terraspace-2.0.0 lib/terraspace/cli/fmt/runner.rb
terraspace-1.1.7 lib/terraspace/cli/fmt/runner.rb