aboutsummaryrefslogtreecommitdiffstats
path: root/pelican-htmlmin/minify.py
diff options
context:
space:
mode:
authorBryan Brattlof <bryanbrattlof@gmail.com>2019-09-08 12:35:38 -0500
committerBryan Brattlof <bryanbrattlof@gmail.com>2019-09-08 15:13:53 -0500
commit86f97bc655c2a5dc6b249986c4fe9d60cecb257d (patch)
treeaf2615d35da36051ff297566d60b8f54a11b4a82 /pelican-htmlmin/minify.py
parentb141915cb947d93003cbf32071938c556ff20781 (diff)
downloadpelican-htmlmin-86f97bc655c2a5dc6b249986c4fe9d60cecb257d.tar.gz
pelican-htmlmin-86f97bc655c2a5dc6b249986c4fe9d60cecb257d.tar.bz2
move minify scripts into package folder
Diffstat (limited to 'pelican-htmlmin/minify.py')
-rw-r--r--pelican-htmlmin/minify.py53
1 files changed, 53 insertions, 0 deletions
diff --git a/pelican-htmlmin/minify.py b/pelican-htmlmin/minify.py
new file mode 100644
index 0000000..d403574
--- /dev/null
+++ b/pelican-htmlmin/minify.py
@@ -0,0 +1,53 @@
+
+from pelican import signals
+
+import multiprocessing
+import htmlmin
+import os
+import re
+
+import logging
+logger = logging.getLogger(__name__)
+
+
+def run(pelican):
+
+ if pelican.setings.get('MINIFY_DEBUG', False):
+ return # specifically told to minify content or not
+ if logging.getLevelName(logger.getEffectiveLevel()) == 'DEBUG':
+ return # pelican is in debug mode, skip minification
+
+ options = pelican.settings.get('MINIFY_OPTIONS', {})
+ htmlfile = re.compile(
+ pelican.settings.get('MINIFY_MATCH', r'.html?$')
+ )
+ pool = multiprocessing.Pool()
+
+ # find all matching files and give to workers to minify
+ for base, dirs, files in os.walk(pelican.settings['OUTPUT_PATH']):
+ for f in filter(htmlfile.search, files):
+ filepath = os.path.join(base, f)
+ pool.apply_async(worker, (filepath, options))
+
+ # wait for the workers to finish
+ pool.close()
+ pool.join()
+
+
+def worker(filepath, options):
+ """use htmlmin to minify the given file"""
+ rawhtml = open(filepath, encoding='utf-8').read()
+ with open(filepath, 'w', encoding='utf-8') as f:
+ logger.debug('Minifying: %s' % filepath)
+ try:
+ compressed = htmlmin.minify(rawhtml, **options)
+ f.write(compressed)
+ except Exception as e:
+ logger.critical('Minification failed: {}'.format(e))
+
+
+def register():
+ """
+ Minify HTML at the end of the processing loop
+ """
+ signals.finalized.connect(run)