File tree 4 files changed +65
-0
lines changed
lib/overcommit/hook/pre_commit
spec/overcommit/hook/pre_commit
4 files changed +65
-0
lines changed Original file line number Diff line number Diff line change @@ -91,6 +91,10 @@ PreCommit:
91
91
description : ' Analyzing with JSHint'
92
92
include : ' **/*.js'
93
93
94
+ JsonSyntax :
95
+ description : ' Validating JSON syntax'
96
+ include : ' **/*.json'
97
+
94
98
JsxHint :
95
99
description : ' Analyzing with JSXHint'
96
100
include : ' **/*.jsx'
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change @@ -27,6 +27,7 @@ Gem::Specification.new do |s|
27
27
s . required_ruby_version = '>= 1.8.7'
28
28
29
29
s . add_dependency 'childprocess' , '>= 0.5.1'
30
+ s . add_dependency 'json' , '>= 1.8' # For 1.8.7. support only
30
31
31
32
s . add_development_dependency 'rspec' , '2.14.1'
32
33
s . add_development_dependency 'image_optim' , '~> 0.13.0'
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments