Giter VIP home page Giter VIP logo

dsheiko / jscodesniffer Goto Github PK

View Code? Open in Web Editor NEW
42.0 11.0 8.0 1.2 MB

⛔️ [DEPRECATED] Tool to ensure that your JavaScript code does not violate the specified coding standard (Idiomatic Style Manifesto or JQuery Core Style Guidelines)

Home Page: http://dsheiko.github.io/jscodesniffer/

JavaScript 26.93% HTML 72.33% CSS 0.60% Shell 0.14%
code-sniffer static-analyzer linter naming-conventions idiomatic-js jquery-coding-style standard deprecated obsolete

jscodesniffer's Introduction

JSCodeSniffer v.2.x

No Maintenance Intended

WARNING - THIS PROJECT IS NO LONGER MAINTAINED!!!

NPM

Build Status Bower version Gitter

JSCodeSniffer is a node.js application that checks JavaScript code style consistency according to a provided coding style, just like phpcs. One can define a custom coding style by using described below JSON notation or use one of predefined standards.

Features

Install

You have at least three installation options:

Download or clone the Git repository

git clone https://github.com/dsheiko/jscodesniffer.git

Install by using Node.js Package Manager

sudo npm  install jscodesniffer -g

Install by using Bower.io Package Manager

bower install --save jscodesniffer

Using JSCodeSniffer in the command line

Simply get detailed report on a target (file or directory) coding style according to jQuery Coding Style Guide

./jscs source-code.js --standard=Jquery  --report-full

or

node jscs.js source-code.js  --standard=Jquery  --report-full

or

./jscs js/dir1 file1.js js/dir2 file2.js --standard=Jquery  --report-full

JS CodeSniffer Full Report Example

Get detailed report on the coding style for all .js/.json files of the 'lib' folder according to jQuery Coding Style Guide

./jscs lib --standard=Jquery --report-full

Get summary report

./jscs lib --report-summary

JS CodeSniffer Summary Report Example

Get XML report (which allows you to parse the output easily and use the results in your own scripts)

./jscs lib --report=xml

Get Checkstyle report (that is supported by wide range of 3rd party software. E.g. Jenkins via a plugin)

./jscs lib --report=checkstyle

Report to a file (by default report goes to stdout)

./jscs lib --report-file=filePath

Disable colors in the report

./jscs lib --highlight=0

Define width of report screen

./jscs lib --reportWidth=84

Using JSCodeSniffer as RequireJS (AMD) module

  1. Install the package or download and unpack it into you project folder
 npm i jscodesniffer
  1. Use RequireJS to load required modules
require( [ "<esprima-js-path>/esprima", "<pkg-path>/lib/Sniffer", "<pkg-path>/lib/Dictionary/en", "<pkg-path>/lib/Dictionary" ], function( esprima, Sniffer, en, Dictionary ) {
  var sniffer = new Sniffer( esprima ),
      dictionary = new Dictionary( en ),
      logger, messages;

    // Get sniffer report
    logger = sniffer.getTestResults( node.srcCode.value, { standard: "Jquery" } ),
    // Translate messages
    messages = dictionary.translateBulk( logger.getMessages(), true );
    // Output report
    console.log( messages );
});

Environments

Standard to sniff against can be enforced on the file by following instructions directly in the code

/* jscs standard:Jquery */

Old form introduced in version 1.x.x is also supported

/* @jscs standard:Jquery */

Real-Time Configuration

Adjusting options can be provided as manual standard in .jscsrc file placed in the root of your project. JSCodesniffer will search upward recursively until it finds any. It will extend the specified standard rule-sets with the defenitions provided in this real-time configuration file. .jscsrc syntax is pretty much the same as standard defenition file except it doesn't need to be UMD (just JSON). I you need disable particular rule-sets you can simply empty rule-set configurations:

{
  "Indentation": false,
  "QuoteConventions": false
}

.jscsignore

Specifies files to ignore in the same format as .gitignore

With .jscsignore in project root directory:

standard/**/*.js

The code sniffer produces following output:

 node jscs.js ./standard --standard=Jquery
 * `standard/Idiomatic.js` ignored in concordance with .jscsignore
 * `standard/Jquery.js` ignored in concordance with .jscsignore
 JsCodeSniffer 2.1.15 (https://github.com/dsheiko/jscodesniffer)

Declaring coding style

Standard declaration are located in standard directory. You can store there in a file named after your custom standard name the rule-sets that you want your code be validated against. To make the defenition available for AMD/RequireJs, the JSON notation is supposed to be wrapped as a UMD module.

NOTE: Conventions 'Any ; used as a statement terminator must be at the end of the line' and 'Multi-line Statements is checked' are tested by JSHint and therefore not provided with sniffs (See [http://contribute.jquery.org/style-guide/js/#linting] for details).

{
  /*
    defines what characters allowed for line indentation
  */
    "Indentation": {
      "allowOnlyTabs": true,
      "allowOnlySpaces": true,
      "disallowMixed": true,
      "ignoreBlockComments": true
    },
  /*
    defines if trailing spaces allowed for lines
  */
    "LineSpacing": {
      "allowLineTrailingSpaces": false
    },
  /*
    defines allowed range for line length
  */
    "LineLength": {
      "allowMaxLength": 80,
      "allowMinLength": 0
    },
  /*
    defines spacing conventions for comma punctuator
    Example:
    // good
    var foo, bar;
    // bad
    var foo , bar;
  */
    "CommaPunctuatorSpacing": {
      "disallowPrecedingSpaces": false
    },
  /*
    defines spacing conventions for semicolon punctuator
    Example:
    // good
    var foo;
    // bad
    var foo ;
  */
    "SemicolonPunctuatorSpacing": {
      "disallowPrecedingSpaces": false
    },

  /*
    defines scoping rules for compound statements

    Example:
    // good
    if ( true ) {
      var foo = "bar";
    }
    // bad
    if ( true ) var foo = "bar";

    All the constrains are optional.
    if ( true )__{..}, for (..)__{..} - opening brace preceding whitespace
    if ( true ) {__..}, for (..){__..} - opening brace trailing whitespace
    if ( true ) {..__}, for (..){..__} - closing brace preceding whitespace
  */
    "CompoundStatementConventions": {
      "for": [
        "IfStatement",
        "SwitchStatement",
        "WhileStatement",
        "DoWhileStatement",
        "ForStatement",
        "ForInStatement",
        "WithStatement",
        "TryStatement"
      ],
      "requireBraces": true,
      "requireMultipleLines": true,
      "allowOpeningBracePrecedingWhitespaces": 1,
      "allowOpeningBraceTrailingWhitespaces": 1,
      "requireOpeningBracePrecedingNewLine": true,
      "requireOpeningBraceTrailingNewLine": true,
      "allowClosingBracePrecedingWhitespaces": 1,
      "requireClosingBracePrecedingNewLine": true
    },
    /*
    defines spacing conventions for unary expressions

    Example:
    !!100 // good
    !! 100 // bad
    */
    "UnaryExpressionIdentifierSpacing": {
      "allowTrailingWhitespaces" : 0
    },
    /*
    defines spacing conventions for ternary conditionals

    Example:
    foo = true ? 1 : 0; // good
    foo = true ?1:0; // bad
    */
    "TernaryConditionalPunctuatorsSpacing": {
      "allowTestTrailingWhitespaces": 1,
      "allowConsequentPrecedingWhitespaces": 1,
      "allowConsequentTrailingWhitespaces": 1,
      "allowAlternatePrecedingWhitespaces": 1,
       /*
        Optional modifier.
        When undefined the sniffer treats nesting statements the same
            as regular
        When false, no rules applied for nesting statements
        When defined, the corresponding rules go for nesting statements
        foo( a?b:c )
        */
      "ifNesting": {
        "allowTestTrailingWhitespaces": 0,
        "allowConsequentPrecedingWhitespaces": 0,
        "allowConsequentTrailingWhitespaces": 0,
        "allowAlternatePrecedingWhitespaces": 0
      }
    },
    /*
    defines spacing conventions for empty constructs
    "for" qualifier takes an array of tokens compatible with
    Mozilla Parser AST (https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API)

    Example:
    obj = {}; // good
    obj = {  }; // bad
    */
    "EmptyConstructsSpacing": {
      "for": [
        "ObjectExpression",
        "ArrayExpression",
        "CallExpression"
      ],
      "allowWhitespaces": false
    },
   /*
    defines spacing conventions for object literals

    Example:
    obj = { prop: 1 }; // good
    obj = { prop:1 };// bad
    */
    "ObjectLiteralSpacing": {
      "allowKeyPrecedingWhitespaces": 1,
      "allowKeyTrailingWhitespaces": 0,
      "allowValuePrecedingWhitespaces": 1,
      "allowValueTrailingWhitespaces": 1
    },
   /*
    defines spacing conventions for array literals

    Example:
    arr = [ 1, 2 ]; // good
    arr = [1,2]; // bad
    */
    "ArrayLiteralSpacing": {
      "allowElementPrecedingWhitespaces": 1,
      "allowElementTrailingWhitespaces": 1,
      /*
      Optional modifier.
      "for" qualifier takes an array of tokens compatible with
      Mozilla Parser AST (https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API)
      When qualifier "for" is missing the exception rules gets applied for any node type
      */
      "exceptions": {
        "singleElement": {
          "for": [ "Literal" ],
          "allowElementPrecedingWhitespaces": 0,
          "allowElementTrailingWhitespaces": 0
        },
        "firstElement": {
          "for": [ "Literal" ],
          "allowElementPrecedingWhitespaces": 1
        },
        "lastElement": {
          "for": [ "Literal" ],
          "allowElementTrailingWhitespaces": 1
        }
      }
    },
   /*
    defines type of quotes to use across the code-base

    Example:
    foo = "text"; // good
    foo = 'text'; // bad
    */
    "QuoteConventions": {
      "allowDoubleQuotes": true,
      "allowSingleQuotes": false
    },
    /*
    defines naming conventions for variables
    Note: variable of all uppercase (including $_0-9) are considered as constants and ignored by the sniffer

    Example:
    var camelCase; // good
    var not_camel_case; // bad
    */
    "VariableNamingConventions": {
      "allowCase": ["camel"],
      "allowRepeating": true,
      "allowNumbers": true
    },
   /*
    defines naming conventions for functions

    Example:
    var PascalCase; // good
    var not_camel_or_pascal_case; // bad
    */
    "FunctionNamingConventions": {
      "allowCase": ["camel", "pascal"],
      "allowRepeating": true,
      "allowNumbers": true
    },
    /*
    defines naming conventions for new expressions

    Example:
    obj = new Constructor(); // good
    obj = new constructor(); // bad
    */
    "NewExpressionCalleeNamingConventions": {
      "allowCase": [ "pascal" ],
      "allowRepeating": true,
      "allowNumbers": true
    },

   /*
    defines spacing conventions for arguments

    Example:
    fn( 1, 2 ); // good
    fn(1,2); // bad
    */
    "ArgumentsSpacing": {
      "allowArgPrecedingWhitespaces": 1,
      "allowArgTrailingWhitespaces": 1,
      /*
        Optional modifier.
       "for" qualifier takes an array of tokens compatible with
        Mozilla Parser AST (https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API)
        When qualifier "for" is missing the exception rules gets applied for any node type
      */
      "exceptions": {
        "singleArg" : {
          "for": [ "FunctionExpression", "ArrayExpression", "ObjectExpression" ],
          "allowArgPrecedingWhitespaces": 0,
          "allowArgTrailingWhitespaces": 0
        },
        "firstArg": {
          "for": [ "FunctionExpression" ],
          "allowArgPrecedingWhitespaces": 0
        },
        "lastArg": {
          "for": [ "FunctionExpression" ],
          "allowArgTrailingWhitespaces": 0
        }
      },
      /*
        Optional modifier.
        When undefined the sniffer treats nesting statements the same
            as regular
        When false, no rules applied for nesting statements
        When defined, the corresponding rules go for nesting statements
        foo( bar(1,1) )
        */
      "ifNesting": {
        "allowArgPrecedingWhitespaces": 0,
        "allowArgTrailingWhitespaces": 0
      }
    },
  /*
    defines spacing conventions for parameters

    Example:
    function fn( foo, bar ){}; // good
    function fn(foo,bar){}; // bad
    */
    "ParametersSpacing": {
      "allowParamPrecedingWhitespaces": 1,
      "allowParamTrailingWhitespaces": 1,
      "exceptions": {
        "singleParam": {
          "for": [ "Identifier" ],
          "allowParamPrecedingWhitespaces": 0,
          "allowParamTrailingWhitespaces": 0
        },
        "firstParam": {
          "for": [ "Identifier" ],
          "allowParamPrecedingWhitespaces": 1,
          "allowParamTrailingWhitespaces": 0
        },
        "lastParam": {
          "for": [ "Identifier" ],
          "allowParamPrecedingWhitespaces": 1
          "allowParamTrailingWhitespaces": 0
        }
      }
    },
    /*
    defines how methods can be placed when a chain of method calls is too long to fit on one line

    Example:
    // good
    elements
    .addClass( "foo" )
    .children();

    // bad
    elements.addClass( "foo" )
    .children();
    */

    "ChainedMethodCallsPerLineConventions": {
      "requireOnePerLineWhenMultilineCaller": true
    },
    /*
    defines spacing conventions for chains of method calls
    Example:
    // good
    elements.addClass( "foo" )

    // bad
    elements.  addClass( "foo" )
    */
    "ChainedMethodCallsSpacing": {
      "allowPrecedingPropertyWhitespaces": 0
    },
    /*
    defines spacing conventions for operators (including declarator)

    Example:
    foo = 1 + 1; // good
    foo = 1+1; // bad
    */
    "OperatorSpacing" : {
      "allowOperatorPrecedingWhitespaces": 1,
      "allowOperatorTrailingWhitespaces": 1
    },
    /*
    defines conventions for variable declarations

    Example:
    // good
    (function(){
      var foo, bar;
    })();

    // bad
    (function(){
      var foo;
      var bar;
    })();
    */
    "VariableDeclarationPerScopeConventions" : {
      "disallowMultiplePerBlockScope": true,
      "requireInTheBeginning": true
    },
    /*
    defines conventions for object declarations

    Example:
    // good
    o = { p1: 1, p2: 2 }
    // good
    o = {
      p1: 1,
      p2: 2
    }
    // bad
    o = {
      p1: 1, p2: 2 }
     */
    "ObjectLiteralConventions": {
      "requireOnePerLineWhenMultiline": true
    },
    /*
    defines conventions for array declarations

    Example:
    // good
    arr = [ 1, "two" ]
    // good
    arr = [
      1,
      "two"
    ]
    // bad
    arr = [
      1, "two" ]
    */
    "ArrayLiteralConventions": {
      "requireOnePerLineWhenMultiline": true
    }
  }

JSCodeSniffer and Continuous Integration

Setting up Apache Ant build script reporting to Jenkins Checkstyle plugin.

NOTE: If you have phpcs-ci ant target, invoke it prior to this one. Jscs will find created by phpcs checkstyle.xml and extend its body instead of overriding the report.

<target name="jscs-ci"
         description="Find coding standard violations using JS_CodeSniffer and print human readable output.">
  <exec executable="jscs">
   <arg value="--standard=Jquery" />
   <arg value="--report=checkstyle" />
   <arg value="--report-file=${basedir}/build/logs/checkstyle.xml" />
   <arg path="${basedir}/src" />
  </exec>
 </target>

Setting up Grunt task

Gruntfile.js

grunt.loadNpmTasks('grunt-jscodesniffer');
grunt.initConfig({
     // Validate against jQuery coding standard
     jscs: {
        options: {
            "standard": "Jquery"
        },
        all: ["js-folder"]
     }
  });

package.json

"devDependencies": {
    //..
    "grunt-jscodesniffer": "*"
  }

Using the Subversion pre-commit hook

A pre-commit hook is a feature available in the Subversion version control system that allows code to be validated before it is committed to the repository. Edit scripts/jscs-svn-pre-commit and replace JSCS value with your own path to JS CodeSniffer

JSCS = "/your-path/jscodesniffer"

Make a symlink of scripts/jscs-svn-pre-commit in your repository hooks folder. E.g.

ln -s /<full path>/scripts/jscs-svn-pre-commit /repositories/<project>/hooks/pre-commit

Using the git pre-commit hook

Make a symlink of scripts/jscs-git-pre-commit in your repository .git/hooks folder. E.g.

ln -s /<full path>/scripts/jscs-git-pre-commit /<project>/.git/hooks/pre-commit

API Notes

High-level interface example (the report in stdout):

var argv = [ "node", "jscs", "./source-dir/", "--standard=Jquery", "--report-full" ],
		jscodesniffer = require( "jscodesniffer" );

jscodesniffer( argv, process.cwd() );

Low-level one example:

var Sniffer = require( "./lib/Sniffer" ),
		sniffer = new Sniffer(),
		src = "var a= 1;",
		options = {
			standard: "Jquery"
		},
		logger = sniffer.getTestResults( src, options, {} );

console.log(logger.getMessages());

/*
  [ { sniff: 'OperatorSpacing',
    errorCode: 'OperatorPrecedingWhitespaces',
    range: [ 5, 5 ],
    loc: {  start: { line: 1, column: 5 }, end: { line: 1, column: 5 }  },
    payload:
     { actual: 0,
       expected: 1,
       excerpt: '',
       trace: '..a=..',
       where: '<' } } ]

*/

Developing a sniff

Let's consider a sniff, which validates the number of spaces preceding parameter list in a function declaration. First of all, we need to apply the defined rules to function declarations only. Syntax Tree gives us precise information about any function declaration in the code. As the sniff will rely on Syntax Tree we place the new module to /Lib/Sniff/SyntaxTree and name it according to the defined rule-set FunctionDeclarationParameterListSpacing (has to be also presented in SyntaxAnalizer).

Every sniff module has method validateRule. There we simply enlist the option validators:

utils.validateRule( rule, "allowPrecedingWhitespaces", "number", true );

Method run performs the sniffing job. There we lop off all the inappropriate nodes (node.type === "FunctionDeclaration"). Now we have to determine what the node parts correspond to the rule. In this case we need function identifier (node.id) and the following token representing opening parenthesis. Unfortunately the Syntax Tree doesn't contain any information about such tokens as grouping parentheses. However we can ask TokenIterator for help. Let's get the token corresponding to the function identifier:

tokenIt = tokenIterator.findByLeftPos( node.id.range[ 0 ] );

Now we can simply request the token following this one as tokenIt.get( 1 ) (and preceding as tokenIt.get( -1 ). So the spaces of our interest are expected between those two tokens. We can make sure we point to the right code fragment like that:

sourceCode.extract( node.id.range[ 1 ], tokenIt.get( 1 ).range[ 0 ] ).print();

to make the real check, we use the following mixin:

mixin.sniffExcerpt( node.id, tokenIt.get( 1 ),
  rule.allowPrecedingWhitespaces, "FunctionDeclarationParamListPrecedingSpacing", "<" );

Analytics

Bitdeli Badge

jscodesniffer's People

Contributors

bafolts avatar bitdeli-chef avatar dsheiko avatar nschonni avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jscodesniffer's Issues

ArgumentsSpacing Exception (firstArg > allowArgPrecedingWhitespaces) doesn't seem to work.

Hi,

I recently tried integrating this project into our build system to check the style of everyones JS modules and standardize it, but I have a little bit of trouble with the configuration.

This is a piece of module definition:

/*global define */
define('library/uielements/textinput', [
  'core'
], function(require) {

And the configuration that should apply to the preceding whitespace of the first argument of the define function.

"ArgumentsSpacing": {
    "allowArgPrecedingWhitespaces": 1,
    "allowArgTrailingWhitespaces": 0,
    "exceptions": {
      "singleArg" : {
        "for": ["FunctionExpression", "ArrayExpression", "ObjectExpression"],
        "allowArgPrecedingWhitespaces": 0,
        "allowArgTrailingWhitespaces": 0
      },
      "firstArg": {
        "for": [ "FunctionExpression" ],
        "allowArgPrecedingWhitespaces": 0
      },
      "lastArg": {
        "for": [ "FunctionExpression" ],
        "allowArgTrailingWhitespaces": 0
      }
    }
}

The way I read these configs, it should allow a preceding whitespace in all cases, except for the first parameter. Yet it complains when I check the style. It says it needs a preceding space.

Secondly, could these exceptions also be added to the parameter options?

PS: Thank you so much for this tool. Finally I can enforce code style conventions within the company.

ArrayLiteralSpacing > Exceptions > firstElement > allowElementPrecedingWhitespaces fails.

Consider this test:

/*jshint -W068 */
/*jshint multistr: true */
var Sniffer = require( "../../lib/Sniffer" );

require( "should" );

Array.prototype.hasErrorCode = function( errCode ) {
  return !!this.filter(function( msg ){
    return msg.errorCode === errCode;
  }).length;
};

var OPTIONS = {
      standard: "Jquery"
  };

describe( " Custom checks ", function () {
  var sniffer, logger = null;
  beforeEach(function(){
    sniffer = new Sniffer();
  });

  it(" must implement custom standard correctly", function () {
   var code = "ok.push([ok[1]]);",

    modifiers = {
      "LineLength": false,
      "Indentation": false,
      "QuoteConventions": false,
      "ArgumentsSpacing": false,
      "ParametersSpacing": false,
      "ObjectLiteralSpacing": false,
      "ArrayLiteralSpacing": {
            "allowElementPrecedingWhitespaces": 1,
            "allowElementTrailingWhitespaces": 0,
            "exceptions": {
                "singleElement": {
                    "for": [ "FunctionExpression", , "ArrayExpression", "ObjectExpression", "Literal" ],
                    "allowElementPrecedingWhitespaces": 0,
                    "allowElementTrailingWhitespaces": 0
                },
                "firstElement": {
                    "for": [ "FunctionExpression", , "ArrayExpression", "ObjectExpression", "Literal" ],
                    "allowElementPrecedingWhitespaces": 0
                },
                "lastElement": {
                    "for": [ "FunctionExpression", , "ArrayExpression", "ObjectExpression", "Literal" ],
                    "allowElementTrailingWhitespaces": 0
                }
            }
        }
    };

    logger = sniffer.getTestResults( code, OPTIONS, modifiers );

    console.log(logger.getMessages());

    logger.getMessages().length.should.equal(0);
  });
});

The test fails for the array within an array, but it should allow this or is my configuration wrong?

Wrong EmptyConstructsSpacing validation

I've got a little piece of code that is failing validation, and I can't figure out why that is. I suspect a bug.

The code I'm using is as follows:

if (typeof piwikDomain != "undefined") {
    var _paq = _paq || [];
    (function(){
    var piwikDomain = true;
    })();
}
else {
    console.warn( "piwikDomain variable not defined" );
}

I have been testing this with both node-jscs and the online validator, and in both cases I get this:
3 4 There must be no whitespaces in empty constructs; one found

Does this qualify as a bug, or do I really have some sort of error in my syntax that I am not aware of?

Missing a colon in "readme documentation"

In the readme.me file (https://github.com/dsheiko/jscodesniffer/blob/master/README.md), under "Declaring coding style", there is an example file.

Well, there is a colon missing in the "ParametersSpacing" option, in the 4th line of the "lastParam":

        "lastParam": {
          "for": [ "Identifier" ],
          "allowParamPrecedingWhitespaces": 1
          "allowParamTrailingWhitespaces": 0
        }

Should be:

        "lastParam": {
          "for": [ "Identifier" ],
          "allowParamPrecedingWhitespaces": 1,
          "allowParamTrailingWhitespaces": 0
        }

Thanks

ArrayLiteralSpacing Strange Behavior

Here is the relevant area of my .jscsrc file:

"ArrayLiteralSpacing": {
    "allowElementPrecedingWhitespaces": 1,
    "allowElementTrailingWhitespaces": 0,
    "exceptions": {
        "singleElement": {
            "for": [ "Identifier", "FunctionExpression", "Literal", "ObjectExpression", "ArrayExpression" ],
            "allowElementPrecedingWhitespaces": 0,
            "allowElementTrailingWhitespaces": 0
        },
        "firstElement": {
            "for": [ "Identifier", "FunctionExpression", "Literal", "ObjectExpression", "ArrayExpression" ],
            "allowElementPrecedingWhitespaces": 0
        },
        "lastElement": {
            "for": [ "Identifier", "Literal" ],
            "allowElementTrailingWhitespaces": 0
        }
    }
},

It reports the following code:

var w = 1,
    x = [1, 2, 3],
    y = [x[0], x[1], x[2]],
    z = [w + 1];

(Line 3 & 4, Column 6): ArrayLiteralSpacing: There must be one whitespace(s) preceding array element; no found

Is there a bug in the code, or an issue with my settings?

Have the same exception possibilities of arguments on arrays.

Consider:

/*jshint -W068 */
/*jshint multistr: true */
var Sniffer = require( "../lib/Sniffer" );

require( "should" );

Array.prototype.hasErrorCode = function( errCode ) {
  return !!this.filter(function( msg ){
    return msg.errorCode === errCode;
  }).length;
};

var OPTIONS = {
      standard: "Jquery"
  };

describe( " Custom checks ", function () {
  var sniffer, logger = null;
  beforeEach(function(){
    sniffer = new Sniffer();
  });

  it(" must implement custom standard correctly", function () {
   var code = "var a = [1, 2, 3];",

    modifiers = {
      "Indentation": false,
      "QuoteConventions": false,
      "ArrayLiteralSpacing": {
        "allowElementPrecedingWhitespaces": 1,
        "allowElementTrailingWhitespaces": 1
      }
    };

    logger = sniffer.getTestResults( code, OPTIONS, modifiers );

    console.log(logger.getMessages());
    logger.getMessages().length.should.not.be.ok;
  });

});

It would be nice if I could pass this test by changing the modifiers of ArrayLiteralSpacing.

ifNesting of argumentSpacing should accept the same configuration as its parent.

There is no way of configuring nested argumentSpacing options the same way as its parent. This gives us strange situations where I have to force employees to change their styling for nested function calls. Consider this piece of code:

define('library/uielements/textinput', [
  'core'
], function(require) {
  var core = require("core"),
      _textinput = {
        create: function(input, type, options) {
          switch(type) {
            case _self.TYPE_NORMAL:
              _self.normal(input, options);
              break;
          }
       }
     };
});

The _self.normal() is seen as a nested function call but doesn't allow for that format in any way.

Error when running

Hi,
I'm using nodejs version 0.8.21 and getting the following error when trying to run jscs:

/home/user/src/jscodesniffer/standard/Idiomatic.js:202
this.log( token, "Idiomatic.invalidCommaPunctuatorSpac
^
TypeError: Object # has no method 'log'
at members.sniffArgumentSpacing (/home/user/src/jscodesniffer/standard/Idiomatic.js:202:30)
at Array.forEach (native)
at members.sniffArgumentSpacing (/home/user/src/jscodesniffer/standard/Idiomatic.js:200:39)
at Object.sniffer.analyzeTokens (/home/user/src/jscodesniffer/lib/Sniffer.js:47:45)
at Object.sniffer.run (/home/user/src/jscodesniffer/lib/Sniffer.js:23:31)
at /home/user/src/jscodesniffer/jscs:88:26
at processFile (/home/user/src/jscodesniffer/jscs:27:21)
at processPath (/home/user/src/jscodesniffer/jscs:48:36)
at Object. (/home/user/src/jscodesniffer/jscs:84:1)
at Module._compile (module.js:449:26)

Thanks

Windows - Maximum call stack size exceeded

I am running inside Windows XP with npm version 1.4.3 and node version 0.10.26.
When trying to run a test of jscs no matter what directory/file I give, I get the error "Maximum call stack size exceeded".

I delved into the code some printing console logs along the way, the error is happening inside jscs-module.js on the call to "cli.readRealTimeConfig( cwd )".
Inside "readRealTimeConfig" in "Cli.js", I figured the cause to the be the calculation of of the parentPath and it is getting stuck in an endless loop.
ParentPath keeps going to the top drive letter, "C:". Unfortunately the parentPath of top drive still returns "C:". The "readRealTimeConfig"'s exit condition states the length must be equal to 1 or receive a non-directory, probably a linux only coding expecting "/". So it is never reaching this exit condition and hence nodejs reaching the maximum call stack.

To fix this, an extra exit condition of "pathArg == parentPath" should be added, to prevent an endless loop.

Custom standart as path

Is there a way to pass not the name, but the path to a custom standart? I would like to tweak an existing standart to suit our needs, but can't find a way to reference it without putting it into the node_modules directory.

Is there a way that I am missing?

ArgumentsSpacing Exception isn't working

Hi there,

I'm trying to use my own coding-standard but the exceptions of ArgumentsSpacing and ParametersSpacing aren't working. Here ´'s the rule:

"ArgumentsSpacing": {
        "allowArgPrecedingWhitespaces": 1,
        "allowArgTrailingWhitespaces": 0,
        "exceptions": {
            "singleArg": {
                "for": [ "FunctionExpression", "ArrayExpression", "ObjectExpression" ],
                "allowArgPrecedingWhitespaces": 0,
                "allowArgTrailingWhitespaces": 0
            },
            "firstArg": {
                "for": [ "FunctionExpression", "ArrayExpression", "ObjectExpression" ],
                "allowArgPrecedingWhitespaces": 0
            },
            "lastArg": {
                "for": [ "FunctionExpression", "ArrayExpression", "ObjectExpression" ],
                "allowArgTrailingWhitespaces": 0
            }
        }
    }

And this line creates following error:

$(selector).css("width", final + "px");
ArgumentsSpacing: There must be one whitespace(s) preceding argument; no found

What I want is: 1 whitespace between every argument. But not before the first argument and not after the last argument. That implies no whitespaces before and after a single argument too.

Thanks for help!

Gulp plugin

Hey

I'm considering making a Gulp friendly plugin that processes file streams against this module. I've had a quick look around the code and the docs but its not immediately clear how to use this module strictly programmatically from another module. In pseudo code, something like the following:

var jscs = require('jscodesniffer');

var results = jscs(args);

Where results in the above example would be a reporter/formatter implementation agnostic object literal that could be used flexibly to transform the output in any way:

{
    path: "path/to/file/under/test.js",
    pass: false,
    errors: [
        {
            line: 47,
            column: 13,
            message: "Fail message text"
        },
        { ... },
        { ... }
    ]
}

I don't mean the above code examples as a prescriptive suggestion, I'm just trying to illustrate the way I'd need to use the module programmatically. From what I can see the module is quite structured around the notion of using it as a cli tool rather than a node module.

Is this above use case supported do you think?

Configurable report width

It would be nice if the report width was configurable via command line. It looks like this project is in the spirit of php codesniffer, which supports this option, among others that would also be nice to have.

Relax indentation rule(s) for JSDoc comments

It would be nice if there was a setting to relax indentation rules for JSDoc comments.

So we want to force tabs for indenting and no mixing of tabs and spaces is allowed, but it should be possible to format the comment with spaces (one):

    /**
     * Gets a member in object specified by path.
     *
     * @param {Object} object An object
     * @param {Array} path An array of indices indicating a path to a member of object
     */

instead of

    /**
    * Gets a member in object specified by path.
    *
    * @param {Object} object An object
    * @param {Array} path An array of indices indicating a path to a member of object
    */

Add sniff for whitespace around control flow statements

It would be nice if there was built in support for whitespace around control flow statements. e.g.

good
for (...) {
while (...) {
if (...) {
} else {
}

bad
for(...){
while (...){
if(...)
{
}
else
{
}

They could be additional parameters under CompoundStatementConventions -> allowPrecedingWhitespaces and allowTrailingWhitespaces

On a related note, CompoundStatementConventions -> requireMultipleLines = true doesn't work the way I would expect.

This isn't allowed (as expected): if (dumb) { dumb = 1; }, but this is:

if (dumb) { dumb = 1;
}

I'd expect requireMultipleLines to require that a line break immediately follow the open brace. This would also be consistent with jQuery's style guide.

Use strict generates error

In start of js file we need to add 'use strict' to comply to the new standards, but adding this in first line of file and running jscs of this file gives follow error:
FILE: <file.js> violates Idiomatic standard
ERROR: Variable statements should always be in the beginning of their respective scope

ES6 support

Hi

Is ES6 going to be supported ? esprima version you are using only supports 5.1, but the newest version has ES6 support. Is there a reason why it is no used yet ?

Certain keywords preceded or followed by a new line.

It would be nice if you could configure certain lines that start with a keyword (if/return/etc) to have either an empty line preceding and/or following that line/construct.

Good:

  val = 1;  

  return val;
}

Bad:

  val = 1;
  return val;
}

Good:

if (val === 1) {
  console.log(val);
}

With an override for all first lines in a function/if/switch/... block.

function() {
  if (val === 1) {
    console.log(val);
  }
}();

Bad:

if (val === 1) {
  console.log(val);
}

'error' event on first tick

I have installed jscodesniffer on ubuntu (made sure every required dependecies were installed) and I got this error at fisrt try on js file.

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Object # has no method 'existsSync'
at /usr/local/lib/node_modules/npm/test/packages/jscodesniffer/jscs:44:23
at Object. (/usr/local/lib/node_modules/npm/test/packages/jscodesniffer/jscs:84:1)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)

Spaces around function declarations vs. function invocation parens

Unless I'm missing it, it seems like a handy rule would relate to spaces around the function keyword parens in different scenarios. Namely, function declaration vs. function invocation. For example:

Enforce spaces around parens for function declarations

// Good
function () {
}
function foo () {
}

// Bad
function() {
}
function(){
}
function foo() {
}
function foo (){
}
function foo(){
}

Enforce no spaces around parens for function invocation

// Good
var a = function();

// Bad
var a = function ();

The rationale behind this rule relates to the fact that some devs like to enforce a visual distinction between a function declaration and a function invocation.

What do you think?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.