Skip to content

Instantly share code, notes, and snippets.

@reinhrst
Created November 7, 2022 10:49
Show Gist options
  • Save reinhrst/4eefe0b11b8ed10f4f3af68f2de82a6f to your computer and use it in GitHub Desktop.
Save reinhrst/4eefe0b11b8ed10f4f3af68f2de82a6f to your computer and use it in GitHub Desktop.
" This function will first check if no changes are staged in git.
" If so, it will save the current file, and then commit and push it.
" The whole function is mapped to <leader>sacp
" the function (when called manually) allows an argument that is the commit
" message
" Only use this for things where it makes sense to commit one file at a time
" (like a dev log). Else make proper commits.
function SaveAddCommitPushInfo(msg) abort
for line in a:msg->split('\n')
echom line
endfor
endfunction
function SaveAddCommitPushError(msg) abort
echohl Error
for line in a:msg->split('\n')
echom line
endfor
echohl None
endfunction
function SaveAddCommitPush(msg = "")
let commitmessage = "SaveAddCommitPush " . trim(system("hostname")) . " " . trim(system("date -u +%Y-%m-%dT%H:%M:%SZ"))
if a:msg != ""
let commitmessage = a:msg . "\n\n" . commitmessage
endif
let filename = expand("%:p")
let pathname = trim(system("dirname " . shellescape(filename)))
let changedir = "cd " . shellescape(pathname)
let check_nothing_staged =
\ "(OUTPUT=$(git diff --cached --name-only --exit-code) || " .
\ "(echo \"Staged changes found, please commit or reset\\n${OUTPUT}\"; false))"
let add_file_and_commit = "(git add " . shellescape(filename) .
\ " && git commit -m " . shellescape(commitmessage) . ")"
let check_nothing_staged = system(changedir . " && " .
\ check_nothing_staged)
if v:shell_error != 0
call SaveAddCommitPushError(check_nothing_staged)
return 1
endif
write
let output = system(changedir . " && " .
\ add_file_and_commit . " && git push && echo done")
if v:shell_error != 0
call SaveAddCommitPushError(output)
else
call SaveAddCommitPushInfo(output)
endif
endfunction
nmap <leader>sacp :call SaveAddCommitPush()<CR>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment