Skip to content

Commit

Permalink
Add verbose option
Browse files Browse the repository at this point in the history
Closes #65
  • Loading branch information
vvasilev- committed Feb 7, 2017
1 parent 2142930 commit 2bc5d7a
Show file tree
Hide file tree
Showing 12 changed files with 61 additions and 19 deletions.
7 changes: 7 additions & 0 deletions README.md
Expand Up @@ -181,6 +181,13 @@ Built-in filters:

> A [svg-sprite](https://github.com/jkphl/svg-sprite#configuration-basics) configuration.
###### verbose

> Prints the plugin output to the console.
- Default: `false`
- Required: `false`

----

### The Image
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -33,6 +33,7 @@
},
"dependencies": {
"bluebird": "^3.1.1",
"debug": "^2.6.0",
"fs-extra": "^0.26.4",
"lodash": "^4.0.0",
"postcss": "^5.0.14",
Expand Down
46 changes: 38 additions & 8 deletions src/core.js
Expand Up @@ -3,6 +3,7 @@ import fs from 'fs-extra';
import postcss from 'postcss';
import Promise from 'bluebird';
import _ from 'lodash';
import debug from 'debug';
import RasterFactory from './factories/raster';
import VectorFactory from './factories/vector';

Expand Down Expand Up @@ -69,7 +70,8 @@ export const defaults = {
svg: {
precision: 5
}
}
},
verbose: false
};

/**
Expand All @@ -87,8 +89,11 @@ export function prepareFilterBy(opts, result) {
opts.filterBy.unshift(image => {
return fs.statAsync(image.path)
.catch(() => {
result.warn(`skip ${image.url} because doesn't exist.`);
throw new Error(`Skip ${image.url} because doesn't exist.`);
const message = `Skip ${image.url} because doesn't exist.`;

opts.logger(message);

throw new Error(message);
});
});
}
Expand Down Expand Up @@ -135,6 +140,8 @@ export function prepareGroupBy(opts) {
export function extractImages(root, opts, result) {
let images = [];

opts.logger('Extracting the images...');

// Search for background & background image declartions
root.walkRules((rule) => {
const styleFilePath = opts.relativeTo === RELATIVE_TO_RULE ? rule.source.input.file : root.source.input.file;
Expand Down Expand Up @@ -175,7 +182,7 @@ export function extractImages(root, opts, result) {

images.push(image);
} else {
result.warn(`skip ${image.url} because isn't supported.`);
opts.logger(`Skip ${image.url} because isn't supported.`)
}
}
});
Expand All @@ -193,6 +200,8 @@ export function extractImages(root, opts, result) {
* @return {Promise}
*/
export function applyFilterBy(opts, images) {
opts.logger('Applying the filters...');

return Promise.reduce(opts.filterBy, (images, filterFn) => {
return Promise.filter(images, (image) => {
return filterFn(image)
Expand All @@ -209,6 +218,8 @@ export function applyFilterBy(opts, images) {
* @return {Promise}
*/
export function applyGroupBy(opts, images) {
opts.logger('Applying the groups...');

return Promise.reduce(opts.groupBy, (images, groupFn) => {
return Promise.map(images, (image) => {
return groupFn(image)
Expand Down Expand Up @@ -286,6 +297,8 @@ export function setTokens(root, opts, images) {
* @return {Promise}
*/
export function runSpritesmith(opts, images) {
opts.logger('Generating the spritesheets...');

return new Promise((resolve, reject) => {
const promises = _.chain(images)
.groupBy((image) => {
Expand Down Expand Up @@ -327,24 +340,25 @@ export function runSpritesmith(opts, images) {
* @return {Promise}
*/
export function saveSpritesheets(opts, images, spritesheets) {
opts.logger('Saving the spritesheets...');

return Promise.each(spritesheets, (spritesheet) => {
return (
_.isFunction(opts.hooks.onSaveSpritesheet) ?
Promise.resolve(opts.hooks.onSaveSpritesheet(opts, spritesheet)) :
Promise.resolve(makeSpritesheetPath(opts, spritesheet))
)
.then(( res ) => {
if (!res) {
throw new Error('postcss-sprites: Spritesheet requires a relative path.');
}

if ( _.isString(res) ) {
spritesheet.path = res;
} else {
_.assign(spritesheet, res);
}

if (!spritesheet.path) {
throw new Error('postcss-sprites: Spritesheet requires a relative path.');
}

spritesheet.path = spritesheet.path.replace(/\\/g, '/');

return fs.outputFileAsync(spritesheet.path, spritesheet.image);
Expand Down Expand Up @@ -392,6 +406,8 @@ export function mapSpritesheetProps(opts, images, spritesheets) {
* @return {Promise}
*/
export function updateReferences(root, opts, images, spritesheets) {
opts.logger('Replacing the references...');

root.walkComments((comment) => {
let rule, image;

Expand Down Expand Up @@ -577,3 +593,17 @@ export function makeSpritesheetPath(opts, { groups, extension }) {
export function isToken(commentValue) {
return commentValue.indexOf(COMMENT_TOKEN_PREFIX) > -1;
}

/**
* Create a logger that can be disabled in runtime.
*
* @param {Boolean} enabled
* @return {Function}
*/
export function createLogger(enabled) {
if (enabled) {
debug.enable('postcss-sprites');
}

return debug('postcss-sprites');
}
8 changes: 6 additions & 2 deletions src/index.js
Expand Up @@ -11,7 +11,8 @@ import {
runSpritesmith,
saveSpritesheets,
mapSpritesheetProps,
updateReferences
updateReferences,
createLogger
} from './core';

/**
Expand All @@ -22,6 +23,9 @@ export default postcss.plugin('postcss-sprites', (options = {}) => {
// Extend defaults
const opts = _.merge({}, defaults, options);

// Setup the logger
opts.logger = createLogger(opts.verbose);

// Prepare filter & group functions
prepareFilterBy(opts, result);
prepareGroupBy(opts);
Expand All @@ -36,7 +40,7 @@ export default postcss.plugin('postcss-sprites', (options = {}) => {
.spread((opts, images, spritesheets) => mapSpritesheetProps(opts, images, spritesheets))
.spread((opts, images, spritesheets) => updateReferences(css, opts, images, spritesheets))
.spread((root, opts, images, spritesheets) => {
result.warn(`${spritesheets.length} ${spritesheets.length > 1 ? 'spritesheets' : 'spritesheet'} generated.`);
opts.logger(`${spritesheets.length} ${spritesheets.length > 1 ? 'spritesheets' : 'spritesheet'} generated.`);
})
.catch((err) => {
console.error(`postcss-sprites: An error occurred while processing files - ${err.message}`);
Expand Down
2 changes: 1 addition & 1 deletion test/03-extract-images.js
Expand Up @@ -11,7 +11,7 @@ test.beforeEach((t) => {
`;

t.context.ast = postcss.parse(input, { from: '/tmp/test.css' });
t.context.opts = Object.assign({}, defaults);
t.context.opts = Object.assign({ logger() {} }, defaults);
});

test('should convert rules to image objects', async (t) => {
Expand Down
2 changes: 1 addition & 1 deletion test/04-apply-filter-by.js
Expand Up @@ -5,7 +5,7 @@ import _ from 'lodash';
import { defaults, prepareFilterBy, extractImages, applyFilterBy } from '../lib/core';

test.beforeEach(async (t) => {
t.context.opts = _.merge({}, defaults);
t.context.opts = _.merge({ logger() {} }, defaults);

const input = `
.selector-a { background-image: url(circle.png); }
Expand Down
2 changes: 1 addition & 1 deletion test/05-apply-group-by.js
Expand Up @@ -10,7 +10,7 @@ test.beforeEach((t) => {
.selector-b { background: url(square@2x.png) no-repeat 0 0; }
`;

t.context.opts = _.merge({}, defaults);
t.context.opts = _.merge({ logger() {} }, defaults);
t.context.ast = postcss.parse(input, { from: '/tmp/test.css' });
});

Expand Down
2 changes: 1 addition & 1 deletion test/06-set-tokens.js
Expand Up @@ -5,7 +5,7 @@ import { defaults, extractImages, setTokens } from '../lib/core';

async function run(input) {
let root = postcss.parse(input, { from: '/tmp/test.css' });
let opts = _.merge({}, defaults);
let opts = _.merge({ logger() {} }, defaults);
let images;

[ opts, images ] = await extractImages(root, opts);
Expand Down
2 changes: 1 addition & 1 deletion test/07-run-spritesmith.js
Expand Up @@ -8,7 +8,7 @@ import { defaults, extractImages, prepareGroupBy, applyGroupBy, runSpritesmith }
const readFileAsync = Promise.promisify(fs.readFile);

test.beforeEach((t) => {
t.context.opts = _.merge({}, defaults);
t.context.opts = _.merge({ logger() {} }, defaults);
});

test('should generate spritesheets', async (t) => {
Expand Down
4 changes: 2 additions & 2 deletions test/08-save-spritesheets.js
Expand Up @@ -16,7 +16,7 @@ import {
const readFileAsync = Promise.promisify(fs.readFile);

test.beforeEach((t) => {
t.context.opts = _.merge({}, defaults);
t.context.opts = _.merge({ logger() {} }, defaults);
});

test('should save spritesheets', async (t) => {
Expand Down Expand Up @@ -103,7 +103,7 @@ test('should throw error if path is empty', async (t) => {
[ opts, images ] = await extractImages(ast, t.context.opts);
[ opts, images, spritesheets ] = await runSpritesmith(t.context.opts, images);

t.throws(saveSpritesheets(images, t.context.opts, spritesheets));
t.throws(saveSpritesheets(t.context.opts, images, spritesheets));
});

test('should use Promise result provided by book', async (t) => {
Expand Down
2 changes: 1 addition & 1 deletion test/09-map-spritesheet-props.js
Expand Up @@ -16,7 +16,7 @@ import {
const readFileAsync = Promise.promisify(fs.readFile);

test.beforeEach((t) => {
t.context.opts = _.merge({}, defaults);
t.context.opts = _.merge({ logger() {} }, defaults);
});

test('should add coords & spritePath to every image', async (t) => {
Expand Down
2 changes: 1 addition & 1 deletion test/10-update-references.js
Expand Up @@ -17,7 +17,7 @@ import {
const readFileAsync = Promise.promisify(fs.readFile);

test.beforeEach((t) => {
t.context.opts = _.merge({}, defaults);
t.context.opts = _.merge({ logger() {} }, defaults);
});

test('should update CSS declarations', async (t) => {
Expand Down

0 comments on commit 2bc5d7a

Please sign in to comment.