diff --git a/.rubocop.yml b/.rubocop.yml index e55c5d1..72f47ae 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -10,4 +10,4 @@ Metrics/MethodLength: Metrics/BlockLength: Exclude: - bin/git-format-staged # Long block for option parser is ok - \ No newline at end of file + - spec/**/*.rb diff --git a/spec/git.rb b/spec/git.rb index 6d5ec56..17cad1f 100644 --- a/spec/git.rb +++ b/spec/git.rb @@ -31,6 +31,14 @@ module Git File.write absolute, content.end_with?("\n") ? content : "#{content}\n" end + def get_content(name) + File.read(Pathname.new(path) + name).chomp + end + + def get_staged(name) + git 'show', ":#{name}" + end + def stage(file) git 'add', file end @@ -62,6 +70,12 @@ module Git def in_repo(&block) Dir.chdir path, &block end + + def run_formatter + in_repo do + FormatStaged.run formatter: "#{__dir__}/test_hook.rb {}", patterns: ['*.test'] + end + end end def self.new_repo diff --git a/spec/test_hook.rb b/spec/test_hook.rb new file mode 100755 index 0000000..0dd2109 --- /dev/null +++ b/spec/test_hook.rb @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +$stdin.readlines.each do |line| + puts line.gsub(/([^\s]*)\s*=\s*(.*)/, '\1 = \2') +end diff --git a/spec/test_spec.rb b/spec/test_spec.rb index 778f761..2b3ef4c 100644 --- a/spec/test_spec.rb +++ b/spec/test_spec.rb @@ -6,12 +6,8 @@ require 'format_staged' describe FormatStaged do def repo - @repo ||= Git.new_repo do |r| - r.file_in_tree 'index.js', <<~CONTENT - function foo () { - return 'foo' - } - CONTENT + @repo ||= Git.new_repo do |repo| + repo.file_in_tree 'origin.test', 'x = y' end end @@ -19,4 +15,41 @@ describe FormatStaged do @repo&.cleanup @repo = nil end + + it 'updates staged file and working copy' do + repo.set_content 'test.test', 'a=b' + repo.stage 'test.test' + repo.run_formatter + + expect(repo.get_staged('test.test')).to eq('a = b') + expect(repo.get_content('test.test')).to eq('a = b') + end + + it 'leaves other changes in working copy' do + repo.set_content 'test.test', "x=y\na=b\n" + repo.stage 'test.test' + repo.set_content 'test.test', 'abc' + repo.run_formatter + + expect(repo.get_content('test.test')).to eq('abc') + expect(repo.get_staged('test.test')).to eq("x = y\na = b") + end + + it 'merges update to working copy' do + repo.set_content 'test.test', "x=y\n#stuff\n" + repo.stage 'test.test' + repo.set_content 'test.test', "x=y\n#stuff\nmore stuff\n" + repo.run_formatter + + expect(repo.get_content('test.test')).to eq("x = y\n#stuff\nmore stuff") + expect(repo.get_staged('test.test')).to eq("x = y\n#stuff") + end + + it 'only touches files matching the given pattern' do + repo.set_content 'test.other', 'x=y' + repo.stage 'test.other' + repo.run_formatter + + expect(repo.get_content('test.other')).to eq('x=y') + end end