1# Copyright 2016 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4"""Framework for stripping whitespace and comments from resource files"""
5
6from __future__ import print_function
7
8from os import path
9import subprocess
10import sys
11
12import six
13
14__js_minifier = None
15__css_minifier = None
16
17def SetJsMinifier(minifier):
18  global __js_minifier
19  __js_minifier = minifier.split()
20
21def SetCssMinifier(minifier):
22  global __css_minifier
23  __css_minifier = minifier.split()
24
25def Minify(source, filename):
26  """Minify |source| (bytes) from |filename| and return bytes."""
27  file_type = path.splitext(filename)[1]
28  minifier = None
29  if file_type == '.js':
30    minifier = __js_minifier
31  elif file_type == '.css':
32    minifier = __css_minifier
33  if not minifier:
34    return source
35  p = subprocess.Popen(
36      minifier,
37      stdin=subprocess.PIPE,
38      stdout=subprocess.PIPE,
39      stderr=subprocess.PIPE)
40  (stdout, stderr) = p.communicate(source)
41  if p.returncode != 0:
42    print('Minification failed for %s' % filename)
43    print(stderr)
44    sys.exit(p.returncode)
45  return stdout
46