class Danger::DangerEslint

Lint javascript files using [eslint](eslint.org/). Results are send as inline commen.

@example Run eslint with changed files only

eslint.filtering = true
eslint.lint

@see leonhartX/danger-eslint @tags lint, javaxctipt

Constants

DEFAULT_BIN_PATH

Attributes

bin_path[W]

A path of eslint's bin

config_file[RW]

An path to eslint's config file @return [String]

filtering[RW]

Enable filtering Only show messages within changed files. @return [Boolean]

ignore_file[RW]

An path to eslint's ignore file @return [String]

target_extensions[W]

Specified extentions of target file Default is [“.js”] @return [Array]

Public Instance Methods

bin_path() click to toggle source
# File lib/eslint/plugin.rb, line 33
def bin_path
  @bin_path ||= DEFAULT_BIN_PATH
end
lint() click to toggle source

Lints javascript files. Generates `errors` and `warnings` due to eslint's config. Will try to send inline comment if supported(Github)

@return [void]

# File lib/eslint/plugin.rb, line 51
def lint
  lint_results
    .reject { |r| r.nil? || r['messages'].length.zero? }
    .reject { |r| r['messages'].first['message'].include? 'matching ignore pattern' }
    .map { |r| send_comment r }
end
target_extensions() click to toggle source
# File lib/eslint/plugin.rb, line 41
def target_extensions
  @target_extensions ||= %W(.js)
end

Private Instance Methods

eslint_path() click to toggle source

Get eslint' bin path

return [String]

# File lib/eslint/plugin.rb, line 63
def eslint_path
  File.exist?(bin_path) ? bin_path : find_executable('eslint')
end
lint_results() click to toggle source

Get lint result regards the filtering option

return [Hash]

# File lib/eslint/plugin.rb, line 70
def lint_results
  bin = eslint_path
  raise 'eslint is not installed' unless bin
  return run_lint(bin, '.') unless filtering
  ((git.modified_files - git.deleted_files - git.renamed_files.map { |r| r[:before] }) + git.added_files + git.renamed_files.map { |r| r[:after] })
    .select { |f| target_extensions.include?(File.extname(f)) }
    .map { |f| f.gsub("#{Dir.pwd}/", '') }
    .map { |f| run_lint(bin, f).first }
end
run_lint(bin, file) click to toggle source

Run eslint aginst a single file.

@param [String] bin

The binary path of eslint

@param [String] file

File to be linted

return [Hash]

# File lib/eslint/plugin.rb, line 89
def run_lint(bin, file)
  command = "#{bin} -f json"
  command << " -c #{config_file}" if config_file
  command << " --ignore-path #{ignore_file}" if ignore_file
  result = `#{command} #{file}`
  JSON.parse(result)
end
send_comment(results) click to toggle source

Send comment with danger's warn or fail method.

@return [void]

# File lib/eslint/plugin.rb, line 100
def send_comment(results)
  dir = "#{Dir.pwd}/"
  results['messages'].each do |r|
    filename = results['filePath'].gsub(dir, '')
    method = r['severity'] > 1 ? 'fail' : 'warn'
    send(method, r['message'], file: filename, line: r['line'])
  end
end