exports.jscs = function(args) {
	var Checker = require('jscs');
	var checker = new Checker();

	checker.registerDefaultRules();
	checker.configure(JSON.parse(fs.readFileSync(args.configFile)));
	checker.checkPath(args.src).then(function(results) {
		var errorsCollection = [].concat.apply([], results);
		var count = 0;

		errorsCollection.forEach(function(errors) {
			if (!errors.isEmpty()) {
				errors.getErrorList().forEach(function(error) {
					console.log(errors.explainError(error, true) + '\n');
					count++;
				});
			}
		});

		if (count > 0) {
			console.log("jscs errors found: " + count);
			process.exit(1);
		}

		if (args.oncomplete) {
			args.oncomplete();
		}
	});
};
Beispiel #2
0
var checkSource = function (source, config) {
  // Copy options to own object.
  var options = this.options.jscs;
  extend(config, options);

  // Copy query to own object.
  var query = utils.getOptions(this) || {};
  extend(config, query);

  // Move flags.
  var emitErrors = config.emitErrors;
  delete config.emitErrors;
  var failOnHint = config.failOnHint;
  delete config.failOnHint;

  // Custom reporter.
  var reporter = config.reporter;
  delete config.reporter;

  var checker = new Checker();
  checker.registerDefaultRules();
  checker.configure(config);

  var result = checker.checkString(source);

  if (!result.isEmpty()) {
    if (reporter) {
      reporter.call(this, result);
    }
    else {
      var message = result.getErrorList().map(function (error) {
        return '  ' + error.rule +
          ' @ line ' + error.line +
          ' char ' + error.column +
          '\n    ' + error.message;
      }).join('\n\n');

      var emitter = emitErrors ? this.emitError : this.emitWarning;
      if (emitter) {
        emitter('jscs results in errors\n' + message);
      }
      else {
        throw new Error('Your module system doesn\'t support emitWarning.' +
          ' Update available? \n' + message);
      }
    }

    if (failOnHint) {
      throw new Error('Module failed in cause of jscs error.');
    }
  }
};
Beispiel #3
0
module.exports = function (options) {
	var out = [];
	var checker = new Checker();

	checker.registerDefaultRules();

	if (typeof options === 'object') {
		checker.configure(options);
	} else {
		checker.configure(loadConfigFile.load(options));
	}

	return through.obj(function (file, enc, cb) {
		if (file.isNull()) {
			cb(null, file);
			return;
		}

		if (file.isStream()) {
			cb(new gutil.PluginError('gulp-jscs', 'Streaming not supported'));
			return;
		}

		if (checker._isExcluded(file.path)) {
			cb(null, file);
			return;
		}

		try {
			var errors = checker.checkString(file.contents.toString(), file.relative);
			errors.getErrorList().forEach(function (err) {
				out.push(errors.explainError(err, true));
			});
		} catch (err) {
			out.push(err.message.replace('null:', file.relative + ':'));
		}

		cb(null, file);
	}, function (cb) {
		if (out.length > 0) {
			this.emit('error', new gutil.PluginError('gulp-jscs', out.join('\n\n'), {
				showStack: false
			}));
		}

		cb();
	});
};
Beispiel #4
0
module.exports = function (options, reporter) {
	var errorCollection = [];
	var checker = new Checker({esnext: options && !!options.esnext});

	checker.registerDefaultRules();

	if (typeof options === 'object') {
		delete options.esnext;
		checker.configure(options);
	} else {
		checker.configure(loadConfigFile.load(options));
	}

	return through.obj(function (file, enc, cb) {
		if (file.isNull()) {
			cb(null, file);
			return;
		}

		if (file.isStream()) {
			cb(new gutil.PluginError('gulp-jscs', 'Streaming not supported'));
			return;
		}

		if (checker._isExcluded(file.path)) {
			cb(null, file);
			return;
		}

		try {
			var errors = checker.checkString(file.contents.toString(), file.relative);
			if (errors.getErrorCount() > 0) {
				errors.filePath = file.path;
				errorCollection.push(errors);
			}
		} catch (err) {
			console.error(err.message.replace('null:', file.relative + ':'));
		}

		cb(null, file);
	}, function (cb) {
		getReporter(reporter).call(this, errorCollection);

		cb();
	});
};
function analyze (fileSourceData) {
    var analysis = new Analysis(),
        jscs = new Jscs();

    jscs.registerDefaultRules();

    jscs.configure(configuration);

    jscs.checkString(fileSourceData.text)
        .getErrorList()
        .forEach(error => {
            analysis.addError({ 
                line: (error.line + fileSourceData.lineStart) - 1, 
                message: error.message 
            });
        });

    return analysis;
}
Beispiel #6
0
  static fixString(editor) {
    const editorPath = editor.getPath();
    const editorText = editor.getText();

    const config = this.getConfig(editorPath);
    if (!config && this.onlyConfig) {
      return;
    }

    const JSCS = require('jscs');

    // We need re-initialize JSCS before every lint
    // or it will looses the errors, didn't trace the error
    // must be something with new 2.0.0 JSCS
    this.jscs = new JSCS();
    this.jscs.registerDefaultRules();

    const filePath = editor.getPath();

    // Options passed to `jscs` from package configuration
    const options = { esnext: this.esnext };
    if (this.preset !== '<none>') {
      options.preset = this.preset;
    }

    // `configPath` is non-enumerable so `Object.assign` won't copy it.
    // Without a proper `configPath` JSCS plugs cannot be loaded. See #175.
    let jscsConfig = Object.assign({}, options, config);
    if (!jscsConfig.configPath && config) {
      jscsConfig.configPath = config.configPath;
    }

    this.jscs.configure(jscsConfig);

    const fixedText = this.jscs.fixString(editorText, editorPath).output;
    if (editorText === fixedText) {
      return;
    }

    const cursorPosition = editor.getCursorScreenPosition();
    editor.setText(fixedText);
    editor.setCursorScreenPosition(cursorPosition);
  }
Beispiel #7
0
function initChecker() {
  var checker = new Checker();
  checker.registerDefaultRules();

  // Configure the checker with an options object
  checker.configure({
    "requireCurlyBraces": [
      "if",
      "else",
      "for"
    ]
  });

  // Use the Google preset, but override or remove some options
  checker.configure({
    preset: "google",
    disallowMultipleLineBreaks: null, // or false
    validateIndentation: "\t"
  });
  return checker;
}
Beispiel #8
0
module.exports = function (options, f) {
  options = _.extend({
    args: [],
    color: true,
    config: null,
    esnext: false
  }, options);

  var args = grunt.file.expand(options.args);
  var checker = new Checker(options);
  var config;
  var configPath = options.config;
  var hasColors = options.color && process.stdout && process.stdout.isTTY;
  var reporter;
  var reporterPath = 'jscs/lib/reporters/' + (hasColors ? 'console' : 'text');

  config = configFile.load(configPath);

  if (!config) {
    config = configFile.load(path.join(__dirname, '../../defaults/.jscsrc'));
  }

  if (!config) {
    return f(new Error('Configuration source ' + configPath + ' was not found.'));
  }

  if (options.maxErrors) {
    config.maxErrors = Number(options.maxErrors);
  }

  if (options.reporter) {
    reporterPath = path.resolve(process.cwd(), options.reporter);

    if (!fs.existsSync(reporterPath)) {
      reporterPath = 'jscs/lib/reporters/' + options.reporter;
    }
  }

  try {
    reporter = require(reporterPath);
  } catch (e) {
    return f(new Error('Reporter ' + reporterPath + 'doesn\'t exist.'));
  }

  checker.registerDefaultRules();
  checker.configure(config);

  bluebird.all(args.map(checker.checkPath, checker)).then(function(results) {
    var errorsCollection = [].concat.apply([], results);

    reporter(errorsCollection);

    var hasErrors = errorsCollection.some(function(errors) {
      return !errors.isEmpty();
    });

    if (hasErrors) {
      return f(new Error('Found issues with code style'));
    }

    return f();
  }, f);
};
'use strict';
import path from 'path';
import fs from 'fs';
import _ from 'lodash';
import Promise from 'bluebird';
import helpers from 'yeoman-test';
import assert from 'yeoman-assert';
import minimatch from 'minimatch';
import Checker from 'jscs';
const jscs = new Checker();
jscs.registerDefaultRules();
import * as getExpectedFiles from './get-expected-files';
import {
  copyAsync,
  runCmd,
  assertOnlyFiles,
  readJSON,
  runGen
} from './test-helpers';

const TEST_DIR = __dirname;

const defaultOptions = {
  buildtool: 'grunt',
  script: 'js',
  transpiler: 'babel',
  markup: 'html',
  stylesheet: 'sass',
  router: 'uirouter',
  testing: 'mocha',
  chai: 'expect',
Beispiel #10
0
module.exports = function (options) {
	options = options || '.jscsrc';

	if (typeof options === 'string') {
		options = {configPath: options};
	}

	options = assign({esnext: false}, options);

	var out = [];
	var checker = new Checker({esnext: !!options.esnext});

	checker.registerDefaultRules();

	var configPath = options.configPath;
	delete options.esnext;
	delete options.configPath;

	if (configPath) {
		if (typeof options === 'object' && Object.keys(options).length) {
			throw new Error('configPath option is not compatible with code style options');
		}

		try {
			checker.configure(loadConfigFile.load(configPath));
		} catch (error) {
			throw new Error('Unable to load JSCS config file at ' + path.join(process.cwd(), configPath));
		}
	} else {
		checker.configure(options);
	}

	return through.obj(function (file, enc, cb) {
		if (file.isNull()) {
			cb(null, file);
			return;
		}

		if (file.isStream()) {
			cb(new gutil.PluginError('gulp-jscs', 'Streaming not supported'));
			return;
		}

		if (checker.getConfiguration().isFileExcluded(file.path)) {
			cb(null, file);
			return;
		}

		try {
			var errors = checker.checkString(file.contents.toString(), file.relative);
			var errorList = errors.getErrorList();

			file.jscs = {
				success: true,
				errorCount: 0,
				errors: []
			};

			if (errorList.length > 0) {
				file.jscs.success = false;
				file.jscs.errorCount = errorList.length;
				file.jscs.errors = errorList;
			}

			errorList.forEach(function (err) {
				out.push(errors.explainError(err, true));
			});
		} catch (err) {
			out.push(err.stack.replace('null:', file.relative + ':'));
		}

		cb(null, file);
	}, function (cb) {
		if (out.length > 0) {
			this.emit('error', new gutil.PluginError('gulp-jscs', out.join('\n\n'), {
				showStack: false
			}));
		}

		cb();
	});
};
Beispiel #11
0
module.exports = function (settings) {
	var scriptTypes = [
			'js',
			'css',
			'less',
			'dust',
			'json'
		],
		jscs = new Jscs();

	// JSCS config
	jscs.registerDefaultRules();
	if (settings.config && settings.config.jscsRules) {
		jscs.configure(jscsConfig.load(path.join(__dirname, settings.config.jscsRules)));
	}

	var File = function (filepath, params) {
		this.path = filepath;
		this.basename = path.basename(filepath);
		this.extname = path.extname(filepath);

		this.params = extend({
			lint: false,
			jscs: false,
			dust: false,
			ie: false,
			test: false,
			testDeploy: false,
			binary: false,
			vendor: false,
			deploy: true
		}, params);

		this.applyParams();
		this.process();
	};

	File.prototype.applyParams = function () {
		//различные проверки
		var relativePath = this.path.split(path.resolve(settings.source))[1] || this.path,
			isIE = (/\.ie\./i).test(this.basename),
			isTest = (/(\/|\\)test(\/|\\)/i).test(relativePath),
			isVendor = (/(\/|\\)vendor(\/|\\)/i).test(relativePath);

		//файл для версии под ИЕ
		this.params.ie = isIE;

		//файл для тестов
		this.params.test = isTest;

		//"чужой" файл – библиотека, плагин, фреймворк или типа того
		this.params.vendor = isVendor;

		this.params.type = this.extname.split('.')[1];

		if (this.params.type === 'dust') {
			//если это dust-шаблон
			this.params.dust = this.params.dust || true;
		}

		if (this.params.type === 'js' && !this.params.vendor && !this.params.test) {
			//если это свой js-файл – то его надо будет проверить
			this.params.lint = true;
			this.params.jscs = true;
		}

		if (scriptTypes.indexOf(this.params.type) < 0) {
			//если файл не подпадает под "скриптовые" типы – считаем его бинарным
			//и далее тупо копируем
			this.params.binary = true;
		}

		if (this.params.type === 'md' || (this.params.test && !this.params.testDeploy) || this.params.type === 'json') {
			this.params.deploy = false;
		}
	};

	/**
	 * Check file with JSLint and get array of error information objects
	 * @param content file content
	 * @param filename file name
	 * @returns {Array} error information
	 */
	function jsLintFile(content, filename) {
		var result,
			jshintResults = [];

		result = jshint(content, {
			"undef": true,
			"unused": true,
			"plusplus": true,
			"predef": {
				"window": false,
				"jQuery": false,
				"dust": false,
				"extend": false
			}
		});

		if (!result) {
			jshintResults = jshintResults.concat(jshint.errors.map(function (error) {
				if (error) {
					error.file = error.file || filename;
					//error.line -= 1;

					return error;
				}
			}));
		}

		return jshintResults;
	}

	/**
	 * Check file with JSCS and get array of error information objects
	 * @param content file content
	 * @param filename file name
	 * @returns {Array} error information
	 */
	function jscsFile(content, filename) {
		var result = [];

		try {
			jscs.checkString(content, filename).getErrorList().forEach(function (err) {
				err.file = filename;
				result.push({
					line: err.line,
					character: err.column,
					reason: err.message,
					file: filename
				});
			});
		} catch (err) {
			result.push(err.message.replace('null:', filename + ':'));
		}

		return result;
	}

	File.prototype.processors = {
		'js': function () {
			if (this.params.lint) {
				this.errors = jsLintFile(this.content, this.path);
			}

			if (this.params.jscs) {
				this.csErrors = jscsFile(this.content, this.path);
			}

			return this.content;
		},
		'css': function () {
			if (!this.params.vendor) {
				return autoprefixer(settings.config.autoprefixerOptions).process(this.content);
			}

			return this.content;
		},
		'less': function () {
			var file = this,
				syncReady = false,
				parser = new (less.Parser)({
					syncImport: true,
					paths: [ // указывает пути поиска для директив @import
						this.path,
						path.resolve(settings.source, 'apps', this.params.app, 'css'),
						path.resolve(settings.source, 'apps', 'common', 'css'),
						path.resolve(settings.source, 'modules')
					],
					filename: this.path // указывает имя файла, для улучшения сообщений об ошибках
				});

			parser.parse(this.content, function (e, tree) {
				syncReady = true;

				file.content = tree.toCSS();
			});

			if (!syncReady) {
				throw new Error('Can`t synchronous render less file!');
			}
			this.params.type = 'css';
			this.content = this.processors[this.params.type].call(this);

			return this.content;
		},
		'dust': function () {
			var file = this,
				name = path.join(this.params.parent || '', this.params.path.replace(/^templates(\/|\\|$)/, ''), path.basename(this.basename, '.dust')),
				template,
				moduleRx = /\{@my([^\}]*)\}/g,
				moduleNameRx = /module="([^"]*)"/,
				BOMcheck = /^\uFEFF/,
				modules;

			if (this.content.match(BOMcheck)) {
				this.errors = [
					{
						reason: 'BOM mark detected!',
						file: this.path,
						line: 1,
						character: 1
					}
				];

				this.content = this.content.replace(BOMcheck, '');
			}

			name = name.replace(/\\/g, '/');

			this.modules = [];

			// проверяем, подключаются ли в шаблоне модули
			modules = this.content.match(moduleRx);

			if (modules) {
				// если подключаются, находим их названия
				modules.forEach(function (module) {
					module = module.match(moduleNameRx)[1];

					if (module && file.modules.indexOf(module) === -1) {
						file.modules.push(module);
					}
				});
			}

			try {
				template = dust.compile(this.content, name);
				dust.loadSource(template);
			} catch (e) {
				sys.log('Dust syntax error\n\tFile: ' + this.path);
				sys.puts('\t' + e.message);
				throw e;
			}

			this.params.type = 'js';

			return template;
		}
	};

	File.prototype.process = function () {
		if (this.params.deploy) {
			//onlyBinaries нужна, чтобы можно было скопировать
			//бинарники уже ранее обработанного модуля
			//и не читать заново другие файлы
			if (!this.params.onlyBinaries || this.params.binary) {
				this.content = fs.readFileSync(this.path, this.params.binary ? null : {encoding: 'utf8'});

				//если нужно как-то обработать контент файла – делаем это
				if (this.processors[this.params.type]) {
					this.content = this.processors[this.params.type].call(this);
				}
			}
		}
	};

	return File;
};