Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge branch 'json'

  • Loading branch information...
commit 82f90eed858100185ba25f0b5b960239bbc0c658 2 parents 1812cb3 + 645d3ec
@xaviershay xaviershay authored
View
3  lib/cane/cli/parser.rb
@@ -106,6 +106,9 @@ def add_cane_options
add_option %w(--max-violations VALUE),
"Max allowed violations", default: 0, cast: :to_i
+ add_option %w(--json),
+ "Output as JSON", default: false
+
add_option %w(--parallel),
"Use all processors. Slower on small projects, faster on large.",
cast: ->(x) { x }
View
17 lib/cane/json_formatter.rb
@@ -0,0 +1,17 @@
+require 'json'
+
+module Cane
+
+ # Computes a machine-readable JSON representation from an array of violations
+ # computed by the checks.
+ class JsonFormatter
+ def initialize(violations)
+ @violations = violations
+ end
+
+ def to_s
+ @violations.to_json
+ end
+ end
+
+end
View
11 lib/cane/runner.rb
@@ -1,6 +1,7 @@
require 'parallel'
require 'cane/violation_formatter'
+require 'cane/json_formatter'
module Cane
def run(*args)
@@ -18,7 +19,7 @@ def initialize(spec)
end
def run
- outputter.print ViolationFormatter.new(violations)
+ outputter.print formatter.new(violations)
violations.length <= opts.fetch(:max_violations)
end
@@ -36,5 +37,13 @@ def violations
def outputter
opts.fetch(:out, $stdout)
end
+
+ def formatter
+ if opts[:json]
+ JsonFormatter
+ else
+ ViolationFormatter
+ end
+ end
end
end
View
11 spec/json_formatter_spec.rb
@@ -0,0 +1,11 @@
+require 'spec_helper'
+
+require 'cane/json_formatter'
+
+describe Cane::JsonFormatter do
+ it 'outputs violations as JSON' do
+ violations = [{description: 'Fail', line: 3}]
+ JSON.parse(described_class.new(violations).to_s).should ==
+ [{'description' => 'Fail', 'line' => 3}]
+ end
+end
View
5 spec/parser_spec.rb
@@ -102,4 +102,9 @@ def run(cli_args)
_, result = run("--no-readme")
result[:no_readme].should be
end
+
+ it 'handles json option' do
+ _, result = run("--json")
+ result[:json].should be
+ end
end
View
12 spec/runner_spec.rb
@@ -8,5 +8,17 @@
described_class.new(checks: [], max_violations: 0).run.should be
described_class.new(checks: [], max_violations: -1).run.should_not be
end
+
+ it 'returns JSON output' do
+ formatter = fire_replaced_class_double("Cane::JsonFormatter")
+ formatter.should_receive(:new).and_return("JSON")
+ buffer = StringIO.new("")
+
+ described_class.new(
+ out: buffer, checks: [], max_violations: 0, json: true
+ ).run
+
+ buffer.string.should == "JSON"
+ end
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.