if-statementvimconditional-statementsstatusline

How can i make this conditional return a value IF the output is a number?


i am making this function for my vim-statusline:

function! GitCommitSymbol(timer_id)
  let l:uncommited = system('echo -n $(git checkout | grep -oP "(\M+)" -c)')
  if (uncommited == number)
    let g:uncommited = ''
    hi MyGitSymbol ctermfg=11
  else
    let g:uncommited = ''
    hi MyGitSymbol ctermfg=7
  endif
  call timer_start(30000, 'GitCommitSymbol')
endfunction

And i made this command git checkout | grep -oP "(\M+)" -c specifically to return only a number of uncommited changes (that's why i use grep).

So basically, if im on a location that is a git repository and i type the command on the shell, it returns me "0", "1" and so on, depending on how much uncommited changes i have.

However, if i type it on a location that is not a git repository, it returns me something like:

fatal: not a git repository (or any parent up to mount point /) Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set). 0

So, on this line of the function: if (uncommited == number), i need a conditional, to show something IF the output of the command is numeric, and the "else" is for when it is not numeric (like the "fatal" output i put above). But i don't know how to make this conditional.


Solution

  • You don't need the extra echo, just call the command directly, then use Vimscript's trim() to remove whitespace around the output.

    let uncommitted = trim(system('git checkout | grep -oP "(\M+)" -c'))
    

    Then you can check if it's a number by using the =~ operator, together with a regex such as '^\d\+$' to match numeric output:

    if uncommitted =~ '^\d\+$'
    

    If later on you would like to access the count as a number, you can use str2nr(uncommitted).