Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
parser.error("You must provide a css file ")
elif len(args) == 1:
parser.error(("You must provide the relative path between "
"the css and the images."))
css_path = os.path.basename(args[0])
img_rel_path = args[1]
# Configure the logger
log = logging.getLogger('csscache')
handler = logging.StreamHandler(sys.stderr)
handler.setLevel(logging.ERROR)
log.addHandler(handler)
if options.minified:
cssutils.ser.prefs.useMinified()
# Create the parser
parser = cssutils.CSSParser(log=log,
raiseExceptions=True,
parseComments=not options.minified,
validate=False)
try:
# Parse the original file
sheet = parser.parseFile(args[0])
except Exception, e:
sys.stderr.write('Error: %s %s\n' % (css_path, e.args[0]))
sys.exit(1)
# Replace all the urls
replacer = partial(cache_bust_replacer, options, css_path, img_rel_path)
cssutils.replaceUrls(sheet, replacer, ignoreImportRules=True)
directory to save files to
saveparsed
save literal CSS from server or save the parsed CSS
minified
save minified CSS
Both parsed and minified (which is also parsed of course) will
loose information which cssutils is unable to understand or where
it is simple buggy. You might to first save the raw version before
parsing of even minifying it.
"""
msg = 'parsed'
if saveraw:
msg = 'raw'
if minified:
cssutils.ser.prefs.useMinified()
msg = 'minified'
inlines = 0
for i, sheet in enumerate(self.stylesheetlist):
url = sheet.href
if not url:
inlines += 1
url = u'%s_INLINE_%s.css' % (self._filename, inlines)
# build savepath
scheme, loc, path, query, fragment = urlparse.urlsplit(url)
# no absolute path
if path and path.startswith('/'):
path = path[1:]
path = os.path.normpath(path)
path, fn = os.path.split(path)
if path:
src = cssutils.parseFile(path, encoding=sourceencoding)
elif url:
src = cssutils.parseUrl(url, encoding=sourceencoding)
else:
sys.exit('Path or URL must be given')
result = cssutils.resolveImports(src)
result.encoding = targetencoding
cssutils.log.info(u'Using target encoding: %r' % targetencoding, neverraise=True)
if minify:
# save old setting and use own serializer
oldser = cssutils.ser
cssutils.setSerializer(cssutils.serialize.CSSSerializer())
cssutils.ser.prefs.useMinified()
cssText = result.cssText
cssutils.setSerializer(oldser)
else:
cssText = result.cssText
return cssText
'source and target file "%s".' % fname)
sys.exit(2)
elif options.no_overwrite and os.path.exists(target):
sys.stderr.write('File exists (and --no-overwrite was used) "%s".' % target)
sys.exit(3)
src = open(fname)
try:
try:
converted = clevercss.convert(src.read(), fname=fname)
except (ParserError, EvalException) as e:
sys.stderr.write('Error in file %s: %s\n' % (fname, e))
sys.exit(1)
if options.minified:
css = cssutils.CSSParser().parseString(converted)
cssutils.ser.prefs.useMinified()
converted = css.cssText
dst = open(target, 'w')
try:
print('Writing output to %s...' % target)
dst.write(converted)
finally:
dst.close()
finally:
src.close()
help='minify parsed CSS', default=False)
p.add_option('-d', '--debug', action='store_true', dest='debug',
help='activate debugging output')
(options, params) = p.parse_args(args)
if not params and not options.url:
p.error("no filename given")
if options.debug:
p = cssutils.CSSParser(loglevel=logging.DEBUG)
else:
p = cssutils.CSSParser()
if options.minify:
cssutils.ser.prefs.useMinified()
if options.string:
sheet = p.parseString(u''.join(params), encoding=options.encoding)
print sheet.cssText
elif options.url:
sheet = p.parseUrl(options.url, encoding=options.encoding)
print sheet.cssText
else:
for filename in params:
sys.stderr.write('=== CSS FILE: "%s" ===\n' % filename)
sheet = p.parseFile(filename, encoding=options.encoding)
print sheet.cssText
print
sys.stderr.write('\n')
def _minified():
href = self.base_url if self.base_url != '' else None
sheet = cssutils.parseString(css, href=href)
sheet = cssutils.resolveImports(sheet)
cssutils.ser.prefs.useMinified()
return sheet.cssText
return self.cached(css.encode('utf-8'), _minified)
in code called after this method is called.
:type css_text: str
:param css_text: Text containing the CSS to be written to the file.
:return: None
**Example:**
>>> css_text = '.margin-top-50px { margin-top: 3.125em }'
>>> css_file = CSSFile()
>>> css_file.minify(css_text=css_text)
"""
parse_string = parseString(css_text)
ser.prefs.useMinified() # Enable minification.
file_path = get_file_path(
file_directory=self.file_directory,
file_name=self.file_name,
extension=str('.min' + self.extension) # prepend '.min'
)
with open(file_path, 'w') as css_file:
css_file.write(parse_string.cssText.decode('utf-8'))
ser.prefs.useDefaults() # Disable minification.