|
| 1 | +module Overcommit::Hook::PreCommit |
| 2 | + # Runs `w3c_validators` against any modified HTML files. |
| 3 | + class W3cHtmlValidator < Base |
| 4 | + def run |
| 5 | + begin |
| 6 | + require 'w3c_validators' |
| 7 | + rescue LoadError |
| 8 | + return :fail, 'w3c_validators not installed -- run `gem install w3c_validators`' |
| 9 | + end |
| 10 | + |
| 11 | + result_messages = |
| 12 | + begin |
| 13 | + applicable_files.collect do |path| |
| 14 | + results = validator.validate_file(path) |
| 15 | + messages = results.errors + results.warnings |
| 16 | + messages.collect do |msg| |
| 17 | + # Some warnings are not per-line, so use 0 as a default |
| 18 | + line = Integer(msg.line || 0) |
| 19 | + |
| 20 | + # Build message by hand to reduce noise from the validator response |
| 21 | + text = "#{msg.type.to_s.upcase}; URI: #{path}; line #{line}: #{msg.message.strip}" |
| 22 | + Overcommit::Hook::Message.new(msg.type, path, line, text) |
| 23 | + end |
| 24 | + end |
| 25 | + rescue W3CValidators::ValidatorUnavailable => e |
| 26 | + return :fail, e.message |
| 27 | + rescue W3CValidators::ParsingError => e |
| 28 | + return :fail, e.message |
| 29 | + end |
| 30 | + |
| 31 | + result_messages.flatten! |
| 32 | + return :pass if result_messages.empty? |
| 33 | + |
| 34 | + result_messages |
| 35 | + end |
| 36 | + |
| 37 | + private |
| 38 | + |
| 39 | + def validator |
| 40 | + unless @validator |
| 41 | + @validator = W3CValidators::MarkupValidator.new(opts) |
| 42 | + @validator.set_charset!(charset, only_as_fallback = true) unless charset.nil? |
| 43 | + @validator.set_doctype!(doctype, only_as_fallback = true) unless doctype.nil? |
| 44 | + @validator.set_debug! |
| 45 | + end |
| 46 | + @validator |
| 47 | + end |
| 48 | + |
| 49 | + def opts |
| 50 | + @opts ||= { |
| 51 | + validator_uri: config['validator_uri'], |
| 52 | + proxy_server: config['proxy_server'], |
| 53 | + proxy_port: config['proxy_port'], |
| 54 | + proxy_user: config['proxy_user'], |
| 55 | + proxy_pass: config['proxy_pass'] |
| 56 | + } |
| 57 | + end |
| 58 | + |
| 59 | + # Values specified at |
| 60 | + # http://www.rubydoc.info/gems/w3c_validators/1.2/W3CValidators#CHARSETS |
| 61 | + def charset |
| 62 | + @charset ||= config['charset'] |
| 63 | + end |
| 64 | + |
| 65 | + # Values specified at |
| 66 | + # http://www.rubydoc.info/gems/w3c_validators/1.2/W3CValidators#DOCTYPES |
| 67 | + def doctype |
| 68 | + @doctype ||= config['doctype'] |
| 69 | + end |
| 70 | + end |
| 71 | +end |
0 commit comments