Skip to content

Instantly share code, notes, and snippets.

@oblique63
Created November 5, 2010 12:42
Show Gist options
  • Save oblique63/664079 to your computer and use it in GitHub Desktop.
Save oblique63/664079 to your computer and use it in GitHub Desktop.
Expands minified CSS/Javascript files. No support for Strings or Regex syntax.
from os.path import abspath, isfile
import sys
def expand(filename):
"Expands minified Javascript/CSS files."
filename = abspath(filename)
is_js = filename.endswith(".js")
is_css = filename.endswith(".css")
assert isfile(filename) and (is_js or is_css), "Invalid File"
out_filename = filename.split(".",1)
out_filename = out_filename[0] + "_expanded"
if is_js:
out_filename += ".js"
elif is_css:
out_filename += ".css"
infile = open(filename, "r")
inscript = infile.read()
infile.close()
outscript = ""
indent_spaces = 2
indents = ""
ignore_semicolons = False
for index in xrange(len(inscript)):
char = inscript[index]
if char == ";" and not ignore_semicolons:
char += "\n" + indents
elif char == "{":
indents += " "*indent_spaces
char += "\n" + indents
if ignore_semicolons:
ignore_semicolons = False
elif char == "}":
if len(indents) > indent_spaces:
indents = indents[0:-indent_spaces]
else:
indents = ""
if inscript[index-1] != ";":
char = "\n" + indents + char
if not inscript[index+1] == ";":
char += "\n" + indents
# check if we're in a for-loop statement
elif is_js \
and (inscript[index-1 : index+4] == " for " \
or inscript[index-1 : index+4] == " for(") :
ignore_semicolons = True
outscript += char
outfile = open(out_filename,"w")
outfile.write(outscript)
outfile.close()
if __name__ == "__main__":
for filename in sys.argv[1:]:
expand(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment