Skip to content

Instantly share code, notes, and snippets.

@danielholmstrom
Created May 9, 2012 17:30
Show Gist options
  • Save danielholmstrom/2646981 to your computer and use it in GitHub Desktop.
Save danielholmstrom/2646981 to your computer and use it in GitHub Desktop.
Format and check css files
""" CSS-file formatter
Formats CSS-files without merging rules, preserves comments.
"""
import argparse
import cssutils
import os
import logging
SERIALIZER_PREFERENCES = {'indentClosingBrace': False,
'keepEmptyRules': True,
'keepAllProperties': True,
'listItemSpacer': '\n',
'omitLastSemicolon': False}
parser = argparse.ArgumentParser(description='Formats css files without '
'rewriting rules, May loose some comments.')
parser.add_argument('--check', default=False, action='store_true',
help='Check file for errors and warnings')
parser.add_argument('--replace', default=False, action='store_true',
help='Replace original file (and backups original)')
parser.add_argument('--force', default=False, action='store_true',
help='Force replace even if the file contains errors or warnings')
parser.add_argument('paths', metavar='FILES', type=str, nargs='+',
help='File(s) that should be formatted.')
logging.basicConfig()
l = logging.getLogger()
l.setLevel(logging.DEBUG)
args = parser.parse_args()
def check_file(path, **kwargs):
""" Check file for errors and warnings and prints them
"""
return cssutils.parseFile(path, **kwargs)
def replace_file(path, **kwargs):
""" Format a single css file and overwrite the original """
try:
parser = cssutils.CSSParser(**kwargs)
sheet = parser.parseFile(path)
except IOError, e:
print 'Failed to parse file "%s": %s' % (path, e)
return
except Exception, e:
print 'Failed to parse file "%s": %s' % (path, e)
return
try:
counter = 0
while os.path.isfile('%s.bak%d' % (path, counter)):
counter = counter + 1
dest = '%s.bak%d' % (path, counter)
os.rename(path, dest)
except Exception, e:
print "Failed to backup file '%s' to '%s': %s" % (path, dest, e)
return
for k in SERIALIZER_PREFERENCES:
sheet.setSerializerPref(k, SERIALIZER_PREFERENCES[k])
with open(path, 'w') as f:
f.write(sheet.cssText)
for path in args.paths:
path = os.path.abspath(path)
if args.check:
check_file(path)
if args.replace:
replace_file(path, raiseExceptions=not args.force)
else:
parser = cssutils.CSSParser()
sheet = parser.parseFile(path)
for k in SERIALIZER_PREFERENCES:
sheet.setSerializerPref(k, SERIALIZER_PREFERENCES[k])
print sheet.cssText
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment