Skip to content

Instantly share code, notes, and snippets.

@vamsiampolu
Created April 16, 2018 09:39
Show Gist options
  • Save vamsiampolu/0c039f59fdc952aeb905347d0a7620a3 to your computer and use it in GitHub Desktop.
Save vamsiampolu/0c039f59fdc952aeb905347d0a7620a3 to your computer and use it in GitHub Desktop.
" returns 1 if:
" eslintConfig exists in package.json and eslint is a devDependency
" .eslintrc exists and eslint is a devDependency in package.json
" returns 0 if
" eslint is a devDependency but no eslintConfig or .eslintrc is found,
" this is because eslint does not turn on any validation rules by default
" eslint is not a devDependency
function! HasEslint()
"a: indicates that the variable is argument scoped
"l: specifies that a variable is local to a function
" system executes a command in the shell and returns the result as a string
" has is a jq filter that returns true if an object has a key, if not it returns false
let l:pkgJsonConf = system("jq < package.json 'has(\"eslintConfig\")'") =~# 'true'
" ==# and !=# do a case sensitive string comparision
let l:fileConf = findfile('.eslintrc', escape(expand('<amatch>:h'),' ') . ';') !=# ''
let l:hasConfig = l:pkgJsonConf || l:fileConf
let l:hasDep = system("jq < package.json '.devDependencies | has(\"eslint\")'")
" double quote does not work in the if statement below
let l:res = l:hasConfig == 1 && l:hasDep =~# 'true'
" echom l:res
return l:res
endfunction
" neoformat should try formatprg where available
let g:neoformat_try_formatprg = 1
augroup vimrc
" if eslint is found
if HasEslint()
"get path of prettier-eslint
let g:prettier_eslint_path = system('PATH=$(npm bin):$PATH && which prettier-eslint')
let g:prettier_eslint_path2 = substitute(g:prettier_eslint_path,'[@\^\n\t\r]', '', 'g')
echom g:prettier_eslint_path
echom g:prettier_eslint_path2
if s:has_eslintrc_path
"get full path to eslintrc if eslintrc file exists
let g:eslintrc_full_path = getcwd() + s:eslintrc_path
echom g:eslintrc_full_path
autocmd FileType javascript execute "setlocal formatprg=".g:prettier_eslint_path2."\\ --filePath\\ ".g:eslintrc_full_path
elseif s:has_eslintConfig
let g:eslintConfig = system("jq -cr < package.json '.eslintConfig'")
let g:eslintEscapedConfig = substitute(g:eslintConfig, '[\n\t\r]\?', '', 'g')
echom g:eslintConfig
echom g:eslintEscapedConfig
autocmd FileType javascript execute "setlocal formatprg=".g:prettier_eslint_path2."\\ --eslintConfig\\ ".g:eslintEscapedConfig
endif
else
" just use prettier-standard
autocmd FileType javascript set formatprg=prettier-standard
endif
autocmd BufWritePre *.js Neoformat
" autocmd BufWritePre,TextChanged,InsertLeave *.js Neoformat
augroup end
" Merge commands into augroup vimrc
" augroup vimrc
"checks for .eslintrc and before falling back to standard
autocmd BufNewFile,BufReadPre *.js let b:syntastic_checkers = HasEslint() ? ['eslint'] : ['standard']
augroup end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment