Skip to content

Commit

Permalink
Merge pull request #51 from t32k/develop
Browse files Browse the repository at this point in the history
Support custom request options, and CLI options
  • Loading branch information
t32k committed Mar 28, 2014
2 parents c24afd3 + ed0c023 commit 634d19d
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 30 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ Supports glob(required quotations) input.
$ stylestats 'path/**/*.css'
```

`-t` option output JSON or CSV or HTML.
`-t` option output JSON, CSV and HTML.

```sh
$ stylestats foo.css -t [json|csv|html]
Expand Down Expand Up @@ -195,9 +195,9 @@ var StyleStats = require('stylestats');
var stats = new StyleStats('path/to/stylesheet.css', 'path/to/.stylestatsrc');
```

Default configuration is [here](lib/default.json).
Default configuration is [here](assets/default.json).

Here is an example of enabling display gzipped size:
Here is an example JSON to enable display gzipped size:

```
{
Expand All @@ -223,6 +223,9 @@ $ stylestats -h
-c, --config [path] Path and name of the incoming JSON file.
-t, --type [format] Specify the output format. <json|html|csv>
-s, --simple Show compact style's log.
-g, --gzip Show gzipped file size.
-n, --number Show only numeral metrics.
-u, --ua [OS] Specify the user agent. <ios|android>
```
```shell
Expand Down Expand Up @@ -317,6 +320,7 @@ _(Coming soon)_
## Release History
+ v3.2.0: Support request option, and add ClI options.
+ v3.1.0: Support compiled Less/Stylus files.
+ v3.0.0: __API is changed:__ CLI option. Support parse HTML page.
+ v2.3.0: Support HTML output CLI option.
Expand Down
5 changes: 4 additions & 1 deletion assets/default.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
{
"published": true,
"paths": true,
"stylesheets": true,
"size": true,
"dataUriSize": true,
Expand All @@ -22,5 +24,6 @@
"importantKeywords": true,
"floatProperties": true,
"mediaQueries": true,
"propertiesCount": 10
"propertiesCount": 10,
"customHttpHeaders": {}
}
61 changes: 60 additions & 1 deletion bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

'use strict';

var fs = require('fs');
var path = require('path');
var jade = require('jade');
var Table = require('cli-table');
Expand All @@ -15,6 +16,7 @@ _.mixin(_.str.exports());
_.str.include('Underscore.string', 'string');

var StyleStats = require('../lib/stylestats');
var util = require('../lib/util');

/**
* Prettify StyleStats data.
Expand Down Expand Up @@ -55,14 +57,71 @@ program
.option('-c, --config [path]', 'Path and name of the incoming JSON file.')
.option('-t, --type [format]', 'Specify the output format. <json|html|csv>')
.option('-s, --simple', 'Show compact style\'s log.')
.option('-g, --gzip', 'Show gzipped file size.')
.option('-n, --number', 'Show only numeral metrics.')
.option('-u, --ua [OS]', 'Specify the user agent. <ios|android>')
.parse(process.argv);

if (!program.args.length) {
console.log('\n No input file specified.');
program.help();
}

var stats = new StyleStats(program.args, program.config);

// Config
var config = {
customHttpHeaders: {
headers: {}
}
};
if (program.gzip) {
config.gzippedSize = true;
}
if (program.ua) {
var iOS = 'Mozilla/5.0 (iPhone; CPU iPhone OS 7_0 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11A465 Safari/9537.53';
var Android = 'Mozilla/5.0 (Linux; Android 4.4; Nexus 5 Build/KRT16M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36';
switch (program.ua) {
case 'ios':
config.customHttpHeaders.headers['User-Agent'] = iOS;
break;
case 'android':
config.customHttpHeaders.headers['User-Agent'] = Android;
break;
default:
console.error(' [WARN] User agent should be `ios` or `android`.');
break;
}
}
if (program.number) {
var numberConfig = {
"published": false,
"paths": false,
"mostIdentifierSelector": false,
"lowestCohesionSelector": false,
"uniqueFontSize": false,
"uniqueColor": false,
"propertiesCount": false
};
_.extend(config, numberConfig);
}
var userConfig = {};
if (program.config && util.isFile(program.config)) {
var configString = fs.readFileSync(program.config, {
encoding: 'utf8'
});
try {
userConfig = JSON.parse(configString);
} catch (e) {
throw e;
}
} else if (_.isObject(program.config)) {
userConfig = config;
}
_.extend(config, userConfig);


// Parse
var stats = new StyleStats(program.args, config);
stats.parse(function(result) {
switch (program.type) {
case 'json':
Expand Down
43 changes: 24 additions & 19 deletions lib/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ var util = require('./util');

/**
* Get promised request
* @param {String} url
* @param {Object} options
* @returns {Promise}
*/
function requestSync(url) {
function requestSync(options) {
return new Promise(function(resolve, reject) {
request(url, function(error, response) {
request(options, function(error, response) {
if (!error && response.statusCode === 200) {
resolve(response);
} else if (!error) {
Expand All @@ -35,10 +35,11 @@ function requestSync(url) {
* @param {Array} styles
* @constructor
*/
function Parser(urls, files, styles) {
function Parser(urls, files, styles, options) {
this.urls = urls;
this.files = files;
this.styles = styles;
this.options = options;

this.cssFiles = [];
this.sassFiles = [];
Expand Down Expand Up @@ -69,7 +70,7 @@ function Parser(urls, files, styles) {
Parser.prototype.parse = function(callback) {

// object to return
var result = {
var parsedData = {
cssString: '',
cssSize: 0,
styleElements: 0,
Expand All @@ -85,7 +86,9 @@ Parser.prototype.parse = function(callback) {
// remote file requests
var requestPromises = [];
this.urls.forEach(function(url) {
requestPromises.push(requestSync(url));
var options = that.options.customHttpHeaders;
options.url = url;
requestPromises.push(requestSync(options));
});

// css string array from arguments
Expand Down Expand Up @@ -153,14 +156,16 @@ Parser.prototype.parse = function(callback) {
var $style = $('style');

// add css file count
result.cssFiles += $link.length;
result.styleElements += $style.length;
parsedData.cssFiles += $link.length;
parsedData.styleElements += $style.length;

// request link[href]
$link.each(function() {
var relPath = $(this).attr('href');
var absPath = url.resolve(result.request.href, relPath);
requestPromisesInner.push(requestSync(absPath));
var options = that.options.customHttpHeaders;
options.url = absPath;
requestPromisesInner.push(requestSync(options));
});

// add text in style tags
Expand Down Expand Up @@ -188,45 +193,45 @@ Parser.prototype.parse = function(callback) {
}

// join all css string
result.cssString = that.styles.join('');
result.cssSize = Buffer.byteLength(result.cssString, 'utf8');
parsedData.cssString = that.styles.join('');
parsedData.cssSize = Buffer.byteLength(parsedData.cssString, 'utf8');

// parse css string
var rawRules = [];

try {
rawRules = cssParse(result.cssString).stylesheet.rules;
rawRules = cssParse(parsedData.cssString).stylesheet.rules;
} catch (error) {
throw error;
}

// add rules into result
rawRules.forEach(function(rule) {
if (rule.type === 'rule') {
result.rules.push(rule);
parsedData.rules.push(rule);
} else if (rule.type === 'media') {
result.mediaQueries += 1;
parsedData.mediaQueries += 1;
rule.rules.forEach(function(rule) {
if (rule.type === 'rule') {
result.rules.push(rule);
parsedData.rules.push(rule);
}
});
}
});

// add selectors and declarations into result
result.rules.forEach(function(rule) {
parsedData.rules.forEach(function(rule) {
rule.selectors.forEach(function(selector) {
result.selectors.push(selector);
parsedData.selectors.push(selector);
});
rule.declarations.forEach(function(declaration) {
if (declaration.type === 'declaration') {
result.declarations.push(declaration);
parsedData.declarations.push(declaration);
}
});
});
if (_.isFunction(callback)) {
callback(null, result);
callback(null, parsedData);
}
}, function onRejected(error) {
if (_.isFunction(callback)) {
Expand Down
14 changes: 9 additions & 5 deletions lib/stylestats.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ function StyleStats(args, config) {
}

this.options = _.extend({}, defaultOptions, customOptions);
this.parser = new Parser(this.urls, this.files, this.styles);
this.parser = new Parser(this.urls, this.files, this.styles, this.options);
}

/**
Expand All @@ -101,10 +101,14 @@ StyleStats.prototype.parse = function(callback) {
var analyzeData = analyzer.analyze();

var stats = {};
stats.published = new Date();
stats.paths = [];
Array.prototype.push.apply(stats.paths, that.files);
Array.prototype.push.apply(stats.paths, that.urls);
if (that.options.published) {
stats.published = new Date();
}
if (that.options.paths) {
stats.paths = [];
Array.prototype.push.apply(stats.paths, that.files);
Array.prototype.push.apply(stats.paths, that.urls);
}
if (that.options.stylesheets) {
stats.stylesheets = that.files.length + data.cssFiles - 0;
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "stylestats",
"version": "3.1.0",
"version": "3.2.0",
"main": "lib/stylestats.js",
"bin": {
"stylestats": "bin/cli.js"
Expand Down

0 comments on commit 634d19d

Please sign in to comment.