diff --git a/config/default.yml b/config/default.yml index b388f130..41a1d4b4 100644 --- a/config/default.yml +++ b/config/default.yml @@ -737,12 +737,19 @@ PreCommit: install_command: 'brew install swiftlint' include: '**/*.swift' + TerraformFormat: + enabled: false + description: 'Analyze with Terraform' + required_executable: 'terraform' + flags: ['fmt', '-check=true', '-diff=false'] + include: '**/*.tf' + TsLint: - enabled: false - description: 'Analyze with TSLint' - required_executable: 'tslint' - install_command: 'npm install -g tslint typescript' - include: '**/*.ts' + enabled: false + description: 'Analyze with TSLint' + required_executable: 'tslint' + install_command: 'npm install -g tslint typescript' + include: '**/*.ts' TrailingWhitespace: enabled: false diff --git a/lib/overcommit/hook/pre_commit/terraform_format.rb b/lib/overcommit/hook/pre_commit/terraform_format.rb new file mode 100644 index 00000000..905a55eb --- /dev/null +++ b/lib/overcommit/hook/pre_commit/terraform_format.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +module Overcommit::Hook::PreCommit + # Runs 'terraform fmt' against any modified *.tf files. + # + # @see https://www.terraform.io/docs/commands/fmt.html + class TerraformFormat < Base + def run + messages = [] + applicable_files.each do |f| + result = execute(command, args: [f]) + unless result.success? + messages << Overcommit::Hook::Message.new(:error, f, nil, "violation found in #{f}") + end + end + messages + end + end +end diff --git a/spec/overcommit/hook/pre_commit/terraform_format_spec.rb b/spec/overcommit/hook/pre_commit/terraform_format_spec.rb new file mode 100644 index 00000000..6897f8c3 --- /dev/null +++ b/spec/overcommit/hook/pre_commit/terraform_format_spec.rb @@ -0,0 +1,38 @@ +# frozen_string_literal: true + +require 'spec_helper' + +describe Overcommit::Hook::PreCommit::TerraformFormat do + let(:config) { Overcommit::ConfigurationLoader.default_configuration } + let(:context) { double('context') } + subject { described_class.new(config, context) } + + before do + subject.stub(:applicable_files).and_return(%w[file1.tf file2.tf]) + end + + context 'when Terraform exits successfully' do + before do + result = double('result') + result.stub(:success?).and_return(true) + subject.stub(:execute).and_return(result) + end + + it { should pass } + end + + context 'when Terraform exits unsucessfully' do + let(:result_ok) { double('result') } + let(:result_bad) { double('result') } + let(:cmdline) { %w[terraform fmt -check=true -diff=false] } + + before do + result_ok.stub(:success?).and_return(true) + result_bad.stub(:success?).and_return(false) + subject.stub(:execute).with(cmdline, args: ['file1.tf']).and_return(result_ok) + subject.stub(:execute).with(cmdline, args: ['file2.tf']).and_return(result_bad) + end + + it { should fail_hook } + end +end