Permalink
Browse files

new check: ensure all ruby source files have an encoding marker

  • Loading branch information...
1 parent 0cfb1d6 commit cf7e549db15931e4b8bb2d7e57a7c81f108d9938 @yob yob committed Jun 17, 2012
Showing with 92 additions and 0 deletions.
  1. +2 −0 lib/cane.rb
  2. +39 −0 lib/cane/encoding_check.rb
  3. +51 −0 spec/encoding_check_spec.rb
View
@@ -1,4 +1,5 @@
require 'cane/abc_check'
+require 'cane/encoding_check'
require 'cane/style_check'
require 'cane/doc_check'
require 'cane/threshold_check'
@@ -16,6 +17,7 @@ def run(opts)
class Runner
CHECKERS = {
abc: AbcCheck,
+ encoding: EncodingCheck,
style: StyleCheck,
doc: DocCheck,
threshold: ThresholdCheck
View
@@ -0,0 +1,39 @@
+module Cane
+
+ # Creates violations for ruby files that have no encoding marker in the
+ # first two lines
+ class EncodingCheck < Struct.new(:opts)
+ def violations
+ file_names.map { |file_name|
+ find_violations(file_name)
+ }.flatten.compact
+ end
+
+ def find_violations(file_name)
+ data = File.open(file_name, 'r:utf-8')
+ line_one, line_two = *data.lines
+
+ if !line_one.to_s.match(/coding:/) && !line_two.to_s.match(/coding:/)
+ NoEncodingViolation.new(file_name)
+ end
+ end
+
+ def file_names
+ Dir[opts.fetch(:files)]
+ end
+
+ end
+
+ # Value object used by EncodingCheck
+ class NoEncodingViolation < Struct.new(:file_name)
+ def description
+ "Source file missing an encoding marker"
+ end
+
+ def columns
+ [file_name]
+ end
+
+ end
+
+end
@@ -0,0 +1,51 @@
+require 'spec_helper'
+
+require 'cane/encoding_check'
+
+describe Cane::EncodingCheck do
+ context "with a source file that has no encoding marker" do
+ let!(:file_name) {
+ make_file <<-RUBY
+puts "chunky bacon"
@xaviershay

xaviershay Jun 17, 2012

Contributor

sorry I try to keep my code bases vegan :P

+ RUBY
+ }
+
+ it 'creates an EncodingViolation' do
+ violations = described_class.new(files: file_name).violations
+ violations.length.should == 1
+
+ violations[0].should be_instance_of(Cane::NoEncodingViolation)
+ violations[0].file_name.should == file_name
+ end
+ end
+
+ context "with a source file that has an encoding marker on line 1" do
+ let!(:file_name) {
+ make_file <<-RUBY
+# coding: utf-8
+puts "chunky bacon"
+ RUBY
+ }
+
+ it 'creates no violationsn' do
+ violations = described_class.new(files: file_name).violations
+ violations.length.should == 0
+ end
+ end
+
+ context "with a source file that has an encoding marker on line 2" do
+ let!(:file_name) {
+ make_file <<-RUBY
+#!/bin/env ruby
+# coding: utf-8
+puts "chunky bacon"
+ RUBY
+ }
+
+ it 'creates no violationsn' do
+ violations = described_class.new(files: file_name).violations
+ violations.length.should == 0
+ end
+ end
+
+end

0 comments on commit cf7e549

Please sign in to comment.