Git Commit Automation With Neovim: Pull, Commit and Push


Hey 👋,

I think I have never mentioned it in here but I am a vimwiki user for a long time now.

Normally I use it from a single computer and I have had a cronjob that automatically does a commit and push every hour.

That was enough, but recently I am using a secondary computer and I have seen an hour was not frequent enough.

I changed it to run every minute, but I starting thinking if I could do anything better. And I did it with a simple script.

⚠️ The following script uses Neovim’s jobs to run commands in background. If you are using Vim you might want to consider changing to Neovim.

The following is a vimscript that I added to my .config/nvim/init.vim file:

" Autocommands to pull and push to git automatically.
" author: @aaron <https://aaron.com.es>

" This is better accompanied with a crontab similar to:
" # Disable emails
" MAILTO=""
" # Autocommit for vimwiki
" * * * * * (cd ~/vimwiki && git pull origin master; git add .; git commit -m "Autocommit (cron 1 min) @ $(hostname -s)"; git push origin master)


function! GitCommitAndPush()
    let l:cmd = 'git commit -am "Autocommit (on save) @ $(hostname -s)" && git push'
    call jobstart(l:cmd, {'on_exit': 'GitAsyncHandler'})
endfunction

function! GitAsyncHandler(job_id, data, event)
    if a:event == 'exit'
        if a:data[1] == 0
            echo "Git commit and push successful."
        else
            echoerr "Git commit and push failed."
        endif
    endif
endfunction

function! GitPull()
    let output = system('git pull origin master')
    if v:shell_error
        echoerr "Git pull failed"
        echoerr output
    else
        echom "Git pull successful"
    endif
endfunction

augroup vimwiki-autocommit
    au! BufReadPre ~/vimwiki/** call GitPull()
    au! BufWritePost ~/vimwiki/** call GitCommitAndPush()
augroup END

You might want to tweak the ~/vimwiki/** pattern to point to your vimwiki folder (or any folder of your choice that is under git control).

Also you can maybe want to tweak the commit messages or feedback messages to something more meaningful to you.

Let me know if that was of any help to you by clicking the 👍 button below or reaching out to me.

PS: I might at some point improve the above code or maybe even create a plugin for it. Not that it is really required, but I think I would have fun creating my first vim plugin 😄 🎉