Bloc-note d'un développeur web
Dans : Développement Web
3 juin 2010J’ai pris l’habitude de valider mon code JavaScript à l’aide de JSLint. Outil d’analyse statique de code, JSLint permet de m’assurer du niveau de qualité de mon code avant toute déploiement en production.
Cependant la console accompagnant l’outil ne me convenait pas, et ce pour plusieurs raisons :
window n’est pas défini via les options passées à JSLINT ce qui m’oblige à le déclarer, à l’aide de l’instruction /*@global, dans une majorité de mes scripts.browser: true — non présentes dans l’appel à JSLINT.Vous trouverez dans les lignes qui suivent la console que j’utilise en remplacement.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | /*global JSLINT */ /*jslint white: true, rhino: true */ /** * @fileOverview Provides a JSLint console for Rhino. * <p>Usage: <code>java -jar lib/js.jar lib/jslint-console.js lib/fulljslint.js src/testFile1.js src/testFile2.js</code></p> * @author Mehdi Kabab <http://pioupioum.fr/> * @version 0.1.1 (2010-06-24) */ /** * @license Copyright (c) 2010 Mehdi Kabab <http://pioupioum.fr/>. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ // Loads the JSLint script given as first argument. load(arguments.splice(0, 1)); (function (scripts) { var i, indentLen = 0; /** * Returns the string repeated multiplier times. * @param {Number} multiplier Number of time the string should be repeated. * @this {String} * @return Returns the repeated string. * @type String * @addon */ String.prototype.repeat = function (multiplier) { if (0 > multiplier) { multiplier = 0; } return new Array(1 + multiplier).join(this); }; /** * Cleans evidence message and assign <code>identLen</code>. * @private * @param {String} str The full message. * @param {String} p1 Possible identation. * @param {String} p2 The message content. * @returns The message content * @type String */ function cleanEvidence(str, p1, p2) { indentLen = p1.length; return p2; } // cleanEvidence /** * Check quality code of the given script. * @private * @param {String} jsfile File to check. * @requires JSLINT * @requires String#repeat() */ function lint(jsfile) { var i, input, e, errLen, errTag = "[ERROR] ", found = 0; print("Running JSLint on: " + jsfile); input = readFile(jsfile); if (!input) { print(errTag + "Couldn't open file."); quit(1); } if (!JSLINT(input, { browser: true, rhino: true, laxbreak: true, onevar: true, undef: true, nomen: true, eqeqeq: true, bitwise: true, regexp: false, newcap: true, predef: ['window', 'escape', 'unescape'] })) { for (i = 0, errLen = JSLINT.errors.length; i < errLen; ++i) { e = JSLINT.errors[i]; if (e) { found += 1; if ("% scanned)." !== e.reason.substr(-11)) { print(errTag + e.reason.replace(/\.$/, '') + " on line " + e.line + " character " + e.character + "."); if ("" !== e.evidence) { print(" ".repeat(errTag.length) + (e.evidence || '').replace(/^(\s*)(\S*(\s+\S+)*)\s*$/, cleanEvidence)); print(" ".repeat(errTag.length) + ".".repeat(e.character - indentLen - 1) + "^"); } } else { print(errTag + e.reason); } } } print("=> " + found + " error(s) found.\n"); quit(2); } else { print("OK\n"); } } // lint if (!scripts[0]) { print("Usage: jslint-console.js fulljslint.js file1.js[ file2.js]"); quit(1); } for (i = 0; i < scripts.length; ++i) { lint(scripts[i]); } }(arguments)); |
Les prérequis sont simples :
js.jar.rhino.js (en fin de script).Dans un shell, exécutez jslint-console.js à l’aide de Rhino, comme suis :
$ java -jar lib/rhino/js.jar lib/jslint/jslint-console.js lib/jslint/fulljslint.js src/*.js
Ici, deux arguments sont passés à la console jslint :
lib/jslint/fulljslint.js, à fournir en premier argument. Je ne le charge pas en dur dans jslint-console.js afin de conserver une souplesse d’implémentation (via une tâche Ant par exemple).Voici un exemple de sortie de la console :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $ java -jar lib/rhino/js-1.7R2.jar lib/jslint/jslint-console.js lib/jslint/fulljslint.js src/*.js Running JSLint on: src/jsfile1.js OK Running JSLint on: src/jsfile2.js [ERROR] Expected '===' and instead saw '==' on line 52 character 23. if (false == test) { ..........^ [ERROR] Unexpected dangling '_' in '_ob' on line 74 character 17. var _ob = window.ob; ....^ [ERROR] 'ob' is not defined on line 80 character 39. if ('function' !== typeof ob.getVariables) { ..........................^ [ERROR] 'ob' is not defined on line 83 character 26. params = ob.getVariables().sequence; .........^ => 4 error(s) found. |
Bonjour,
Très intéressé par ce post, j’ai tenté de mettre tout ça en application. Malheureusement, je suis apparement incapable de trouver un “jslint-console.js” qui va bien.
Peut être pourriez vous partager le votre ?
Merci pour votre post, rophle
Le code source présenté est celui du fichier
jslint-console.js. J’ai ajouté un lien de téléchargement direct.Merci !
Je reviens pour vous signaler ce qui me semble être une petite erreur dans votre script.
J’ai été embêté par une erreur “js: Inappropriate array length.” lors de l’analyse de mes scripts.
Pour corriger cette erreur, j’ai modifié la méthode repeat comme suit :
En effet, d’après mon analyse, la string posant problème était ” // check for the input hidden to get the id” (avec espaces et tabs mixés en début de chaine) en effet, je me retrouvais avec un “indentLen” à 17 après “(e.evidence || ”).replace(/^(\s)(\S(\s+\S+))\s$/, cleanEvidence)” alors que “e.character” ne valait que 16, donc le “(e.character - indentLen - 1)” de la ligne suivante valait -2 ! Et donc paf !
J’espère avoir été un minimum clair dans ces explications.
En tout cas, encore merci pour ce script, c’est diablement pratique !
J’avais rencontré et fixé le problème dans un ensemble d’outils de manipulation d’objets String qui sera publié sous peu sur le blog.
Merci pour cette piqûre de rappel, j’avais complètement zappé de répercuter le bugfix dans la console JSLint, désolé :-s