How to add a custom prompt to windows console
Julian Oct 24
Cmder is an awsome package of software which replaces the default console
powershell on windows.
If you are in a git repo, you see the current branch in the prompt, colored in white if its clean or red if dirty. There are similar features for yarn, npm, ...
Sometimes you want to add the output of to the prompt too. This can be done like this:
In my case i wanted to see on which terraform workspace i am. with terraform you can do this by running
terraform workspace show in your terraform directory. this would output something like
λ terraform workspace show default
To do this you have to create a clink extension. Assuming that you installed cmder in
C:\Program Files\Cmder you create a file called
local color = require("color") local function is_terraform() for dir in io.popen([[dir ".\" /b /ad]]):lines() do if dir == ".terraform" then return true end end return false end local function terraform_prompt_filter() if is_terraform() then f = assert (io.popen ("terraform workspace show")) for line in f:lines() do terraform_context = '(workspace: ' .. line .. ')' if line == "production" then prompt_color = color.RED elseif line == "development" then prompt_color = color.GREEN else prompt_color = color.YELLOW end break end -- for loop f:close() terraform_context = color.color_text(terraform_context, prompt_color) clink.prompt.value = clink.prompt.value:gsub("\n", terraform_context .. "\n") return false end end clink.prompt.register_filter(terraform_prompt_filter, 1)
this code checks if it is currently in a terraform directory by looking if the directory
.terraform exists. it colors the workspace output in green if you are on
development workspace, red if you are on
production and yellow on all others. adapt the code for your needs.
i am sure that the lua code can be optimized, i am open for comments and enhancements.
- cover image by Willi Heidelbach https://pixabay.com/en/puzzle-match-missing-hole-blank-693870/