UNPKG

grunt-htmltidy

Version:
77 lines (63 loc) 2.38 kB
/* * grunt-htmltidy * http://gruntjs.com/ * * Copyright (c) 2014 Gavin Ballard, contributors * Licensed under the MIT license. */ 'use strict'; var chalk = require('chalk'); var prettyBytes = require('pretty-bytes'); var tidy = require('htmltidy').tidy; var eachAsync = require('each-async'); module.exports = function (grunt) { grunt.registerMultiTask('htmltidy', 'Tidy HTML', function () { // Set up task options and configuration. var options = this.options(); var done = this.async(); /** * Iterator function to apply to each input file with eachAsync(). * * @param file The input file object provided by Grunt to be processed. * @param index The index of the input file. * @param callback The callback method supplied by sync.forEach() to be triggered on success or error. * @returns {*} */ var tidyFile = function(file, index, callback) { var untidied; var src = file.src[0]; // Check the file exists. if(!grunt.file.exists(src || ' ')) { grunt.log.writeln('Source file "' + chalk.cyan(src) + '" not found.'); return callback(false); } // Read the contents of the file and check there's something in them. untidied = grunt.file.read(src); if(untidied.length === 0) { grunt.log.writeln('Destination ' + chalk.cyan(file.dest) + ' not written because source file was empty.'); return callback(false); } // Make the call out to tidy(). tidy(untidied, options, function(error, tidied) { if(error) { grunt.log.writeln(error); return callback(false); } // Check something was generated by tidy(). if(tidied.length === 0) { grunt.log.writeln('Destination ' + chalk.cyan(file.dest) + ' not written because there was nothing to tidy.'); return callback(false); } // Write the tidied file and print a success message. grunt.file.write(file.dest, tidied); grunt.log.writeln('Tidied ' + chalk.cyan(file.dest) + ' ' + prettyBytes(untidied.length) + ' → ' + prettyBytes(tidied.length)); // Trigger the success callback. callback(); }); }; // Start the asynchronous iteration over files. eachAsync(this.files, tidyFile, function(error) { done(error); }); }); };