Skip to content

Commit db49148

Browse files
jfelchnerShane da Silva
authored and
Shane da Silva
committed
Add JsonSyntax pre-commit
Change-Id: I071ccc85f3968f38e2ce8797551c47aaff048d31 Reviewed-on: http://gerrit.causes.com/37957 Tested-by: jenkins <jenkins@causes.com> Reviewed-by: Shane da Silva <shane@causes.com>
1 parent fc81d6d commit db49148

File tree

4 files changed

+65
-0
lines changed

4 files changed

+65
-0
lines changed

config/default.yml

+4
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,10 @@ PreCommit:
9191
description: 'Analyzing with JSHint'
9292
include: '**/*.js'
9393

94+
JsonSyntax:
95+
description: 'Validating JSON syntax'
96+
include: '**/*.json'
97+
9498
JsxHint:
9599
description: 'Analyzing with JSXHint'
96100
include: '**/*.jsx'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
require 'json'
2+
3+
module Overcommit::Hook::PreCommit
4+
# Checks the syntax of any modified JSON files.
5+
class JsonSyntax < Base
6+
def run
7+
output = []
8+
9+
applicable_files.each do |file|
10+
begin
11+
File.open(file) { |io| JSON.load(io) }
12+
rescue JSON::ParserError => e
13+
output << "#{e.message} parsing #{file}"
14+
end
15+
end
16+
17+
return :good if output.empty?
18+
19+
[:bad, output]
20+
end
21+
end
22+
end

overcommit.gemspec

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ Gem::Specification.new do |s|
2727
s.required_ruby_version = '>= 1.8.7'
2828

2929
s.add_dependency 'childprocess', '>= 0.5.1'
30+
s.add_dependency 'json', '>= 1.8' # For 1.8.7. support only
3031

3132
s.add_development_dependency 'rspec', '2.14.1'
3233
s.add_development_dependency 'image_optim', '~> 0.13.0'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
require 'spec_helper'
2+
3+
describe Overcommit::Hook::PreCommit::JsonSyntax do
4+
let(:config) { Overcommit::ConfigurationLoader.default_configuration }
5+
let(:context) { double('context') }
6+
let(:staged_file) { 'my_file.json' }
7+
8+
subject { described_class.new(config, context) }
9+
10+
before do
11+
subject.stub(:applicable_files).and_return([staged_file])
12+
end
13+
14+
around do |example|
15+
repo do
16+
File.open(staged_file, 'w') { |f| f.write('foo') }
17+
`git add #{staged_file}`
18+
19+
example.run
20+
end
21+
end
22+
23+
context 'when JSON files have no errors' do
24+
before do
25+
JSON.stub(:load)
26+
end
27+
28+
it { should pass }
29+
end
30+
31+
context 'when JSON file has errors' do
32+
before do
33+
JSON.stub(:load).and_raise(JSON::ParserError)
34+
end
35+
36+
it { should fail_hook }
37+
end
38+
end

0 commit comments

Comments
 (0)