Skip to content

Instantly share code, notes, and snippets.

@notlmn
Last active January 20, 2019 13:09
Show Gist options
  • Select an option

  • Save notlmn/84e28bc6db15d0b5549b702b91da15b6 to your computer and use it in GitHub Desktop.

Select an option

Save notlmn/84e28bc6db15d0b5549b702b91da15b6 to your computer and use it in GitHub Desktop.
Git prompt for Clink
function trim(str)
return (str:gsub("^%s*(.-)%s*$", "%1"))
end
function exec(command)
local file = io.popen(command .. ' 2>nul', 'r')
local output = trim(file:read('*all'))
local rc = {file:close()}
local exit_code = rc[3]
return output, exit_code
end
function isEmpty(str)
return (trim(str) == "")
end
function getGitBranch()
local branchName = ""
-- Check if the current directory is in a Git repository
local output, exit_code = exec("git rev-parse")
if (not (exit_code == 0)) or (not isEmpty(output)) then
return ""
end
-- Is a Git repository, but has no HEAD pointer or tags
-- Either it is an empty Git repo or something went wrong
local headInfo, exit_code = exec("git show-ref --head --tags")
if (not (exit_code == 0)) or isEmpty(headInfo) then
return ""
end
-- Get the short symbolic ref for HEAD
branchName, exit_code = exec("git rev-parse --abbrev-ref HEAD")
-- Early exit
if not (exit_code == 0) then
return ""
end
-- If HEAD isn't a symbolic ref, get the short SHA for the latest commit
if isEmpty(branchName) or branchName == "HEAD" then
branchName, exit_code = exec("git rev-parse --short HEAD")
if exit_code == 0 then
return branchName
else
return ""
end
end
-- Otherwise, just give up.
return branchName
end
function promptGit()
local branchName = getGitBranch()
if not isEmpty(branchName) then
clink.prompt.value = clink.prompt.value .. " (" .. branchName .. ") "
end
return false
end
clink.prompt.register_filter(promptGit, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment