Add a lua script to clean the aliases file

Note that cmder doesn't ship with lua. Next step is converting this
script to perl, which ships with msysgit.
This commit is contained in:
melchior 2014-10-16 00:20:36 -04:00
parent dcc9f5e59a
commit 1e2f954724
2 changed files with 64 additions and 0 deletions

View File

@ -15,6 +15,7 @@ if not ["%_temp%"] == ["%_temp2%"] (
echo %* >> "%CMDER_ROOT%\config\aliases"
doskey /macrofile="%CMDER_ROOT%\config\aliases"
lua "%CMDER_ROOT%\scripts\clean_aliases.lua"
echo Alias created
endlocal
goto:eof

63
scripts/clean_aliases.lua Normal file
View File

@ -0,0 +1,63 @@
--[[
Cmder adds aliases to its aliases file without caring for duplicates.
This can result in the aliases file becoming bloated. This script cleans
the aliases file.
]]
local aliases = {}
local alias_file = os.getenv('CMDER_ROOT') .. "/config/aliases"
-- from http://www.lua.org/pil/19.3.html
-- function to create an iterator that returns the key-value pairs
-- sorted by keys
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do
table.insert(a, n)
end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then
return nil
else
return a[i], t[a[i]]
end
end
return iter
end
-- First step
-- Read the aliases file line by line, and put every entry in
-- a dictionary. The newer aliases being the last, the new will
-- always be kept over the old.
for line in io.lines(alias_file) do
-- Doskey actually accepts a lot of weird characters in macros
-- definitions.
local key, value = line:match('([^=%s<>]+)=(.*)')
if key then
aliases[key] = value
else
print('Invalid macro definition: '..line)
end
end
-- Second step
-- Write back the aliases. Sort them to make the file look nice.
local f = io.open(alias_file, 'w')
for key, value in pairsByKeys(aliases) do
-- write the pair only if the value is not empty
if value then
f:write(key .. '=' .. value .. '\n')
end
end
f:close()