Treat the use of #author as code style violation - javascript

Goal:
Issue a warning in case an #author tag is used anywhere inside the .js files in the project.
Question:
Is it something that jshint or other static code check tools can help with? If not, what options do I have?
Description:
I completely agree with Paul's answer at Javadoc #author tag good practices thread and treat #author tag as an unnecessary noise.
And, in the Python world, I've seen people checking for the tag usage. For example, Openstack Style Guidelines explicitly state not use #author tag. They have developed a set of custom flake8 checks which include:
[H105] Don’t use author tags.
Now, I'm trying to solve the same problem in JavaScript.
Example (this should not pass a code quality check):
/**
* #author John Smith <john#smith.com>
*/
'use strict';

No, jshint can't do that. Just do a grep across the sources looking for #author. If you want you could put that in a git pre-commit hook. Or, you could hack JSDoc to error out when creating docs if it encounters #author.

Sorry, I meant to try this out before posting an answer, but the bounty's almost up. ;^)
This answer claims that there's a way to write your own JSHint module.
It looks like it was done in a branch, https://github.com/jshint/jshint-next/wiki/Design
Its readme says, This project is obsolete. It was merged into the main repository, so that's a good sign.
Let's pretend it works as advertised and has been merged back in.
Great instructions here, though note that those are on the "jshint-next" site.
Example code from that page:
// This module errs on any identifier that doesn't starts with 'kitty'.
function myModule(linter) {
linter.on("Identifier", function (ident) {
if (ident.name && ident.name.slice(0, 5) !== "kitty")
linter.report.addError("C001", "More cats please.");
});
}
Here's from the initial section on how to set up a linter:
var Linter = require("jshint").Linter;
var code = "<your beautiful JavaScript code here>";
// Create a new instance of Linter.
var linter = new Linter(code);
// Now you can teach JSHint about your predefined variables.
// Note that default JavaScript identifiers are already there.
linter.addGlobals({
jQuery: false,
MyPlugin: true
});
// If you have any JSHint extensions, you can attach them
// to the current instance.
linter.addModule(myModule);
// Finally, parse your code.
linter.parse();
I realize that's pretty generic (you'd still need to research linter.on options beyond Identifier; there's a String too, eg), but it looks pretty promising. Again, you can see how to integrate using the instructions above. And it looks like this is the format that's used in style.js.
I have not tried this out yet. Just haven't had time at home; apologies.
Is there a specific reason torazaburo's "Just grep it" answer doesn't work? Do you need this to be part of a code quality workflow? If so, this "write your own module" would seem to be the way to go.
There are also pretty obvious ways to hack up JSLint, if you're up for it, but I'm not sure Crockford would appreciate that. ;^)

Solved it with ESLint package - a pluggable linting utility for JavaScript.
Created a custom rule (note how simple it is) and saved it to rules/no-author.js:
/**
* #fileoverview A rule to disallow #author tag in code
*/
module.exports = function (context) {
"use strict";
function checkComment(node) {
var commentToCheck = node.value.toLowerCase().trim();
if (commentToCheck.indexOf("#author") !== -1) {
context.report(node, "A comment unexpectedly contains #author.");
}
}
return {
"BlockComment": checkComment,
"LineComment": checkComment
};
};
Now, imagine I have a test.js file that violates the use of #author tag:
/**
* #author John Smith <john#smith.com>
*/
And see how the rule is applied:
$ eslint test.js --rulesdir=rules/ --rule='no-author: 2'
test.js
1:0 error A comment unexpectedly contains #author no-author
✖ 1 problem
FYI, no-author: 2 here means to turn the rule on as an error (exit code is 1 when triggered).

Related

SonarQube JavaScript disable a part of code

I would like to disable a block of code(say a function) in a file for analysis by SonarQube... Any suggestions on how to do that..
I found something for java here --> Turning Sonar off for certain code
As far as I know Sonar respects // NOSONAR tag for Java projects but it looks like that is also has been implemented for JS: https://jira.sonarsource.com/browse/SONARJS-294
SonarQube provides plenty of options for ignoring issues in specific files and/or code blocks, see Narrowing the Focus documentation (and to your specific case: look for Ignore Issues in Blocks).
To ignore blocks:
// BEGIN-NOSCAN
const YourFunction () => {
// Your code
}
// END-NOSCAN
To ignore single lines:
// NOSONAR
const YourCode = 'Example';
You can read more about it here in the SonarQube docs Narrowing the Focus. Thanks to Jan and Nicolas's answer above.

Buggy code completion in eclipse JavaScript Development Tools

I open a project with file => new => static web project. Name it MyProject and web content folder name is WebContent.
Right click the WebContent directory and add a js directory. Right click the js directory and choose new => other => JavaScript source file and call it DomStuff.js with the following content:
var MyApp={};
MyApp.DomStuff={};
MyApp.DomStuff.someFunction=function(){
return true;
}
MyApp.do<== here it auto completes to DomStuff
Right click the js directory again and choose new => other => JavaScript source file and call it WorkFlow.js
When I type MyApp. then press control + space I get a box saying No Default Proposals. It's like auto complete only works when all the code is in one file.
Right click JavaScript Resources under the Source tab MyProject/WebContent is listed as included all and excluded none.
This is in Eclipse Version: 4.2.1 with Eclipse Web Developer Tools 3.4.1 and JavaScript Development Tools 1.4.1.
For as long as I remember I never got the auto complete to work on code outside the file I am currently working on. Is this normal or am I missing some setting here?
Standard JSDT can seem non deterministic when it come to completions across files. That is because even if the project is configured correctly then the most expensive type of it's source code analysis only occurs on files that are open. Do you get the same result if both files are open?
By the way, there is a fork of JSDT that is a candidate for merging to official JSDT called JSDT+NJSDoc that handles such cross file analysis extremely efficiently (and adds other features): https://bitbucket.org/nexj/webtools.jsdt.core
[update]
Basically Eclipse with JSDT can't do the job. Tried to define all my namespaces with constructor functions but it's all too much trouble.
Trying netbeans now and it'll assist most of the closure library and all of my code. Some things like goog.array won't complete because goog.array is never defined. When adding goog.array=new Object() to the array.js it'll complete goog.array and goog.array.ArrayLike. These modded js file go in your js/libs directory of your project.
If you want the troublesome way to get it to work in Eclipse then keep reading.
It seems that Eclipse has problems with objects declared as object literals. Declaring my complex types with a constructor function seems to do the trick. An instance of the root object has to be created on Window (capital W).
// this would be the way I would define
// a complex property that doesn't need
// more than one instance and is not complex
// enough to put in a separate file
myapp.workflow.objectLiteral={
thisDoesNotCodeAssist:function(){},
neitherDoesThis:22
};
/** if you define the complex property as
* a constructor it will auto complete
* in other files and closure compiler will
* recognize it's type
*/
/** #constructor organizes flow
* used for Eclipse code assist */
var WorkFlow=function(){};
ProwpWithSubs=function(){};
PropWithSubs.prototype.subProp=22;
PropWithSubs.prototype.subFunction=function(){
this.subsub=44;
};
WorkFlow.prototype.propwithsubs=new PropWithSubs();
if(ALLWAYSFALSE){
/**needed for Eclipse code assist
* #constructor
*/
var MyApp=function(){};
MyApp.prototype.workflow=new WorkFlow();
MyApp.prototype.dom=new DOM();
Window.prototype.myapp=new MyApp();
}else{
myapp.workflow=new WorkFlow();
}
[update]
Here are 3 files I use to split up the definition and the implementation a little so it's easier with google closure.
Setting up the main types in types.js
// source: js/mmyapp/types.js
goog.provide("myapp.types");
/** #constructor */
var gooblediegoog=function(){};
/** #constructor */
gooblediegoog.prototype.WorkFlow=function(){};
/** #constructor */
gooblediegoog.prototype.Dom=function(){};
myapp.types=new gooblediegoog();
A file that isn't used at all in my code but tells Eclipse how to auto complete:
// source: js/myapp/forCodeAssist.js
/** #const {boolean} */
var ALLWAYSFALSE=false;
if(ALLWAYSFALSE){
/**needed for Eclipse autocomplete
* #constructor
*/
var MyApp=function(){};
MyApp.prototype.types=new gooblediegoog();
Window.prototype.myapp=new MyApp();
MyApp.prototype.workflow=new myapp.types.WorkFlow();
MyApp.prototype.dom=new myapp.types.Dom();
}
An implementation of workflow:
// source: js/myapp/workflow.js
goog.provide("myapp.workflow");
goog.require("myapp.types");
goog.require("myapp.dom");
/** #returns number|undefined */
myapp.types.WorkFlow.prototype.createOrder=function(){
return myapp.dom.getArticleAmout();
};
myapp.workflow=new myapp.types.WorkFlow();
window['console'].log(myapp.workflow.createOrder());
This can be converted to a myapp.workflow.createOrder=... syntax by replacing myapp.types.WorkFlow.prototype with myapp.workflow, removing myapp.workflow=new myapp.types.WorkFlow() and removing the goog.require("myapp.types"). Maybe this can be automated in the build/compile process if needed.
I am not sure if creating a single object with the help from a constructor function is much more expensive than just having goog.require create myapp.workflow and adding properties to it as I used to do (and as it's done in closure library).

How do I use uncompressed files in Dojo 1.7?

I've created a Dojo module which depends on dojox/data/JsonRestStore like this:
define("my/MyRestStore",
["dojo/_base/declare", "dojox/data/JsonRestStore"],
function(declare, JsonRestStore) {
var x = new JsonRestStore({
target: '/items',
identifier: 'id'
});
...
which is fine. But now I want to have the the uncompressed version of the JsonRestStore code loaded so that I can debug it. I can't find any documentation on how to do this, but since there is a file called 'JsonRestStore.js.uncompressed.js' I changed my code to:
define("my/MyRestStore",
["dojo/_base/declare", "dojox/data/JsonRestStore.js.uncompressed"],
function(declare, JsonRestStore) {
...
thinking that might work.
I can see the JsonRestStore.js.uncompressed.js file being loaded in FireBug, but I get an error when trying to do new JsonRestStore:
JsonRestStore is not a constructor
Should this work?
Is there a way of configuring Dojo to use uncompressed versions of all modules? That's what I really want, but will settle for doing it on a per dependency basis if that's the only way.
Update
I've found a way to achieve what I want to do: rename the JsonRestStore.js.uncompressed.js file to JsonRestStore.js.
However, this seems a bit like a hacky workaround so I'd still be keen to know if there is a better way (e.g. via configuration).
You have two options
1) Create a custom build. The custom build will output a single uncompressed file that you can use for debugging. Think the dojo.js.uncompressed.js but it includes all the extra modules that you use.
OR
2) For a development environment, use the dojo source code. This means downloading the Dojo Toolkit SDK and referencing dojo.js from that in the development environment.
For the projects I work on, I do both. I set up the Dojo configuration so that it can be dynamic and I can change which configuration that I want using a query string parameter.
When I am debugging a problem, I will use the first option just to let me step through code and see what is going on. I use the second option when I am writing some significant js and don't want the overhead of the custom build to see my changes.
I describe this a bit more at
http://swingingcode.blogspot.com/2012/03/dojo-configurations.html
I think the reason for this is due to the fact that the loader declares its class-loads (modules), by the file conventions used. The 1.7 loader is not too robust just yet, ive had similar problems until realizing how to separate the '.' and '/' chars.
Its only a qualified guess; but i believe it has to do with the interpretation of '.' character in the class-name which signifies as a sub-namespace and not module name.
The 'define(/ * BLANK * / [ / * DEPENDENCIES * / ], ...)' - where no first string parameter is given - gets loaded by the filename (basename). The returned declare also has a saying though. So, for your example with jsonrest, its split/parsed as such:
toplevel = dojox
mid = data
modulename = JsonRestStore.js.uncompressed
(Fail.. Module renders as dojox.data.JsonRestStore.js.uncompressed, not dojox.data.JsonRestStore as should).
So, three options;
Load uncomressed classes through <script src="{{dataUrl}}/dojox/data/JsonRestStore.js.uncompressed.js"></script> and work them on dojo.ready
I think modifying the define([], function(){}) in uncompressed.js to define("JsonRestStore", [], function() {}) would do the trick (uncomfirmed)
Use the dojo/text loader, see below
Text filler needed :)
define("my/MyRestStore",
["dojo/_base/declare", "dojo/text!dojox/data/JsonRestStore.js.uncompressed.js"],
function(declare, JsonRestStore) {
...
JsonRestStore = eval(JsonRestStore);
// not 100% sure 'define' returns reference to actual class,
// if above renders invalid, try access through global reference, such as
// dojox.dat...

Make Closure Compiler strip log function usages

I have a logging API I want to expose to some internal JS code. I want to be able to use this API to log, but only when I am making a debug build. Right now, I have it partially working. It only logs on debug builds, but the calls to this API are still in the code when there is a regular build. I would like the closure-compiler to remove this essentially dead code when I compiler with goog.DEBUG = false.
Log definition:
goog.provide('com.foo.android.Log');
com.foo.Log.e = function(message){
goog.DEBUG && AndroidLog.e(message);
}
goog.export(com.foo.Log, "e", com.foo.Log.e);
AndroidLog is a Java object provided to the webview this will run in, and properly externed like this:
var AndroidLog = {};
/**
* Log out to the error console
*
* #param {string} message The message to log
*/
AndroidLog.e = function(message) {};
Then, in my code, I can use:
com.foo.Log.e("Hello!"); // I want these stripped in production builds
My question is this: How can I provide this API, use this API all over my code, but then have any calls to this API removed when not compiled with goog.DEBUG = true? Right now, my code base is getting bloated with a bunch of calls to the Log API that are never called. I want the removed.
Thanks!
The Closure Compiler provides four options in CompilerOptions.java to strip code: 1) stripTypes, 2) stripNameSuffixes, 3) stripNamePrefixes and 4) stripTypePrefixes. The Closure build tool plovr, exposes stripNameSuffixes and stripTypePrefixes through its JSON configuration file options name-suffixes-to-strip and type-prefixes-to-strip.
There are excellent examples of how these options work in Closure: The Definitive Guide on pages 442 to 444. The following lines are provided as common use cases:
options.stripTypePrefixes = ImmutableSet.of(“goog.debug”, “goog.asserts”);
options.stripNameSuffixes = ImmutableSet.of(“logger”, “logger_”);
To understand the nuances of these options and avoid potential pitfalls, I highly recommend reading the complete examples in Closure: The Definitive Guide.
Instead of running your own script as jfriend00 suggested I would look at the define api of the compiler (which is where goog.DEBUG comes from as well), you have DEBUG, COMPILED by default, but there you can roll your own.
OK, it turns out this is easy to do if I stop exporting com.foo.Log() and its methods. If I really want to be able to log in some specific cases, but still strip out the log calls in my internal code, I can just declare two classes for this:
// This will get inlined and stripped, since its not exported.
goog.provide('com.foo.android.Log');
com.foo.Log.e = function(message){
goog.DEBUG && AndroidLog.e(message);
}
// Don't export.
// This be available to use after closure compiler runs, since it's exported.
goog.provide('com.foo.android.production.Log');
goog.exportSymbol("ProductionLog", com.foo.android.production.Log);
com.foo.android.production.Log.log = function(message){
goog.DEBUG && AndroidLog.e(message);
}
// Export.
goog.exportProperty(com.foo.android.production.Log, "log", com.foo.android.production.Log.log);
I have modified a compiler and packaged it as an npm package.
You can get it here: https://github.com/thanpolas/superstartup-closure-compiler#readme
It will strip all logging messages during compilation

Exclude debug JavaScript code during minification

I'm looking into different ways to minify my JavaScript code including the regular JSMin, Packer, and YUI solutions. I'm really interested in the new Google Closure Compiler, as it looks exceptionally powerful.
I noticed that Dean Edwards packer has a feature to exclude lines of code that start with three semicolons. This is handy to exclude debug code. For instance:
;;; console.log("Starting process");
I'm spending some time cleaning up my codebase and would like to add hints like this to easily exclude debug code. In preparation for this, I'd like to figure out if this is the best solution, or if there are other techniques.
Because I haven't chosen how to minify yet, I'd like to clean the code in a way that is compatible with whatever minifier I end up going with. So my questions are these:
Is using the semicolons a standard technique, or are there other ways to do it?
Is Packer the only solution that provides this feature?
Can the other solutions be adapted to work this way as well, or do they have alternative ways of accomplishing this?
I will probably start using Closure Compiler eventually. Is there anything I should do now that would prepare for it?
here's the (ultimate) answer for closure compiler :
/** #const */
var LOG = false;
...
LOG && log('hello world !'); // compiler will remove this line
...
this will even work with SIMPLE_OPTIMIZATIONS and no --define= is necessary !
Here's what I use with Closure Compiler. First, you need to define a DEBUG variable like this:
/** #define {boolean} */
var DEBUG = true;
It's using the JS annotation for closure, which you can read about in the documentation.
Now, whenever you want some debug-only code, just wrap it in an if statement, like so:
if (DEBUG) {
console.log("Running in DEBUG mode");
}
When compiling your code for release, add the following your compilation command: --define='DEBUG=false' -- any code within the debug statement will be completely left out of the compiled file.
A good solution in this case might be js-build-tools which supports 'conditional compilation'.
In short you can use comments such as
// #ifdef debug
var trace = debug.getTracer("easyXDM.Rpc");
trace("constructor");
// #endif
where you define a pragma such as debug.
Then when building it (it has an ant-task)
//this file will not have the debug code
<preprocess infile="work/easyXDM.combined.js" outfile="work/easyXDM.js"/>
//this file will
<preprocess infile="work/easyXDM.combined.js" outfile="work/easyXDM.debug.js" defines="debug"/>
Adding logic to every place in your code where you are logging to the console makes it harder to debug and maintain.
If you are already going to add a build step for your production code, you could always add another file at the top that turns your console methods into noop's.
Something like:
console.log = console.debug = console.info = function(){};
Ideally, you'd just strip out any console methods, but if you are keeping them in anyway but not using them, this is probably the easiest to work with.
If you use the Closure Compiler in Advanced mode, you can do something like:
if (DEBUG) console.log = function() {}
Then the compiler will remove all your console.log calls. Of course you need to --define the variable DEBUG in the command line.
However, this is only for Advanced mode. If you are using Simple mode, you'll need to run a preprocessor on your source file.
Why not consider the Dojo Toolkit? It has built-in comment-based pragma's to include/exclude sections of code based on a build. Plus, it is compatible with the Closure Compiler in Advanced mode (see link below)!
http://dojo-toolkit.33424.n3.nabble.com/file/n2636749/Using_the_Dojo_Toolkit_with_the_Closure_Compiler.pdf?by-user=t
Even though its an old question. I stumbled upon the same issue today and found that it can be achieved using CompilerOptions.
I followed this thread.
We run the compiler, from Java, on our server before sending the code to the client. This worked for us in Simple mode.
private String compressWithClosureCompiler(final String code) {
final Compiler compiler = new Compiler();
final CompilerOptions options = new CompilerOptions();
Logger.getLogger("com.google.javascript.jscomp").setLevel(Level.OFF);
if (compressRemovesLogging) {
options.stripNamePrefixes = ImmutableSet.of("logger");
options.stripNameSuffixes = ImmutableSet.of("debug", "dev", "info", "error",
"warn", "startClock", "stopClock", "dir");
}
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
final JSSourceFile extern = JSSourceFile.fromCode("externs.js", "");
final JSSourceFile input = JSSourceFile.fromCode("input.js", code);
compiler.compile(extern, input, options);
return compiler.toSource();
}
It will remove all the calls to logger.debug, logger.dev...etc.etc
If you're using UglifyJS2, you can use the drop_console argument to remove console.* functions.
I use this in my React apps:
if (process.env.REACT_APP_STAGE === 'PROD')
console.log = function no_console() {};
In other words, console.log will return nothing on prod enviroment.
I am with #marcel-korpel. Isn't perfect but works. Replace the debug instructions before minification. The regular expression works in many places. Watch out unenclosed lines.
/console\.[^;]*/gm
Works on:
;;; console.log("Starting process");
console.log("Starting process");
console.dir("Starting process");;;;;
console.log("Starting "+(1+2)+" processes"); iamok('good');
console.log('Message ' +
'with new line'
);
console.group("a");
console.groupEnd();
swtich(input){
case 1 : alert('ok'); break;
default: console.warn("Fatal error"); break;
}
Don't works:
console.log("instruction without semicolon")
console.log("semicolon in ; string");
I haven't looked into minification so far, but this behaviour could be accomplished using a simple regular expression:
s/;;;.*//g
This replaces everything in a line after (and including) three semicolons with nothing, so it's discarded before minifying. You can run sed (or a similar tool) before running your minification tool, like this:
sed 's/;;;.*//g' < infile.js > outfile.js
BTW, if you're wondering whether the packed version or the minified version will be 'better', read this comparison of JavaScript compression methods.
I've used following self-made stuf:
// Uncomment to enable debug messages
// var debug = true;
function ShowDebugMessage(message) {
if (debug) {
alert(message);
}
}
So when you've declared variable debug which is set to true - all ShowDebugMessage() calls would call alert() as well. So just use it in a code and forget about in place conditions like ifdef or manual commenting of the debug output lines.
I was searching for a built-in option to do this. I have not found that yet, but my favorite answer also does not require any changes to existing source code. Here's an example with basic usage.
Assume HTML file test.html with:
<html>
<script src="hallo.js"></script>
</html>
And hallo.js with:
sayhi();
function sayhi()
{
console.log("hallo, world!");
}
We'll use a separate file, say noconsole.js, having this from the linked answer:
console.log = console.debug = console.info = function(){};
Then we can compile it as follows, bearing in mind that order matters, noconsole.js must be placed first in the arguments:
google-closure-compiler --js noconsole.js hallo.js --js_output_file hallo.out.js
If you cat hallo.out.js you'd see:
console.log=console.debug=console.info=function(){};sayhi();function sayhi(){console.log("hallo, world!")};
And if I test with mv hallo.out.js hallo.js and reload the page, I can see that the console is now empty.
Hope this clarifies it. Note that I have not yet tested this in the ideal mode of compiling all the source code with ADVANCED optimizations, but I'd expect it to also work.

Categories