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.
Related
I'm migrating a package from a much older version of commander (v2.20.3)
program.command(`install [pkg]`)
.alias(`i`)
.action(installPackageOrLocal)
.option(`-S, --save`, `Save to dependencies`)
.option(`-D, --save-dev`, `Save to devDependencies`)
.option(`--production`, `Will not install modules listed in devDependencies`)
.option(`--test`, `Exit with code 1 if package limits like maxPackagesNumber or maxSizeBites exceeded`);
I'd like for the default (when calling the CLI with no arguments at all) to continue being the display of the help and no erring out, but currently it errs with:
.../npm-reflect/node_modules/.pnpm/commander#8.3.0/node_modules/commander/lib/command.js:142
const [, name, args] = nameAndArgs.match(/([^ ]+) (.)/);
I was able to get the mostly desired behavior by adding:
program.command('help', {isDefault: true})
.action(() => {
program.help();
})
.command(`install [pkg]`)
// ...
...but this seems to be polluting things in the help by listing a new "help" command. How can I avoid the parser complaining when no arguments are present yet without adding a new command?
The default behaviour in latest Commander is to display the help if you have subcommands and do not specify a subcommand. Which sounds like what you want! Not sure how you are getting an error, you might want to open a Commander issue for help.
In general, if you want some custom behaviour for no arguments then it may be simple and easy to check yourself before calling parse(). e.g.
if (process.argv.length < 3)
program.help(); // exits
program.parse(process.argv);
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).
TL;DR
I am trying to manually trigger ace editor snippets through a function call, rather than the conventional approach (keyboard keys).
Explanation
I need a function that takes in the editor and a snippet string as the parameters, and adds that snippet to the editor. function addSnippet(editor, snippet).
Ace editor supports TextMate-ish snippets.
if (${1:condition_name}) {
${2:body}
}
So when we call this function, it should add the snippet, highlight the snippet markers and select the first one. After filling the first one and hitting tab, the editor should move to the next snippet marker. Just like in the Kitchen Sink example (but I want to add/trigger snippets via a function call instead).
I tried hacking my way through and made this function. But it's messy and incomplete (doesn't support markers and tab presses). Is there any native method for this? I've seen a few examples using snippetManager, but they use keyboard triggers, not manual functions.
Any help regarding this issue would be appreciated.
Thanks.
After hours of hacks and research, I finally came across the insertSnippet function of snippetManager in ext-language_tools.js, it works this way:
var snippetManager = ace.require("ace/snippets").snippetManager;
snippetManager.insertSnippet(editor, snippet);
Pretty easy actually, couldn't find it earlier due to lack of documentation.
If you don't use RequireJS then the following syntax works as well:
ace.config.loadModule('ace/ext/language_tools', function () {
editor.insertSnippet(snippetText);
});
Use ace.define(...) for adding your snippet.
The snippets are written in tex-like language.
For Snippet defined at ./src/lib/json-snippet.js:
// eslint-disable-next-line
const snippet = '# AddNode\n\
snippet addn\n\
{\n\
"nodeName": "${1:node_name}",\n\
"algorithmName": "${2:algo_name}",\n\
"input": []\n\
}\n\
';
export default snippet;
// import your snippet
import snippet from "../lib/json-snippet";
// SUPER HACK FOR ADDING SNIPPETS
ace.define("ace/snippets/json", ["require", "exports", "module"], (e, t, n) => {
// eslint-disable-next-line
(t.snippetText = snippet), (t.scope = "json");
});
Use brace/mode/{filetype}, brace/snippets/{filetype} for defining file type and it snippets.
Find existing snippets at node_module/brace/snippets/ for overriding.
import "brace/mode/json";
import "brace/snippets/json";
import "brace/ext/language_tools";
For more information check out:
Demo
This repository
The other answers seem to be kind of old or rather hacky. This worked for me using actual Ace APIs on v1.4.12 (albeit this seems to be totally and frustratingly undocumented).
const snippetManager = ace.require('ace/snippets').snippetManager;
const snippetContent = `
# scope: html
snippet hello
<p>Hello, \${1:name}!</p>
`;
const snippets = snippetManager.parseSnippetFile(snippetContent);
snippetManager.register(snippets, 'html');
Exchange html for whatever scope you want.
In the editor type "hello" followed by TAB to trigger the snippet.
I started using Jasmine to test javascript code and its working fine. But I would like to display inputs to the test suite in specrunner.html.
I tried HtmlReporter() and TrivialReporter() but no luck.
SPEC CODE:
checkAddition("TEST_SUITE","Test INPUTS1",getResult(2,3),5);
checkAddition("TEST_SUITE","Test INPUTS2",getResult(3,8),11);
function checkAddition(suite_name,testcase,result,equalto){
describe(suite_name, function() {
it(testcase, function() {
expect(result).toEqual(equalto);
});
});
}
JavaScript CODE:
function getResult(input1,input2){
return input1+input2;
}
OUTPUT :
EXPECTED OUTPUT :
I need to display inputs that looks like expected output (I edited code in browser using firebug to share expected output).
Please help me. Help would be appreciated :)
The built reporters won't do this. You either need to need to hack the innards of those built in reporters to do this (you're on your own with this route), or create your own reports from scratch (see here for some examples).
But I find this to be a strange request. Perhaps there is a cleaner way to achieve your goal, whatever that may be. Maybe a test suite isn't what you want if you want this info.
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.