cssmin (1660B)
1 #!/usr/bin/env lua 2 --- Removes line breaks, comments and spaces around symbols in a CSS file. 3 --- No dependency, you only need lua (>= 5.1). 4 --- With CSS file as argument or CSS block by stdin 5 -- @name cssmin 6 -- @param filepath the location of a CSS file 7 -- @return A 'text/css' block 8 -- Examples of uses 9 --[[ 10 $ ./cssmin styles.css > styles.min.css 11 $ ./cssmin < styles.css > styles.min.css 12 $ cat styles.css | ./cssmin 13 $ echo ".red { color: red; }" | ./cssmin 14 ]] 15 16 do 17 local function minify(css) 18 return css 19 :gsub('\n', '') -- removes line-breaks 20 :gsub('%s*([:;,*>{}~])%s+', '%1') -- removes spaces around :;,*>{}~ 21 :gsub('/%*.-%*/', '') -- removes comments 22 end 23 24 if arg[1] and io.open(arg[1], 'r') then 25 local file = arg[1] 26 local extension = file:match("^.+(%..+)$") 27 local function read(filepath) 28 if not filepath then 29 print "[Error!] A file is missing as argument." 30 end 31 32 local buffer = assert(io.open(filepath, 'r')) 33 local content = buffer:read '*a' 34 35 buffer:close() 36 37 return content 38 end 39 40 if extension == '.css' then 41 local minified, _ = minify(read(file)) 42 return print(minified) 43 else 44 print "[Error!] Wrong file type. It should be a 'text/css'." 45 end 46 elseif not arg[1] and io.input() ~= nil then 47 local css = {} 48 49 for line in (io.lines()) do 50 css[#css+1] = line 51 end 52 53 local minified, _ = minify(table.concat(css)) 54 55 return print(minified) 56 elseif not arg[1] then 57 print "An argument is missing. You sould add a CSS file as argument." 58 else 59 print("[Error!] The '" .. arg[1] .. "' file does not exist.") 60 end 61 end