summaryrefslogtreecommitdiff
path: root/ale_linters/ruby/brakeman.vim
blob: fa5617df23fed1ef2942e5138eb43403cb2a2227 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
" Author: Eddie Lebow https://github.com/elebow
" Description: Brakeman, a static analyzer for Rails security

let g:ale_ruby_brakeman_options =
\   get(g:, 'ale_ruby_brakeman_options', '')

function! ale_linters#ruby#brakeman#Handle(buffer, lines) abort
    let l:result = json_decode(join(a:lines, ''))

    let l:output = []

    for l:warning in l:result.warnings
        " Brakeman always outputs paths relative to the Rails app root
        let l:rails_root = s:FindRailsRoot(a:buffer)
        let l:warning_file = l:rails_root . '/' . l:warning.file

        if !ale#path#IsBufferPath(a:buffer, l:warning_file)
          continue
        endif

        let l:text = l:warning.warning_type . ' ' . l:warning.message . ' (' . l:warning.confidence . ')'
        let l:line = l:warning.line != v:null ? l:warning.line : 1

        call add(l:output, {
        \    'lnum': l:line,
        \    'type': 'W',
        \    'text': l:text,
        \})
    endfor

    return l:output
endfunction

function! ale_linters#ruby#brakeman#GetCommand(buffer) abort
    let l:rails_root = s:FindRailsRoot(a:buffer)

    if l:rails_root ==? ''
        return ''
    endif

    return 'brakeman -f json -q '
    \    . ale#Var(a:buffer, 'ruby_brakeman_options')
    \    . ' -p ' . ale#Escape(l:rails_root)
endfunction

function! s:FindRailsRoot(buffer) abort
    " Find the nearest dir contining "app", "db", and "config", and assume it is
    " the root of a Rails app.
    for l:name in ['app', 'config', 'db']
        let l:dir = fnamemodify(
        \   ale#path#FindNearestDirectory(a:buffer, l:name),
        \   ':h:h'
        \)

        if l:dir !=# '.'
        \&& isdirectory(l:dir . '/app')
        \&& isdirectory(l:dir . '/config')
        \&& isdirectory(l:dir . '/db')
            return l:dir
        endif
    endfor

    return ''
endfunction

call ale#linter#Define('ruby', {
\    'name': 'brakeman',
\    'executable': 'brakeman',
\    'command_callback': 'ale_linters#ruby#brakeman#GetCommand',
\    'callback': 'ale_linters#ruby#brakeman#Handle',
\    'lint_file': 1,
\})