Skip to content
Browse files

Remove unneeded files

  • Loading branch information...
1 parent a8040ff commit c00c2ac17f1759eabc31ccf17f474ed260906c8b @sindresorhus sindresorhus committed Dec 4, 2012
View
239 cli/bin/yeomaninsight.py
@@ -1,239 +0,0 @@
-#!/usr/bin/env python
-
-from __future__ import print_function
-
-"""This module defines the Yeoman Insight metrics reporter tool."""
-
-__author__ = 'ebidel@gmail.com (Eric Bidelman)'
-
-
-import getopt
-import os
-import random
-import shutil
-import sys
-import time
-
-PYTHON_VERSION_3 = sys.version_info[0] == 3
-
-if PYTHON_VERSION_3:
- import urllib.request, urllib.parse, urllib.error
- import urllib.request, urllib.error, urllib.parse
- URLError = urllib.error.URLError
-else:
- import urllib
- import urllib2
- URLError = urllib2.URLError
-
-NO_STATS = 'NO_STATS'
-DEFAULT_CLI_NAME = 'yeoman'
-
-NUM_SUB_CMDS = 2 # Subcommand depth. TODO: This assumes only "cmd subcmd" format.
-NUM_SECONDS_TO_STASH_DATA = 0 # Send data as it happens.
-
-
-class Analytics(object):
-
- TRACKING_CODE = 'UA-31537568-1'
- BASE_URL = 'http://www.google-analytics.com/collect/__utm.gif'
-
- def __init__(self, tracking_code, application_version):
- if not tracking_code:
- raise Exception('No tracking code was given')
- if not application_version:
- raise Exception('No application version was given')
-
- self.tracking_code = tracking_code
- self.application_version = application_version
- self.do_stats = True
-
- # Create ~/.yeoman/insight if it doesn't exist.
- # install.sh should have taken care of it though.
- if not os.path.exists(INSIGHT_DIR):
- os.makedirs(INSIGHT_DIR)
-
- f = open(LOG_FILE, 'a+') # Open file for reading and appending.
-
- # If we're creating a new file, create a new client ID, setup the file, and
- # record the download action. Otherwise, read the existing client ID saved
- # on the first line of the file.
- if os.path.getsize(LOG_FILE) == 0:
- # Record the initial "download/install". Send it right way.
- # Then have users opt-in.
- self.client_id = '%s%s' % (time.time(), random.random())
- self.__reset_file(f, self.client_id)
- self.record('downloaded')
-
- self._send_all()
-
- else:
- f.seek(0)
- self.client_id = f.readline()[:-1] # Assumes the line ends with "\n".
-
- try:
- first_entry_timestamp = float(f.readline().split(' ')[0])
- time_delta = time.time() - first_entry_timestamp
-
- # If we have data that's too old, send it to Analytics.
- if time_delta >= NUM_SECONDS_TO_STASH_DATA:
- self._send_all()
- except ValueError:
- # Error means we tried to parse a non timestamp or one wasn't present.
- # That means no stats.
- self.do_stats = False
-
- # Insure we're at the EOF to start appending.
- f.seek(os.SEEK_END)
-
- f.close()
-
- def __reset_file(self, f, client_id=None):
- """Setups up the log file for writing entries to.
-
- Args:
- f: A file object, assumed to be open when passed to this method.
- client_id: The client ID to use for this file.
- """
- f.write(client_id+ '\n')
- f.flush()
-
- def _send(self, path='/', recorded_at=None):
- """Sends one pageview entry to Google Analytics.
-
- This method constructs the appropriate URL and makes a GET request to the
- tracking API.
-
- Args:
- path: A string representing the url path of the pageview to record.
- URL query parameters may be included. The format should map to the
- the command that was issued:
- yeoman init -> /init
- yeoman add model -> /add/model
- recorded_at: When the hit was recorded in seconds since the epoch.
- If absent, now is used.
- Returns:
- True if message was sent, otherwise false.
- """
- recorded_at = recorded_at or time.time()
-
- params = {
- 'v': '1', # GA API tracking version.
- 'tid': self.tracking_code, # Tracking code ID.
- 't': 'pageview', # Event type
- 'cid': self.client_id, # Client ID
- 'aip': '1', # Anonymize IP
- 'qt': int((time.time() - recorded_at) * 1e3), # Queue Time. Delta (milliseconds) between now and when hit was recorded.
- 'dp': path,
- 'an': 'Yeoman Insight', # Application Name.
- 'av': self.application_version, # Application Version.
- 'z': time.time() # Cache bust. Probably don't need, but be safe. Should be last param.
- }
-
- if PYTHON_VERSION_3:
- encoded_params = urllib.parse.urlencode(params)
- else:
- encoded_params = urllib.urlencode(params)
-
- url = '%s?%s' % (self.BASE_URL, encoded_params)
-
- # Noop if we're offline. Just keep stashing entries.
- try:
- if PYTHON_VERSION_3:
- response = urllib.request.urlopen(url)
- else:
- response = urllib2.urlopen(url)
- #print(url)
- #if response.code == 200:
- # return True
- return True
- except URLError as e:
- print(e)
- return False
-
- def _send_all(self):
- """Sends all report data stored in the log file to Analytics."""
-
- sent = True
- with open(LOG_FILE) as f:
- # This assumes every line in the log file ends with "\n".
- lines = [line[:-1] for line in f.readlines()]
- for l in lines[1:]: # ClientID is always on the first line. Start on 2nd.
- parts = l.split(' ')
-
- # If one message fails to send, assume we're offline and bomb out.
- sent = self._send(parts[1], recorded_at=float(parts[0]))
- if not sent:
- break
-
- # Proceed with resetting file if everything went well.
- if sent:
- # Reset the file by clearing it and adding in the client id.
- f = open(LOG_FILE, 'w+')
- self.__reset_file(f, self.client_id)
- f.close()
-
- def record(self, cmd_str):
- """Saves the command that was run to a log file.
-
- Args:
- cmd_str: A string representing the full command that was run.
- For example, when running "yeoman add model MyModel", this method
- would save "add model" with a timestamp attached.
- """
- try:
- # Strip cli name off and any whitespace around args.
- cmd_str = ' '.join([x for x in [y.strip() for y in cmd_str.split(CLI_NAME) if y][0].split(' ') if x])
- except IndexError: # yeoman cli cmd was run with no arguments.
- cmd_str = ''
- path = '/'.join(cmd_str.split(' ')[:NUM_SUB_CMDS])
-
- # yeomaninsight.py ... record NO_STATS was sent from cli on first run.
- if self.do_stats and cmd_str != NO_STATS:
- f = open(LOG_FILE, 'a')
- s = '%s /%s' % (time.time(), path)
- f.write(s + '\n')
- f.close()
-
-
-def main(args):
- global INSIGHT_DIR
- global LOG_FILE
- global CLI_NAME
-
- if len(sys.argv) < 2:
- print('Invalid number of arguments.')
- sys.exit(1)
-
- try:
- opts, args = getopt.getopt(sys.argv[1:], 'v:n:', ['version=', 'name='])
- except getopt.GetoptError as err:
- print(str(err))
- sys.exit(1)
-
- application_version = 'x.x.x'
- CLI_NAME = DEFAULT_CLI_NAME
- for opt, val in opts:
- if opt in ('-v', '--version'):
- application_version = val
- elif opt in ('-n', '--name'):
- CLI_NAME = val
-
- method = args[0]
- args = ' '.join(args[1:])
-
- # ~/.yeoman/insight
- INSIGHT_DIR = os.path.join(os.path.expanduser('~'), '.' + CLI_NAME, 'insight')
- LOG_FILE = os.path.join(INSIGHT_DIR, '.log') # ~/.yeoman/insight/.log
-
- ga = Analytics(Analytics.TRACKING_CODE, application_version)
-
- #if callable(getattr(ga, method)):
- # getattr(ga, method)()
- if method == 'record':
- ga.record(args)
- #elif method == 'send_all':
- # ga.send_all()
-
-
-if __name__ == '__main__':
- main(sys.argv)
View
87 cli/lib/plugins/insight.js
@@ -1,87 +0,0 @@
-var fs = require('fs'),
- join = require('path').join,
- exec = require('child_process').exec,
- colors = require('colors'),
- prompt = require('prompt');
-
-/**
- * Records the give cmd to Insight.
- *
- * It's assumed yeomaninsight.py is installed globally as
- * /usr/local/bin/_yeomaninsight (or platform equivalent). A full cmd would
- * might look like: _yeomaninsight -n yeoman -v 0.0.1 record cmd cmd2
- *
- * @param {string} cmd The full command line that was run.
- * @param {Function} callback Callback to call when Insight is done.
- */
-function invokeInsight(cmd, callback) {
- exec(cmd, function(err, stdout, stderr) {
- if (err) {
- console.log(stderr);
- return callback(err);
- }
- callback();
- });
-}
-
-module.exports = {
- init: function(opts) {
-
- var insight = {
- // Store records in user's home dir (e.g. /Users/username/.yeoman/insight)
- logFile: join(opts.getUserHome(), '.' + opts.pkgname, 'insight', '.log'),
- script: '_' + opts.pkgname + 'insight',
- recordArgs: ['-n', opts.pkgname, '-v', opts.pkgversion, 'record'],
- record: invokeInsight
- };
-
- // Example: _yeomaninsight -n yeoman -v 0.9.4 record cmd cmd2.
- var cmdStr = insight.script + ' ' +
- insight.recordArgs.concat(opts.cmds).join(' ');
-
- fs.stat(insight.logFile, function(err, stats) {
- // Error means file doesn't exist and this is the first run.
- // Go through stat opt-in flow.
- if (!err) {
- return insight.record(cmdStr, opts.cb);
- }
-
-/*jshint multistr:true */
-var msg = "\
-==========================================================================".grey + "\n\
-We're constantly looking for ways to make ".yellow + opts.pkgname.bold.red + " better! \n\
-May we anonymously report usage statistics to improve the tool over time? \n\
-More info: yeoman.io/insight.html & http://yeoman.io".yellow + "\n\
-==========================================================================".grey;
-
- prompt.message = '[' + '?'.green + ']';
- prompt.delimiter = ' ';
-
- var properties = [{
- name: 'optin',
- message: '[Y/n]: ',
- "default": 'Y',
- validator: /^[yntf]{1}/i,
- empty: false
- }];
-
- prompt.start();
- console.log(msg);
- prompt.get(properties, function(err, result) {
- if (err) {
- return opts.cb(err);
- }
-
- if (/n/i.test(result.optin)) {
- cmdStr = insight.script + ' ' +
- insight.recordArgs.concat(['NO_STATS']).join(' ');
- return insight.record(cmdStr, opts.cb);
- }
-
- insight.record(cmdStr, opts.cb);
- });
-
- });
-
- }
-};
View
305 cli/lib/plugins/updater.js
@@ -1,305 +0,0 @@
-// Updater.js: npm version checker and updater for packages
-// @author: Addy Osmani and Sindre Sorhus
-// @inspired by: npm, npm-latest
-//
-// Sample usage:
-//
-// Query for the latest update type
-// updater.getUpdate({ name: 'grunt', version: pkg.version }, function( error, update ) {
-// console.log('Update checking complete');
-// });
-//
-// Alternatively, if you just want to pass in a package.json
-// file directly, you can simply do:
-//
-// updater.getUpdate({ localPackageUrl: '../package.json' }, function( error, update ) {
-// console.log('Update checking complete');
-// });
-//
-// Both will either return patch, minor, major or latest. These
-// correspond to:
-//
-// patch 0.0.x: Forced auto-update with opt-out
-// ability. Since it should only contain backwards
-// compatible bugfixes.
-//
-// minor 0.x.0: Update prompts (with auto-update
-// after a set time) with ability to opt out of
-// auto-update.
-//
-// major: x.0.0: Update prompts (no time-limit),
-// since this can contain backwards incompatible changes.
-//
-// latest: you are already up to date
-//
-
-var fs = require('fs');
-var path = require('path');
-var util = require('util');
-var exec = require('child_process').exec;
-var EventEmitter = require('events').EventEmitter;
-var request = require('request');
-var colors = require('colors');
-var prompt = require('prompt');
-
-
-var updater = module.exports;
-
-
-var config = (function() {
- var mkdirp = require('mkdirp');
- var homeDir = process.env[ process.platform === 'win32' ? 'USERPROFILE' : 'HOME' ];
- var folderPath = path.join( homeDir, '.config', 'npm-updater' );
- // Function, since _packageName is not available when this is init'd
- var filename = function() {
- return updater._packageName + '.json';
- };
-
- var loadConfig = function() {
- try {
- return JSON.parse( fs.readFileSync( path.join( folderPath, filename() ), 'utf-8' ) || {} );
- } catch ( err ) {
- // Create dir if it doesn't exist
- if ( err.errno === 34 ) {
- mkdirp.sync( folderPath );
- return {};
- }
- }
- };
-
- return {
- get: function( key ) {
- return loadConfig()[ key ];
- },
- set: function( key, val ) {
- var config = loadConfig();
- config[ key ] = val;
- fs.writeFileSync( path.join( folderPath, filename() ), JSON.stringify( config, null, '\t' ) );
- }
- };
-})();
-
-
-
-
-// Registry end-point
-// Alternative registry mirrors
-// http://85.10.209.91/%s
-// http://165.225.128.50:8000/%s
-updater.registryUrl = 'http://registry.npmjs.org/%s';
-
-// How often the updater should check for updates
-updater.updateCheckInterval = 1000 * 60 * 60 * 24; // 1 day
-
-// How long it should wait until force auto-update
-updater.updatePromptTimeLimit = 1000 * 60 * 60 * 24 * 7; // 1 week
-
-
-// Prompt for update
-updater.promptUpdate = function promptUpdate( cb ) {
- prompt.start();
- prompt.message = 'yeoman'.red;
- prompt.get([{
- name: 'shouldUpdate',
- message: ( 'Do you want to upgrade ' + this._packageName + '?' ).yellow
- }], function( err, result ) {
- cb( !err && /^y/i.test( result.shouldUpdate ) );
- });
-};
-
-
-// TODO(sindresorhus): Docs
-// Prefilter to be overriden if custom logic is needed
-updater.shouldUpdate = function shouldUpdate( update, cb ) {
- var severity = update.severity;
-
- console.log('Update available: ' + update.latest.green +
- (' (current: ' + update.current + ')').grey );
-
- if ( config.get('optOut') === true ) {
- console.log('You have opted out of automatic updates');
- console.log('Run `npm update -g yeoman` to update');
- return cb( false );
- }
-
- if ( severity === 'patch' ) {
- cb( true );
- }
-
- if ( severity === 'minor' ) {
- // Force auto-update if it's past the set time limit
- if ( new Date() - new Date( update.date ) > this.updatePromptTimeLimit ) {
- console.log( 'Forcing update because it\'s been too long since last'.red );
- return cb( true );
- }
-
- this.promptUpdate(function( shouldUpdate ) {
- cb( shouldUpdate );
- });
- }
-
- if ( severity === 'major' ) {
- this.promptUpdate(function( shouldUpdate ) {
- cb( shouldUpdate );
- });
- }
-};
-
-
-//
-// updater.getUpdate()
-// Returns the severity of the latest update available
-//
-// Supported options:
-//
-// @options.name: package name
-//
-// @options.version: local package version
-//
-// @options.localPackageUrl: the url to a local package to be
-// checked against if no package name or version are supplied
-//
-// cb: callback for when the update checks and update is complete
-
-updater.getUpdate = function getUpdate( options, cb ) {
- var localPackage, url;
- var controller = new EventEmitter();
-
- cb = cb || function() {};
-
- // Step 1: We need a package name and version to work off.
-
- // Ideally, supply us with the package name and version
- if ( options.name === undefined || options.version === undefined ) {
- // If not, we'll ascertain from a local package.json file
- if ( options.localPackageUrl ) {
- localPackage = require( options.localPackageUrl );
- options.name = localPackage.name;
- options.version = localPackage.version;
- } else {
- cb();
- return console.error('No package name/version or local package supplied');
- }
- }
-
- // Expose the packageName internally, but still
- // make it accessible if somone would need it
- this._packageName = options.name;
-
- // Create the `optOut` option, so it's easy to switch the flag
- if ( config.get('optOut') === undefined ) {
- config.set( 'optOut', false );
- }
-
- // Only check for updates on a set interval
- if ( new Date() - config.get('lastUpdateCheck') < this.updateCheckInterval ) {
- cb();
- return;
- }
-
- console.log('Starting update check...');
-
- // Update the last update check date
- config.set( 'lastUpdateCheck', +new Date() );
-
- // Step 2: Query the NPM registry for the latest package
- url = util.format( this.registryUrl, options.name );
-
- request({ url: url, json: true }, function( error, response, body ) {
- var latest, update;
-
- // TODO(sindresorhus): Look into the best way to output errors, only cb or cb + emit?
-
- // Fetch issue incurred
- if ( error ) {
- controller.emit('fetchError', {
- message: error.message,
- httpCode: response && response.statusCode
- });
-
- cb( error );
-
- return;
- }
-
- // Whoops, package not found
- if ( body.error ) {
- controller.emit('npmError', {
- errorType: body.error, // not_found etc
- reason: body.reason // additional reason
- });
-
- cb( error );
-
- return;
- }
-
- // Step 3: Package found, lets compare versions
- latest = Object.keys( body.time ).reverse()[0];
-
- // Details to expose about the update
- update = {
- latest: latest,
- date: body.time[ latest ],
- current: options.version,
- severity: this.parseUpdateType( options.version, latest )
- };
-
- if ( update.severity !== 'latest' ) {
- this.shouldUpdate( update, function( shouldUpdate ) {
- if ( shouldUpdate ) {
- this.updatePackage( options.name, function( err, data ) {
- if ( err ) {
- console.error( '\nUpdate error', err );
- } else {
- console.log( '\nUpdated successfully!'.green );
- }
-
- cb( err, update );
- });
- } else {
- cb( err, update );
- }
- }.bind(this));
- } else {
- cb();
- }
- }.bind(this));
-};
-
-
-
-// Compare a local package version and remote package version
-// to discover what type of update (major, minor, patch) is
-// available.
-updater.parseUpdateType = function parseUpdateType( current, remoteVersion ) {
- var current, remote;
-
- if ( current === remoteVersion ) {
- return 'latest';
- }
-
- current = current.split('.');
- remote = remoteVersion.split('.');
-
- if ( remote[0] > current[0] ) {
- return 'major';
- } else if ( remote[1] > current[1] ) {
- return 'minor';
- } else if ( remote[2] > current[2] ) {
- return 'patch';
- } else{
- return 'Update comparison error';
- }
-};
-
-
-// Run `npm update` against a specific package name
-updater.updatePackage = function updatePackage( packageName, cb ) {
- // TODO(sindresorhus): Find a better solution for local packages
- // Something like going up filestructure until node_modules folder
- var child = exec( 'npm update -g ' + packageName, cb );
- console.log( 'Updating ' + packageName + '\n' );
- child.stdout.pipe( process.stdout );
- child.stderr.pipe( process.stderr );
-};
View
471 cli/lib/support/confess.js
@@ -1,471 +0,0 @@
-var fs = require('fs');
-var confess = {
-
- run: function () {
- var cliConfig = {};
- if (!this.processArgs(cliConfig, [
- {
- name: 'url',
- def: 'http://google.com',
- req: true,
- desc: 'the URL of the app to cache'
- }, {
- name: 'task',
- def: 'appcache',
- req: false,
- desc: 'the task to perform',
- oneof: ['performance', 'appcache', 'cssproperties']
- }, {
- name: 'configFile',
- def: 'config.json',
- req: false,
- desc: 'a local configuration file of further confess settings'
- },
- ])) {
- phantom.exit();
- return;
- }
- this.config = this.mergeConfig(cliConfig, cliConfig.configFile);
- var task = this[this.config.task];
- this.load(this.config, task, this);
- },
-
- performance: {
- resources: [],
- onLoadStarted: function (page, config) {
- if (!this.performance.start) {
- this.performance.start = new Date().getTime();
- }
- },
- onResourceRequested: function (page, config, request) {
- var now = new Date().getTime();
- this.performance.resources[request.id] = {
- id: request.id,
- url: request.url,
- request: request,
- responses: {},
- duration: '-',
- times: {
- request: now
- }
- };
- if (!this.performance.start || now < this.performance.start) {
- this.performance.start = now;
- }
- },
- onResourceReceived: function (page, config, response) {
- var now = new Date().getTime(),
- resource = this.performance.resources[response.id];
- resource.responses[response.stage] = response;
- if (!resource.times[response.stage]) {
- resource.times[response.stage] = now;
- resource.duration = now - resource.times.request;
- }
- if (response.bodySize) {
- resource.size = response.bodySize;
- } else if (!resource.size) {
- response.headers.forEach(function (header) {
- if (header.name.toLowerCase()=='content-length') {
- resource.size = parseInt(header.value);
- }
- });
- }
- },
- onLoadFinished: function (page, config, status) {
- var start = this.performance.start,
- finish = new Date().getTime(),
- resources = this.performance.resources,
- slowest, fastest, totalDuration = 0,
- largest, smallest, totalSize = 0,
- missingSize = false,
- elapsed = finish - start,
- length = 104,
- ratio = length / elapsed,
- bar;
-
- resources.forEach(function (resource) {
- if (!resource.times.start) {
- resource.times.start = resource.times.end;
- }
- if (!slowest || resource.duration > slowest.duration) {
- slowest = resource;
- }
- if (!fastest || resource.duration < fastest.duration) {
- fastest = resource;
- }
- totalDuration += resource.duration;
-
- if (resource.size) {
- if (!largest || resource.size > largest.size) {
- largest = resource;
- }
- if (!smallest || resource.size < smallest.size) {
- smallest = resource;
- }
- totalSize += resource.size;
- } else {
- resource.size = '-';
- missingSize = true;
- }
- });
-
- if (config.verbose) {
- console.log('');
- this.emitConfig(config, '');
- }
- console.log('');
- console.log('Elapsed load time: ' + this.pad(elapsed, 6) + 'ms');
- console.log(' # of resources: ' + this.pad(resources.length-1, 8));
- console.log('');
- console.log(' Fastest resource: ' + this.pad(fastest.duration, 6) + 'ms; ' + this.truncate(fastest.url));
- console.log(' Slowest resource: ' + this.pad(slowest.duration, 6) + 'ms; ' + this.truncate(slowest.url));
- console.log(' Total resources: ' + this.pad(totalDuration, 6) + 'ms');
- console.log('');
- console.log('Smallest resource: ' + this.pad(smallest.size, 7) + 'b; ' + this.truncate(smallest.url));
- console.log(' Largest resource: ' + this.pad(largest.size, 7) + 'b; ' + this.truncate(largest.url));
- console.log(' Total resources: ' + this.pad(totalSize, 7) + 'b' + (missingSize ? '; (at least)' : ''));
- if (config.verbose) {
- console.log('');
- resources.forEach(function (resource) {
- bar = this.repeat(' ', (resource.times.request - start) * ratio) +
- this.repeat('-', (resource.times.start - resource.times.request) * ratio) +
- this.repeat('=', (resource.times.end - resource.times.start) * ratio)
- ;
- bar = bar.substr(0, length) + this.repeat(' ', length - bar.length);
- console.log(this.pad(resource.id, 3) + '|' + bar + '|');
- }, this);
- console.log('');
- resources.forEach(function (resource) {
- console.log(
- this.pad(resource.id, 3) + ': ' +
- this.pad(resource.duration, 6) + 'ms; ' +
- this.pad(resource.size, 7) + 'b; ' +
- this.truncate(resource.url, 84)
- );
- }, this);
- }
- }
- },
-
- appcache: {
- resourceUrls: {},
- onResourceRequested: function (page, config, request) {
- if (config.appcache.urlsFromRequests) {
- this.appcache.resourceUrls[request.url] = true;
- }
- },
- onLoadFinished: function (page, config, status) {
- if (status!='success') {
- console.log('# FAILED TO LOAD');
- return;
- }
-
- var key, key2, url,
- neverMatch = "(?!a)a",
- cacheRegex = new RegExp(config.appcache.cacheFilter || neverMatch),
- networkRegex = new RegExp(config.appcache.networkFilter || neverMatch);
-
- console.log('CACHE MANIFEST');
- console.log('');
- console.log('# Time: ' + new Date());
- if (config.verbose) {
- console.log('# This manifest was created by confess.js, http://github.com/jamesgpearce/confess');
- console.log('#');
- console.log('# Retrieved URL: ' + this.getFinalUrl(page));
- console.log('# User-agent: ' + page.settings.userAgent);
- console.log('#');
- this.emitConfig(config, '# ');
- }
- console.log('');
- console.log('CACHE:');
-
- if (config.appcache.urlsFromDocument) {
- for (url in this.getResourceUrls(page)) {
- this.appcache.resourceUrls[url] = true;
- }
- }
- for (url in this.appcache.resourceUrls) {
- if (cacheRegex.test(url) && !networkRegex.test(url)) {
- console.log(url);
- }
- };
- console.log('');
- console.log('NETWORK:');
- console.log('*');
- }
- },
-
- cssproperties: {
- resourceUrls: {},
- onResourceRequested: function (page, config, request) {
- if (config.appcache.urlsFromRequests) {
- this.appcache.resourceUrls[request.url] = true;
- }
- },
- onLoadFinished: function (page, config, status) {
- if (status!='success') {
- console.log('# FAILED TO LOAD');
- return;
- }
- if (config.verbose) {
- console.log('');
- this.emitConfig(config, '');
- }
- console.log('');
- console.log('CSS properties used:');
- for (property in this.getCssProperties(page)) {
- console.log(property);
- }
- }
- },
-
- getFinalUrl: function (page) {
- return page.evaluate(function () {
- return document.location.toString();
- });
- },
-
- getResourceUrls: function (page) {
- return page.evaluate(function () {
- var
- // resources referenced in DOM
- // notable exceptions: iframes, rss, links
- selectors = [
- ['script', 'src'],
- ['img', 'src'],
- ['link[rel="stylesheet"]', 'href']
- ],
-
- resources = {},
- baseScheme = document.location.toString().split("//")[0],
- tallyResource = function (url) {
- if (url && url.substr(0,5)!='data:') {
- if (url.substr(0, 2)=='//') {
- url = baseScheme + url;
- }
- if (!resources[url]) {
- resources[url] = 0;
- }
- resources[url]++;
- }
- },
-
- elements, elementsLength, e,
- stylesheets, stylesheetsLength, ss,
- rules, rulesLength, r,
- style, styleLength, s,
- computed, computedLength, c,
- value;
-
- // attributes in DOM
- selectors.forEach(function (selectorPair) {
- elements = document.querySelectorAll(selectorPair[0]);
- for (e = 0, elementsLength = elements.length; e < elementsLength; e++) {
- tallyResource(elements[e].getAttribute(selectorPair[1]));
- };
- });
-
- // URLs in stylesheets
- stylesheets = document.styleSheets;
- for (ss = 0, stylesheetsLength = stylesheets.length; ss < stylesheetsLength; ss++) {
- rules = stylesheets[ss].rules;
- if (!rules) { continue; }
- for (r = 0, rulesLength = rules.length; r < rulesLength; r++) {
- if (!rules[r]['style']) { continue; }
- style = rules[r].style;
- for (s = 0, styleLength = style.length; s < styleLength; s++) {
- value = style.getPropertyCSSValue(style[s]);
- if (value && value.primitiveType == CSSPrimitiveValue.CSS_URI) {
- tallyResource(value.getStringValue());
- }
- }
- };
- };
-
- // URLs in styles on DOM
- elements = document.querySelectorAll('*');
- for (e = 0, elementsLength = elements.length; e < elementsLength; e++) {
- computed = elements[e].ownerDocument.defaultView.getComputedStyle(elements[e], '');
- for (c = 0, computedLength = computed.length; c < computedLength; c++) {
- value = computed.getPropertyCSSValue(computed[c]);
- if (value && value.primitiveType == CSSPrimitiveValue.CSS_URI) {
- tallyResource(value.getStringValue());
- }
- }
- };
-
- return resources;
- });
- },
-
- getCssProperties: function (page) {
- return page.evaluate(function () {
- var properties = {},
- tallyProperty = function (property) {
- if (!properties[property]) {
- properties[property] = 0;
- }
- properties[property]++;
- },
- stylesheets, stylesheetsLength, ss,
- rules, rulesLength, r,
- style, styleLength, s,
- property;
-
- // properties in stylesheets
- stylesheets = document.styleSheets;
- for (ss = 0, stylesheetsLength = stylesheets.length; ss < stylesheetsLength; ss++) {
- rules = stylesheets[ss].rules;
- if (!rules) { continue; }
- for (r = 0, rulesLength = rules.length; r < rulesLength; r++) {
- if (!rules[r]['style']) { continue; }
- style = rules[r].style;
- for (s = 0, styleLength = style.length; s < styleLength; s++) {
- tallyProperty(style[s]);
- }
- }
- }
-
- // properties in styles on DOM
- elements = document.querySelectorAll('*');
- for (e = 0, elementsLength = elements.length; e < elementsLength; e++) {
- rules = elements[e].ownerDocument.defaultView.getMatchedCSSRules(elements[e], '');
- if (!rules) { continue; }
- for (r = 0, rulesLength = rules.length; r < rulesLength; r++) {
- if (!rules[r]['style']) { continue; }
- style = rules[r].style;
- for (s = 0, styleLength = style.length; s < styleLength; s++) {
- tallyProperty(style[s]);
- }
- }
- }
- return properties;
- });
- },
-
- emitConfig: function (config, prefix) {
- console.log(prefix + 'Config:');
- for (key in config) {
- if (config[key].constructor === Object) {
- if (key===config.task) {
- console.log(prefix + ' ' + key + ':');
- for (key2 in config[key]) {
- console.log(prefix + ' ' + key2 + ': ' + config[key][key2]);
- }
- }
- } else {
- console.log(prefix + ' ' + key + ': ' + config[key]);
- }
- }
- },
-
- load: function (config, task, scope) {
- var page = new WebPage(),
- event;
- if (config.consolePrefix) {
- page.onConsoleMessage = function (msg, line, src) {
- console.log(config.consolePrefix + ' ' + msg + ' (' + src + ', #' + line + ')');
- }
- }
- if (config.userAgent && config.userAgent != "default") {
- if (config.userAgentAliases[config.userAgent]) {
- config.userAgent = config.userAgentAliases[config.userAgent];
- }
- page.settings.userAgent = config.userAgent;
- }
- ['onInitialized', 'onLoadStarted', 'onResourceRequested', 'onResourceReceived']
- .forEach(function (event) {
- if (task[event]) {
- page[event] = function () {
- var args = [page, config],
- a, aL;
- for (a = 0, aL = arguments.length; a < aL; a++) {
- args.push(arguments[a]);
- }
- task[event].apply(scope, args);
- };
- }
- });
- if (task.onLoadFinished) {
- page.onLoadFinished = function (status) {
- if (config.wait) {
- setTimeout(
- function () {
- task.onLoadFinished.call(scope, page, config, status);
- phantom.exit();
- },
- config.wait
- );
- } else {
- task.onLoadFinished.call(scope, page, config, status);
- phantom.exit();
- }
- };
- } else {
- page.onLoadFinished = function (status) {
- phantom.exit();
- }
- }
- page.open(config.url);
- },
-
- processArgs: function (config, contract) {
- var a = 0;
- var ok = true;
- contract.forEach(function(argument) {
- if (a < phantom.args.length) {
- config[argument.name] = phantom.args[a];
- } else {
- if (argument.req) {
- console.log('"' + argument.name + '" argument is required. This ' + argument.desc + '.');
- ok = false;
- } else {
- config[argument.name] = argument.def;
- }
- }
- if (argument.oneof && argument.oneof.indexOf(config[argument.name])==-1) {
- console.log('"' + argument.name + '" argument must be one of: ' + argument.oneof.join(', '));
- ok = false;
- }
- a++;
- });
- return ok;
- },
-
- mergeConfig: function (config, configFile) {
- if (!fs.exists(configFile)) {
- configFile = "config.json";
- }
- var result = JSON.parse(fs.read(configFile)),
- key;
- for (key in config) {
- result[key] = config[key];
- }
- return result;
- },
-
- truncate: function (str, length) {
- length = length || 80;
- if (str.length <= length) {
- return str;
- }
- var half = length / 2;
- return str.substr(0, half-2) + '...' + str.substr(str.length-half+1);
- },
-
- pad: function (str, length) {
- var padded = str.toString();
- if (padded.length > length) {
- return this.pad(padded, length * 2);
- }
- return this.repeat(' ', length - padded.length) + padded;
- },
-
- repeat: function (chr, length) {
- // Add +1 to ensure the _correct_ number of "chr" are repeated
- return (new Array(length + 1)).join(chr);
- }
-
-};
-
-confess.run();
View
18 cli/lib/support/confess.json
@@ -1,18 +0,0 @@
-{
- "task": "appcache",
- "userAgent": "chrome",
- "userAgentAliases": {
- "iphone": "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7",
- "android": "Mozilla/5.0 (Linux; U; Android 2.2; en-us; Nexus One Build/FRF91) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1",
- "chrome": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.12 Safari/535.11"
- },
- "wait": 0,
- "consolePrefix": "#",
- "verbose": true,
- "appcache": {
- "urlsFromDocument": true,
- "urlsFromRequests": false,
- "cacheFilter": ".*",
- "networkFilter": null
- }
-}
View
59 cli/lib/utils/fetch.js
@@ -1,59 +0,0 @@
-var fs = require('fs'),
- path = require('path'),
- colors = require('colors'),
- zlib = require('zlib'),
- request = require('request'),
- tar = require('tar');
-
-// Check if we're behind some kind of proxy.
-var proxy = process.env.http_proxy || process.env.HTTP_PROXY ||
- process.env.https_proxy || process.env.HTTPS_PROXY || '';
-
-// heavily based on npm's util/untar.js file
-function fetch(tarball, target, cb) {
- var now = +new Date();
-
- var log = this.log
- .subhead('Fetching ' + tarball)
- .writeln('This might take a few moment'.yellow);
-
- // tarball untar opts
- var extractOpts = { type: 'Directory', path: target, strip: 1 };
-
- // remote request --> zlib.Unzip() --> untar into h5bp/root
- var req = fetch.request.get(tarball).on('error', cb);
-
- req.on('data', function() { log.write('.'); }).on('end', function() {
- log.ok().writeln();
- log.ok( ('Done in ' + (+new Date() - now) / 1000 + 's.').green );
- });
-
- req
- // first gzip
- .pipe(zlib.Unzip())
- .on('error', function(err) {
- console.error('unzip error', err);
- cb(err);
- })
- // then tar extract into h5bp/root
- .pipe(tar.Extract(extractOpts))
- .on('entry', function(entry) {
- entry.props.uid = entry.uid = 501;
- entry.props.gid = entry.gid = 20;
- })
- .on('error', function(err) {
- console.error('untar error', err);
- cb(err);
- })
- .on('close', function() {
- log.writeln().ok( ('Done in ' + extractOpts.path).green ).writeln();
- cb();
- });
-}
-
-
-module.exports = fetch;
-
-// re-expose the request with proxy defaults, so that we can
-// reuse this instance of request.
-fetch.request = request.defaults({ proxy: proxy });
View
60 cli/lib/utils/index.js
@@ -1,60 +0,0 @@
-
-var path = require('path');
-
-var utils = module.exports;
-
-//
-// flatiron/utile inspired.
-//
-// Set of common utilities, mainly defining wrapper to various utility modules
-// (like mkdir, rimraf) as lazy-loaded getters.
-
-
-Object.defineProperties( utils,
- [
- // Wrapper to `require('mkdirp')`
- 'mkdirp',
- // Wrapper to `require('rimraf')`
- 'rimraf',
- // Wrapper to `require('./fetch')`, internal tarball helper using
- // mikeal/request, zlib and isaacs/tar.
- './fetch'
- ].reduce(function( descriptor, api ) {
- return (
- // Add the Identifier and define a get accessor that returns
- // a fresh or cached copy of the API; remove any
- // non-alphanumeric characters (in the case of "./fetch")
- descriptor[ api.replace(/\W/g, '') ] = {
- get: function() { return require(api); }
- },
- // Return the |descriptor| object at the end of the expression,
- // continuing the the reduction.
- descriptor
- );
- // Prime the "initialVal" with an empty object
- }, {})
-);
-
-
-// **extend** a given object with the util module definition, taking care
-// of not triggering the getters. Doing so with _.extend makes the module
-// to be required right away.
-utils.extend = function extend(o) {
- Object.keys(utils).forEach(function(prop) {
- Object.defineProperty(o, prop, {
- get: function() {
- return utils[prop];
- }
- });
- });
- return o;
-};
-
-//
-// **join** basic wrapper to `path.join`, dealing with `//` and converting back
-// **`\` windows like path to unix like one.
-//
-utils.join = function join() {
- var args = Array.prototype.slice.call(arguments);
- return path.join.apply(path, args).replace(/\\/g, '/');
-};
View
1 cli/package.json
@@ -16,7 +16,6 @@
"homepage": "http://yeoman.io",
"bugs": "https://github.com/yeoman/yeoman/issues",
"author": "Chrome Developer Relations",
- "main": "yeoman",
"bin": {
"yeoman": "bin/yeoman"
},
View
63 cli/tasks/bower.js
@@ -1,63 +0,0 @@
-
-var path = require('path');
-var fs = require('fs');
-var bower = require('bower');
-var template = require('bower/lib/util/template');
-var shelljs = require('shelljs');
-
-
-module.exports = function(grunt) {
-
- // Task facade to Twitter Bower.
- //
- // This task basically just pases our current provess.argv to bower. Special tasks
- // like install, list, search etc. are all configured to trigger this one.
- //
- // A yeoman-specific configuration can be defined in your Gruntfile:
- //
- // - dir: Alternate directory location. (defaults to: components)
- //
- // If the dir option is specified, bower is asked for the package dependency
- // model and each paths. Each package is then simply copied over the value of
- // the dir options.
- //
- // `components/` next to your Gruntfile is bower's internal directory.
- // `app/js/vendor` is your working directory, files used in development and
- // concat / min by grunt script.
- grunt.registerTask('bower', 'This triggers the `bower` commands.', function() {
- // pull in the bower command module
- var args = this.args;
- var command = bower.commands[args[0]];
- if(!command) {
- return grunt.fatal('A valid bower command should be specified.');
- }
-
- // run
- var cb = this.async();
- command.line(process.argv)
- .on('error', grunt.fatal.bind(grunt.fail))
- .on('data', grunt.log.writeln.bind(grunt.log));
- });
-
-
- // Little grunt helper to access the bower template facility.
- //
- // - name - a String to define the template name to invoke
- // - context - A hash of data to pass through the given template
- //
- // Returns the template output
- grunt.registerHelper('bower:template', function(name, context) {
- return template(name, context, true);
- });
-
- // Helper to log through bower template action utility.
- //
- // - name - main message.
- // - stuff - additional logging message. Displayed in grey.
- grunt.registerHelper('bower:log', function(name, stuff) {
- grunt.log.writeln(grunt.helper('bower:template', 'action', {
- name: name,
- shizzle: stuff
- }));
- });
-};
View
52 cli/tasks/compass.js
@@ -1,52 +0,0 @@
-module.exports = function( grunt ) {
- 'use strict';
-
- var _ = grunt.util._;
-
- function optsToArgs( opts ) {
- var args = [];
-
- Object.keys( opts ).forEach(function( el ) {
- var val = opts[ el ];
-
- el = el.replace( /_/g, '-' );
-
- if ( val === true ) {
- args.push( '--' + el );
- }
-
- if ( _.isString( val ) ) {
- args.push( '--' + el, val );
- }
-
- if( _.isArray( val ) ) {
- val.forEach(function( subval ) {
- args.push( '--' + el, subval );
- });
- }
- });
-
- return args;
- }
-
- grunt.registerMultiTask( 'compass', 'Compass task', function() {
- var cb = this.async();
- var args = optsToArgs( this.options() );
-
- var compass = grunt.util.spawn({
- cmd: 'compass',
- args: ['compile'].concat( args )
- }, function( err, result, code ) {
- if ( /not found/.test( err ) ) {
- grunt.fail.fatal('You need to have Compass installed.');
- }
- // Since `compass compile` exits with 1 when it has nothing to compile,
- // we do a little workaround by checking stdout which is then empty
- // https://github.com/chriseppstein/compass/issues/993
- cb( code === 0 || !result.stdout );
- });
-
- compass.stdout.pipe( process.stdout );
- compass.stderr.pipe( process.stderr );
- });
-};
View
85 cli/tasks/css.js
@@ -1,85 +0,0 @@
-
-var fs = require('fs'),
- path = require('path'),
- cleanCSS = require('clean-css'),
- rjs = require('requirejs');
-
-module.exports = function(grunt) {
-
-
-
- // **css* task works pretty much the same as grunt's min task. The task
- // target is the destination, data is an array of glob patterns. These
- // files are concataned and run through requirejs optimizer to handle
- // @import inlines in CSS files.
- grunt.task.registerMultiTask('css', 'Concats, replaces @imports and minifies the CSS files', function() {
- this.requiresConfig('staging');
-
- // if defined, files get prepended by the output config value
- var files = this.data;
-
- // subtarget name is the output destination
- var target = this.target;
-
- // async task
- var cb = this.async();
-
- // concat prior to rjs optimize css, and before min max info
- grunt.log.write('Writing css files to ' + target + '...');
- var out = grunt.helper('mincss', files);
- // only go through if their's file to process
- if(!out) {
- return cb();
- }
-
- // write minified file before going through rjs:optimize to possibly inline
- // @imports (that are not handled by compass within .scss or .sass files)
- grunt.file.write(target, out);
-
- // replace @import statements
- //
- // XXX no error handling in this helper so far..
- // Check that rjs returns an error when something wrong (if it throws...)
- // if it is bubble the error back here
- grunt.helper('rjs:optimize:css', target, function() {
- // do the minification once inline imports are done
- grunt.log.ok();
- cb();
- });
- });
-
- //
- // **mincss** basic utility to concat CSS files and run them through
- // [cleanCSS](https://github.com/GoalSmashers/clean-css), might opt to use
- // [https://github.com/jzaefferer/grunt-css] plugin.
- //
- grunt.registerHelper('mincss', function(files, o) {
- o = o || {};
- files = grunt.file.expandFiles(files);
- return files.map(function(filepath) {
- var content = grunt.file.read(filepath);
- return o.nocompress ? content : cleanCSS.process(content);
- }).join('');
- });
-
- // **rjs:optimize:css** is an helper using rjs to optimize a single file,
- // mainly to properly import multi-level of @import statements, which can be
- // tricky with all the url rewrites.
- //
- // file - Path to the css file to optimize
- // options - (optional) rjs configuration
- // cb - callback function to call on completion
- grunt.registerHelper('rjs:optimize:css', function(file, options, cb) {
- if(!cb) { cb = options; options = {}; }
- options.cssIn = file;
- options.out = options.out || file;
- options.optimizeCss = 'standard.keepComments.keepLines';
- var before = grunt.file.read(file);
- rjs.optimize(options, function() {
- grunt.helper('min_max_info', grunt.file.read(file), before);
- cb();
- });
- });
-
-};
-
View
147 cli/tasks/html.js
@@ -1,147 +0,0 @@
-
-var path = require('path'),
- minifier = require('html-minifier');
-
-//
-// This task takes care of html minification through @kangax' html-minifier
-// project
-//
-// > http://perfectionkills.com/experimenting-with-html-minifier/
-//
-// This is not a multi-task, but a simple one. The configuration is as follow:
-//
-// ...
-// html: {
-// files: ['**/*.html']
-// options: {
-// ...
-// }
-// }
-// ...
-//
-// Usage:
-//
-// grunt html:<type>
-//
-// Three "types" of html compression are supported. They map the html
-// options of h5bp/ant-build-script, except that types and configuration works
-// in "reverse order" here. (eg. default type is most aggresive compression).
-// And we at the moment only have two types of html compression.
-//
-// * compress: (when `grunt html` or `grunt html:compress` is run)
-// Agrresive html compression (Most advanced optimization configuration,
-// Full html minification)
-//
-// * buildkit: (when `grunt html:buildkit` is run)
-// all html whitespace/comments maintained (todo: inline and minify
-// style/script)
-//
-// * basics: (when `grunt html:basics` is run) Intermediate html compression
-// (whitespace removed / comments removed)
-//
-// One very last thing this tasks needs to do is the minification of
-// inlined styles / scripts.
-//
-//
-
-var options = {
- // maintaining whitespace, removing html comments, extra quotes
- // removed, ...
- basics: {
- collapseWhitespace: false
- },
-
- // maintaining whitespace, retain html comments
- buildkit: {
- collapseWhitespace : false,
- removeComments : false,
- removeCommentsFromCDATA : false
- },
-
- compress: {
- removeComments : true,
- removeCommentsFromCDATA : true,
- removeEmptyAttributes : true,
- cleanAttributes : true,
- removeAttributeQuotes : true,
- removeRedundantAttributes : true,
- removeScriptTypeAttributes : true,
- removeStyleLinkTypeAttributes : true,
- collapseWhitespace : true,
- collapseBooleanAttributes : true,
- removeOptionalTags : true
- }
-};
-
-module.exports = function(grunt) {
-
- grunt.registerTask('html', 'Basic to aggresive html minification', function(type) {
- var config = grunt.config('html') || {};
- grunt.config.requires('html.files', 'staging');
-
- grunt.log.writeln('Run htmlcompressor on ' + grunt.log.wordlist(config.files));
-
- // default type
- type = type || config.type || 'compress';
-
- var valid = Object.keys( options ).indexOf( type ) !== -1;
-
- if ( !valid ) {
- return grunt.log.error( 'not a valid target: ' + type );
- }
-
- // merge default options for predefined type with the grunt's config
- // one.
- var defaults = options.compress;
- grunt.util._.defaults(options[type], defaults);
-
- grunt.log
- .write('>> ' + type + '... ')
- .subhead('Options:')
- .writeln(grunt.helper('inspect', options[type]));
-
- var files = grunt.file.expandFiles(config.files).map(function(file) {
- var body = grunt.file.read(file);
- return {
- file: file,
- body: body,
- minified: grunt.helper('html', body, options[type])
- };
- });
-
- // now write back to the disk each optimized html file
- files.forEach(function(file) {
- grunt.log.subhead(file.file);
- grunt.helper('min_max_info', file.minified, file.body);
- grunt.file.write(file.file, file.minified);
- });
- });
-
- //
- // **html** helper is a wrapper to html-minifier package, taking care of
- // html compression. See below for the full list of possible options. Options
- // may be setup using `grunt.config('html.options')` in your gruntfile.
- //
- grunt.registerHelper('html', function(body, opts) {
- opts = opts || {};
-
- // > http://perfectionkills.com/experimenting-with-html-minifier/#options
- grunt.util._.defaults(opts, grunt.config('html.options'), {
- removeComments: true,
- removeCommentsFromCDATA: true,
- removeEmptyAttributes: true,
- cleanAttributes: true,
- removeAttributeQuotes: true,
- removeRedundantAttributes: true,
- removeScriptTypeAttributes: true,
- removeStyleLinkTypeAttributes: true,
- collapseWhitespace: true,
- collapseBooleanAttributes: true,
- removeOptionalTags: true
- });
-
- return minifier.minify(body, opts);
- });
-
-};
-
View
148 cli/tasks/img.js
@@ -1,148 +0,0 @@
-
-var fs = require('fs'),
- path = require('path'),
- which = require('which');
-
-//
-// This task takes care of img optimizations by running a set of `.png`
-// or `.jpg` files through optipng and jpegtran.
-//
-// grunt img:<type>
-//
-// Gruntfile config:
-//
-// ...
-// img: {
-// src: ['img/**/*'],
-// options: {
-// ...
-// }
-// }
-//
-
-var win32 = process.platform === 'win32';
-
-module.exports = function(grunt) {
-
- var png = ['.png'],
- jpegs = ['.jpg', 'jpeg'];
-
- // rev task - reving is done in the `output/` directory
- grunt.registerMultiTask('img', 'Optimizes .png/.jpg images using optipng/jpegtran', function() {
- var cb = this.async(),
- files = grunt.file.expandFiles(this.file.src);
-
- var pngfiles = files.filter(function( file ) {
- return png.indexOf( path.extname( file ).toLowerCase() ) !== -1;
- });
-
- var jpgfiles = files.filter(function( file ) {
- return jpegs.indexOf( path.extname( file ).toLowerCase() ) !== -1;
- });
-
- grunt.helper('optipng', pngfiles, grunt.config('optipng'), function(err) {
- if(err) {
- grunt.log.error(err);
- return cb(false);
- }
-
- grunt.helper('jpegtran', jpgfiles, grunt.config('jpegtran'), function(err) {
- if(err) {
- grunt.log.error(err);
- return cb(false);
- }
- cb();
- });
- });
- });
-
- grunt.registerHelper('optipng', function(files, opts, cb) {
- opts = opts || {};
- cb = cb || function() {};
-
- which('optipng', function(err, cmdpath) {
- if ( err ) {
- return grunt.helper( 'not installed', 'optipng', cb );
- }
-
- var args = opts.args ? opts.args : [];
- args = args.concat(files);
-
- if ( !files.length ) {
- return cb();
- }
-
- grunt.log.writeln('Running optipng... ' + grunt.log.wordlist(files));
- var optipng = grunt.util.spawn({
- cmd: cmdpath,
- args: args
- }, function() {});
-
- optipng.stdout.pipe(process.stdout);
- optipng.stderr.pipe(process.stderr);
- optipng.on('exit', function(code) {
- if ( code ) {
- grunt.warn( 'optipng exited unexpectedly with exit code ' + code + '.', code );
- }
- cb();
- });
- });
- });
-
- grunt.registerHelper('jpegtran', function(files, opts, cb) {
- opts = opts || {};
- cb = cb || function() {};
- opts.args = opts.args ? opts.args : ['-copy', 'none', '-optimize', '-outfile', 'jpgtmp.jpg'];
-
- which('jpegtran', function(err, cmdpath) {
- if ( err ) {
- return grunt.helper( 'not installed', 'jpegtran', cb );
- }
-
- (function run(file) {
- if ( !file ) {
- return cb();
- }
-
- grunt.log.subhead('** Processing: ' + file);
- var jpegtran = grunt.util.spawn({
- cmd: cmdpath,
- args: opts.args.concat(file)
- }, function() {});
-
- jpegtran.stdout.pipe(process.stdout);
- jpegtran.stderr.pipe(process.stderr);
-
- jpegtran.on('exit', function(code) {
- if ( code ) {
- return grunt.warn( 'jpgtran exited unexpectedly with exit code ' + code + '.', code );
- }
- // output some size info about the file
- grunt.helper('min_max_stat', 'jpgtmp.jpg', file);
- // copy the temporary optimized jpg to original file
- fs.createReadStream('jpgtmp.jpg')
- .pipe(fs.createWriteStream(file)).on('close', function() {
- run(files.shift());
- });
- });
- }(files.shift()));
- });
-
- });
-
- grunt.registerHelper('not installed', function(cmd, cb) {
- grunt.verbose.or.writeln();
- grunt.log.write('Running ' + cmd + '...').error();
- grunt.log.errorlns([
- 'In order for this task to work properly, :cmd must be',
- 'installed and in the system PATH (if you can run ":cmd" at',
- 'the command line, this task should work)'
- ].join(' ').replace(/:cmd/g, cmd));
- grunt.log.subhead('Skiping ' + cmd + ' task');
-
- if ( cb ) {
- cb();
- }
- });
-};
-
View
53 cli/tasks/init/yeoman.js
@@ -1,53 +0,0 @@
-
-var fs = require('fs'),
- path = require('path'),
- colors = require('colors'),
- yeoman = require('../../'),
- grunt = require('grunt'),
- utils = yeoman.utils;
-
-// top level export
-var template = module.exports;
-
-// get back the resolved generator name to invoke
-var name = yeoman.generators.name;
-
-// and associated cli options (--help, --foo, ...)
-var opts = yeoman.generators.options;
-
-// strip back args from any `init:` prefix
-grunt.cli.tasks = grunt.cli.tasks.map(function(arg) {
- return arg.replace(/^init:/, '');
-});
-
-if(!name && !opts.help) {
- yeoman.generators.name = 'app';
-}
-
-// Basic template description.
-template.description = 'Init a new project or components';
-
-// warnOn, specifics to resolved generator. Any existing file or directory
-// matching this wildcard will cause a warning.
-//
-// Bypass on --help
-if(!opts.help) {
- template.warnOn = yeoman.generators.warnOn(grunt);
-}
-
-// Template-specific notes to be displayed before question prompts.
-template.notes = '\n'; //... More notes to come here ...'.yellow;
-
-// The actual grunt init template. We need to support:
-//
-// yeoman init
-// yeoman init backbone
-// yeoman init backbone:model modelName
-//
-// Handles the specific case of default generator on `init` (without generator
-// name).
-template.template = function _template(grunt, init, cb) {
-
- // delegate the groundwork of scaffolding to the generator layer
- return yeoman.generators.init(grunt);
-};
View
1,056 cli/tasks/livereload/livereload.js
@@ -1,1056 +0,0 @@
-// https://github.com/livereload/livereload-js/raw/master/dist/livereload.js
-(function() {
-var __customevents = {}, __protocol = {}, __connector = {}, __timer = {}, __options = {}, __reloader = {}, __livereload = {}, __less = {}, __startup = {};
-
-// customevents
-var CustomEvents;
-CustomEvents = {
- bind: function(element, eventName, handler) {
- if (element.addEventListener) {
- return element.addEventListener(eventName, handler, false);
- } else if (element.attachEvent) {
- element[eventName] = 1;
- return element.attachEvent('onpropertychange', function(event) {
- if (event.propertyName === eventName) {
- return handler();
- }
- });
- } else {
- throw new Error("Attempt to attach custom event " + eventName + " to something which isn't a DOMElement");
- }
- },
- fire: function(element, eventName) {
- var event;
- if (element.addEventListener) {
- event = document.createEvent('HTMLEvents');
- event.initEvent(eventName, true, true);
- return document.dispatchEvent(event);
- } else if (element.attachEvent) {
- if (element[eventName]) {
- return element[eventName]++;
- }
- } else {
- throw new Error("Attempt to fire custom event " + eventName + " on something which isn't a DOMElement");
- }
- }
-};
-__customevents.bind = CustomEvents.bind;
-__customevents.fire = CustomEvents.fire;
-
-// protocol
-var PROTOCOL_6, PROTOCOL_7, Parser, ProtocolError;
-var __indexOf = Array.prototype.indexOf || function(item) {
- for (var i = 0, l = this.length; i < l; i++) {
- if (this[i] === item) return i;
- }
- return -1;
-};
-__protocol.PROTOCOL_6 = PROTOCOL_6 = 'http://livereload.com/protocols/official-6';
-__protocol.PROTOCOL_7 = PROTOCOL_7 = 'http://livereload.com/protocols/official-7';
-__protocol.ProtocolError = ProtocolError = (function() {
- function ProtocolError(reason, data) {
- this.message = "LiveReload protocol error (" + reason + ") after receiving data: \"" + data + "\".";
- }
- return ProtocolError;
-})();
-__protocol.Parser = Parser = (function() {
- function Parser(handlers) {
- this.handlers = handlers;
- this.reset();
- }
- Parser.prototype.reset = function() {
- return this.protocol = null;
- };
- Parser.prototype.process = function(data) {
- var command, message, options, _ref;
- try {
- if (!(this.protocol != null)) {
- if (data.match(/^!!ver:([\d.]+)$/)) {
- this.protocol = 6;
- } else if (message = this._parseMessage(data, ['hello'])) {
- if (!message.protocols.length) {
- throw new ProtocolError("no protocols specified in handshake message");
- } else if (__indexOf.call(message.protocols, PROTOCOL_7) >= 0) {
- this.protocol = 7;
- } else if (__indexOf.call(message.protocols, PROTOCOL_6) >= 0) {
- this.protocol = 6;
- } else {
- throw new ProtocolError("no supported protocols found");
- }
- }
- return this.handlers.connected(this.protocol);
- } else if (this.protocol === 6) {
- message = JSON.parse(data);
- if (!message.length) {
- throw new ProtocolError("protocol 6 messages must be arrays");
- }
- command = message[0], options = message[1];
- if (command !== 'refresh') {
- throw new ProtocolError("unknown protocol 6 command");
- }
- return this.handlers.message({
- command: 'reload',
- path: options.path,
- liveCSS: (_ref = options.apply_css_live) != null ? _ref : true
- });
- } else {
- message = this._parseMessage(data, ['reload', 'alert']);
- return this.handlers.message(message);
- }
- } catch (e) {
- if (e instanceof ProtocolError) {
- return this.handlers.error(e);
- } else {
- throw e;
- }
- }
- };
- Parser.prototype._parseMessage = function(data, validCommands) {
- var message, _ref;
- try {
- message = JSON.parse(data);
- } catch (e) {
- throw new ProtocolError('unparsable JSON', data);
- }
- if (!message.command) {
- throw new ProtocolError('missing "command" key', data);
- }
- if (_ref = message.command, __indexOf.call(validCommands, _ref) < 0) {
- throw new ProtocolError("invalid command '" + message.command + "', only valid commands are: " + (validCommands.join(', ')) + ")", data);
- }
- return message;
- };
- return Parser;
-})();
-
-// connector
-// Generated by CoffeeScript 1.3.3
-var Connector, PROTOCOL_6, PROTOCOL_7, Parser, Version, _ref;
-
-_ref = __protocol, Parser = _ref.Parser, PROTOCOL_6 = _ref.PROTOCOL_6, PROTOCOL_7 = _ref.PROTOCOL_7;
-
-Version = '2.0.8';
-
-__connector.Connector = Connector = (function() {
-
- function Connector(options, WebSocket, Timer, handlers) {
- var _this = this;
- this.options = options;
- this.WebSocket = WebSocket;
- this.Timer = Timer;
- this.handlers = handlers;
- this._uri = "ws://" + this.options.host + ":" + this.options.port + "/livereload";
- this._nextDelay = this.options.mindelay;
- this._connectionDesired = false;
- this.protocol = 0;
- this.protocolParser = new Parser({
- connected: function(protocol) {
- _this.protocol = protocol;
- _this._handshakeTimeout.stop();
- _this._nextDelay = _this.options.mindelay;
- _this._disconnectionReason = 'broken';
- return _this.handlers.connected(protocol);
- },
- error: function(e) {
- _this.handlers.error(e);
- return _this._closeOnError();
- },
- message: function(message) {
- return _this.handlers.message(message);
- }
- });
- this._handshakeTimeout = new Timer(function() {
- if (!_this._isSocketConnected()) {
- return;
- }
- _this._disconnectionReason = 'handshake-timeout';
- return _this.socket.close();
- });
- this._reconnectTimer = new Timer(function() {
- if (!_this._connectionDesired) {
- return;
- }
- return _this.connect();
- });
- this.connect();
- }
-
- Connector.prototype._isSocketConnected = function() {
- return this.socket && this.socket.readyState === this.WebSocket.OPEN;
- };
-
- Connector.prototype.connect = function() {
- var _this = this;
- this._connectionDesired = true;
- if (this._isSocketConnected()) {
- return;
- }
- this._reconnectTimer.stop();
- this._disconnectionReason = 'cannot-connect';
- this.protocolParser.reset();
- this.handlers.connecting();
- this.socket = new this.WebSocket(this._uri);
- this.socket.onopen = function(e) {
- return _this._onopen(e);
- };
- this.socket.onclose = function(e) {
- return _this._onclose(e);
- };
- this.socket.onmessage = function(e) {
- return _this._onmessage(e);
- };
- return this.socket.onerror = function(e) {
- return _this._onerror(e);
- };
- };
-
- Connector.prototype.disconnect = function() {
- this._connectionDesired = false;
- this._reconnectTimer.stop();
- if (!this._isSocketConnected()) {
- return;
- }
- this._disconnectionReason = 'manual';
- return this.socket.close();
- };
-
- Connector.prototype._scheduleReconnection = function() {
- if (!this._connectionDesired) {
- return;
- }
- if (!this._reconnectTimer.running) {
- this._reconnectTimer.start(this._nextDelay);
- return this._nextDelay = Math.min(this.options.maxdelay, this._nextDelay * 2);
- }
- };
-
- Connector.prototype.sendCommand = function(command) {
- if (this.protocol == null) {
- return;
- }
- return this._sendCommand(command);
- };
-
- Connector.prototype._sendCommand = function(command) {
- return this.socket.send(JSON.stringify(command));
- };
-
- Connector.prototype._closeOnError = function() {
- this._handshakeTimeout.stop();
- this._disconnectionReason = 'error';
- return this.socket.close();
- };
-
- Connector.prototype._onopen = function(e) {
- var hello;
- this.handlers.socketConnected();
- this._disconnectionReason = 'handshake-failed';
- hello = {
- command: 'hello',
- protocols: [PROTOCOL_6, PROTOCOL_7]
- };
- hello.ver = Version;
- if (this.options.ext) {
- hello.ext = this.options.ext;
- }
- if (this.options.extver) {
- hello.extver = this.options.extver;
- }
- if (this.options.snipver) {
- hello.snipver = this.options.snipver;
- }
- this._sendCommand(hello);
- return this._handshakeTimeout.start(this.options.handshake_timeout);
- };
-
- Connector.prototype._onclose = function(e) {
- this.protocol = 0;
- this.handlers.disconnected(this._disconnectionReason, this._nextDelay);
- return this._scheduleReconnection();
- };
-
- Connector.prototype._onerror = function(e) {};
-
- Connector.prototype._onmessage = function(e) {
- return this.protocolParser.process(e.data);
- };
-
- return Connector;
-
-})();
-
-// timer
-var Timer;
-var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
-__timer.Timer = Timer = (function() {
- function Timer(func) {
- this.func = func;
- this.running = false;
- this.id = null;
- this._handler = __bind(function() {
- this.running = false;
- this.id = null;
- return this.func();
- }, this);
- }
- Timer.prototype.start = function(timeout) {
- if (this.running) {
- clearTimeout(this.id);
- }
- this.id = setTimeout(this._handler, timeout);
- return this.running = true;
- };
- Timer.prototype.stop = function() {
- if (this.running) {
- clearTimeout(this.id);
- this.running = false;
- return this.id = null;
- }
- };
- return Timer;
-})();
-Timer.start = function(timeout, func) {
- return setTimeout(func, timeout);
-};
-
-// options
-var Options;
-__options.Options = Options = (function() {
- function Options() {
- this.host = null;
- this.port = 35729;
- this.snipver = null;
- this.ext = null;
- this.extver = null;
- this.mindelay = 1000;
- this.maxdelay = 60000;
- this.handshake_timeout = 5000;
- }
- Options.prototype.set = function(name, value) {
- switch (typeof this[name]) {
- case 'undefined':
- break;
- case 'number':
- return this[name] = +value;
- default:
- return this[name] = value;
- }
- };
- return Options;
-})();
-Options.extract = function(document) {
- var element, keyAndValue, m, mm, options, pair, src, _i, _j, _len, _len2, _ref, _ref2;
- _ref = document.getElementsByTagName('script');
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- element = _ref[_i];
- if ((src = element.src) && (m = src.match(/^[^:]+:\/\/(.*)\/z?livereload\.js(?:\?(.*))?$/))) {
- options = new Options();
- if (mm = m[1].match(/^([^\/:]+)(?::(\d+))?$/)) {
- options.host = mm[1];
- if (mm[2]) {
- options.port = parseInt(mm[2], 10);
- }
- }
- if (m[2]) {
- _ref2 = m[2].split('&');
- for (_j = 0, _len2 = _ref2.length; _j < _len2; _j++) {
- pair = _ref2[_j];
- if ((keyAndValue = pair.split('=')).length > 1) {
- options.set(keyAndValue[0].replace(/-/g, '_'), keyAndValue.slice(1).join('='));
- }
- }
- }
- return options;
- }
- }
- return null;
-};
-
-// reloader
-// Generated by CoffeeScript 1.3.1
-(function() {
- var IMAGE_STYLES, Reloader, numberOfMatchingSegments, pathFromUrl, pathsMatch, pickBestMatch, splitUrl;
-
- splitUrl = function(url) {
- var hash, index, params;
- if ((index = url.indexOf('#')) >= 0) {
- hash = url.slice(index);
- url = url.slice(0, index);
- } else {
- hash = '';
- }
- if ((index = url.indexOf('?')) >= 0) {
- params = url.slice(index);
- url = url.slice(0, index);
- } else {
- params = '';
- }
- return {
- url: url,
- params: params,
- hash: hash
- };
- };
-
- pathFromUrl = function(url) {
- var path;
- url = splitUrl(url).url;
- if (url.indexOf('file://') === 0) {
- path = url.replace(/^file:\/\/(localhost)?/, '');
- } else {
- path = url.replace(/^([^:]+:)?\/\/([^:\/]+)(:\d*)?\//, '/');
- }
- return decodeURIComponent(path);
- };
-
- pickBestMatch = function(path, objects, pathFunc) {
- var bestMatch, object, score, _i, _len;
- bestMatch = {
- score: 0
- };
- for (_i = 0, _len = objects.length; _i < _len; _i++) {
- object = objects[_i];
- score = numberOfMatchingSegments(path, pathFunc(object));
- if (score > bestMatch.score) {
- bestMatch = {
- object: object,
- score: score
- };
- }
- }
- if (bestMatch.score > 0) {
- return bestMatch;
- } else {
- return null;
- }
- };
-
- numberOfMatchingSegments = function(path1, path2) {
- var comps1, comps2, eqCount, len;
- path1 = path1.replace(/^\/+/, '').toLowerCase();
- path2 = path2.replace(/^\/+/, '').toLowerCase();
- if (path1 === path2) {
- return 10000;
- }
- comps1 = path1.split('/').reverse();
- comps2 = path2.split('/').reverse();
- len = Math.min(comps1.length, comps2.length);
- eqCount = 0;
- while (eqCount < len && comps1[eqCount] === comps2[eqCount]) {
- ++eqCount;
- }
- return eqCount;
- };
-
- pathsMatch = function(path1, path2) {
- return numberOfMatchingSegments(path1, path2) > 0;
- };
-
- IMAGE_STYLES = [
- {
- selector: 'background',
- styleNames: ['backgroundImage']
- }, {
- selector: 'border',
- styleNames: ['borderImage', 'webkitBorderImage', 'MozBorderImage