Git Product home page Git Product 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 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

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);
}

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

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.

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.

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.

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?

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.

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
    */

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?

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!

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

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?

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.

'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)

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?

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.