ADDED gc_lang/fr/nodejs/api.js Index: gc_lang/fr/nodejs/api.js ================================================================== --- gc_lang/fr/nodejs/api.js +++ gc_lang/fr/nodejs/api.js @@ -0,0 +1,253 @@ +/* + ! Grammalecte, grammar checker ! + API pour faciliter l'utilisation de Grammalecte. +*/ + +/* jshint esversion:6, -W097 */ +/* jslint esversion:6 */ +/* global require, exports, console */ + +"use strict"; + +class GrammarChecker { + + constructor(aInit, sPathRoot = "", sLangCode = "fr", sContext = "Javascript") { + this.sLangCode = sLangCode; + this.sPathRoot = sPathRoot; + this.sContext = sContext; + + //Importation des fichiers nécessaire + this._helpers = require(sPathRoot + "/graphspell/helpers.js"); + + this.isInit = { + Grammalecte: false, + Graphspell: false, + Tokenizer: false, + TextFormatter: false, + Lexicographer: false + }; + + if (aInit){ + this.load(aInit); + } + } + + //Auto-chargement avec dépendence + load(aInit = ["Grammalecte", "Graphspell", "TextFormatter", "Lexicographer", "Tokenizer"]){ + //aInit permet de charger que certain composant + // => évite de charger toutes données si par exemple on a besoin que du lexigraphe + // => sorte de gestionnaire de dépendence (peut être amélioré) + this.isInit = {}; + if ( aInit.indexOf("Grammalecte") !== false ){ + //console.log('init Grammalecte'); + this._oGce = require(this.sPathRoot + "/fr/gc_engine.js"); + this._oGce.load(this.sContext); + this.isInit.Grammalecte = true; + this.oSpellChecker = this._oGce.getSpellChecker(); + this.isInit.Graphspell = true; + this.oTokenizer = this.oSpellChecker.getTokenizer(); + this.isInit.Tokenizer = true; + } + + if ( !this.isInit.Graphspell && (aInit.indexOf("Graphspell") !== false || aInit.indexOf("Lexicographer") !== false)){ + //console.log('init Graphspell'); + this._SpellChecker = require(this.sPathRoot + "/graphspell/spellchecker.js"); + this.oSpellChecker = new this._SpellChecker.SpellChecker(this.sLangCode, this.sPathRoot + "/graphspell/_dictionaries"); + this.isInit.Graphspell = true; + this.oTokenizer = this.oSpellChecker.getTokenizer(); + this.isInit.Tokenizer = true; + } + + if ( !this.isInit.Tokenizer && aInit.indexOf("Tokenizer") !== false ){ + //console.log('init Tokenizer'); + this._Tokenizer = require(this.sPathRoot + "/graphspell/tokenizer.js"); + this.oTokenizer = new this._Tokenizer.Tokenizer(this.sLangCode); + this.isInit.Tokenizer = true; + } + + if ( aInit.indexOf("TextFormatter") !== false ){ + //console.log('init TextFormatter'); + this._oText = require(this.sPathRoot + "/fr/textformatter.js"); + this.oTextFormatter = new this._oText.TextFormatter(); + this.isInit.TextFormatter = true; + } + + if ( aInit.indexOf("Lexicographer") !== false ){ + //console.log('init Lexicographer'); + this._oLex = require(this.sPathRoot + "/fr/lexicographe.js"); + this.oLexicographer = new this._oLex.Lexicographe( + this.oSpellChecker, + this.oTokenizer, + this._helpers.loadFile(this.sPathRoot + "/fr/locutions_data.json") + ); + this.isInit.Lexicographer = true; + } + } + + //Fonctions concernant: Grammalecte + getGrammalecte(){ + if (!this.isInit.Grammalecte) { + this.load(["Grammalecte"]); + } + return this._oGce; + } + + gramma(sText){ + if (!this.isInit.Grammalecte) { + this.load(["Grammalecte"]); + } + return Array.from(this._oGce.parse(sText, this.sLangCode)); + } + + getGceOptions () { + if (!this.isInit.Grammalecte) { + this.load(["Grammalecte"]); + } + return this._helpers.mapToObject(this._oGce.getOptions()); + } + + getGceDefaultOptions () { + if (!this.isInit.Grammalecte) { + this.load(["Grammalecte"]); + } + return this._helpers.mapToObject(this._oGce.getDefaultOptions()); + } + + setGceOptions (dOptions) { + if (!this.isInit.Grammalecte) { + this.load(["Grammalecte"]); + } + if (!(dOptions instanceof Map)) { + dOptions = this._helpers.objectToMap(dOptions); + } + this._oGce.setOptions(dOptions); + return this._helpers.mapToObject(this._oGce.getOptions()); + } + + setGceOption (sOptName, bValue) { + if (!this.isInit.Grammalecte) { + this.load(["Grammalecte"]); + } + if (sOptName) { + this._oGce.setOption(sOptName, bValue); + return this._helpers.mapToObject(this._oGce.getOptions()); + } + } + + resetOptions () { + if (!this.isInit.Grammalecte) { + this.load(["Grammalecte"]); + } + this._oGce.resetOptions(); + return this._helpers.mapToObject(this._oGce.getOptions()); + } + + //Fonctions concernant: Graphspell + getGraphspell(){ + if (!this.isInit.Graphspell) { + this.load(["Graphspell"]); + } + return this.oSpellChecker; + } + + spellParagraph(sText, bSuggest = true){ + if (!this.isInit.Graphspell) { + this.load(["Graphspell"]); + } + if (bSuggest){ + let lError = this.oSpellChecker.parseParagraph(sText); + for (let token of lError) { + token.aSuggestions = this.suggest(token.sValue); + } + return lError; + } else { + return this.oSpellChecker.parseParagraph(sText); + } + } + + spell(sWord){ + if (!this.isInit.Graphspell) { + this.load(["Graphspell"]); + } + return this.oSpellChecker.isValid(sWord); + } + + suggest(sWord, nbLimit = 10, bMerge = true){ + if (!this.isInit.Graphspell) { + this.load(["Graphspell"]); + } + let lSuggest = this.oSpellChecker.suggest(sWord, nbLimit); + if (bMerge){ + let lSuggestRep = []; + for (let lSuggestTmp of lSuggest) { + for (let word of lSuggestTmp) { + lSuggestRep.push(word); + } + } + return lSuggestRep; + } else { + return Array.from(lSuggest); + } + + } + + lemma(sWord){ + if (!this.isInit.Graphspell) { + this.load(["Graphspell"]); + } + return this.oSpellChecker.getLemma(sWord); + } + + morph(sWord){ + if (!this.isInit.Graphspell) { + this.load(["Graphspell"]); + } + return this.oSpellChecker.getMorph(sWord); + } + + //Fonctions concernant: Lexicographer + getLexicographer(){ + if (!this.isInit.Lexicographer) { + this.load(["Lexicographer"]); + } + return this.oLexicographer; + } + + lexique(sText){ + if (!this.isInit.Lexicographer) { + this.load(["Lexicographer"]); + } + return this.oLexicographer.getListOfTokensReduc(sText); + } + + //Fonctions concernant: TextFormatter + getTextFormatter(){ + if (!this.isInit.TextFormatter) { + this.load(["TextFormatter"]); + } + return this.oTextFormatter; + } + + formatText(sText){ + if (!this.isInit.TextFormatter) { + this.load(["TextFormatter"]); + } + return this.oTextFormatter.formatText(sText); + } + + //fonctions concernant plussieurs parties + verifParagraph(sText, bSuggest = true){ + if (!this.isInit.Grammalecte || !this.isInit.Graphspell) { + this.load(["Grammalecte"]); + } + return { + lGrammarErrors: Array.from(this._oGce.parse(sText, this.sLangCode)), + lSpellingErrors: this.spellParagraph(sText, bSuggest) + }; + } + +} + +if (typeof exports !== "undefined") { + exports.GrammarChecker = GrammarChecker; +} ADDED gc_lang/fr/nodejs/gramma-cli.bat Index: gc_lang/fr/nodejs/gramma-cli.bat ================================================================== --- gc_lang/fr/nodejs/gramma-cli.bat +++ gc_lang/fr/nodejs/gramma-cli.bat @@ -0,0 +1,1 @@ +@node gramma-cli.js %* ADDED gc_lang/fr/nodejs/gramma-cli.js Index: gc_lang/fr/nodejs/gramma-cli.js ================================================================== --- gc_lang/fr/nodejs/gramma-cli.js +++ gc_lang/fr/nodejs/gramma-cli.js @@ -0,0 +1,537 @@ +// Gramma-Cli +// Grammalect client pour node + +/* jshint esversion:6, -W097 */ +/* jslint esversion:6 */ +/* global require, console */ + +/* +Doc : +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment +https://stackoverflow.com/questions/41058569/what-is-the-difference-between-const-and-const-in-javascript +*/ + +const argCmd = require("./minimist.js")(process.argv.slice(2)); +const { performance } = require("perf_hooks"); + +var repJson = false; +var repPerf = false; + +var sBufferConsole = ""; +var sCmdToExec = ""; + +var cmdAction = { + help: { + short: "", + description: "Affichie les informations que vous lisez ;)", + execute: "" + }, + perf: { + short: "", + description: "(on/off) Permet d'afficher le temps d'exécution des commandes.", + execute: "" + }, + json: { + short: "", + description: "(on/off) Réponse en format format json.", + execute: "" + }, + exit: { + short: "", + description: "Client intéractif: Permet de le quitter.", + execute: "" + }, + text: { + short: "", + description: "Client / Server: Définir un texte pour plusieurs actions.", + execute: "" + }, + gceoption: { + short: "", + description: "Défini une option a utilisé par le correcteur de grammaire.", + execute: "" + }, + format: { + short: "", + description: "Permet de mettre en forme le texte.", + execute: "formatText" + }, + check: { + short: "", + description: "Vérifie la grammaire et l'orthographe d'un texte.", + execute: "verifParagraph" + }, + lexique: { + short: "", + description: "Affiche le lexique du texte.", + execute: "lexique" + }, + spell: { + short: "", + description: "Vérifie l'existence d'un mot.", + execute: "spell" + }, + suggest: { + short: "", + description: "Suggestion des orthographes possible d'un mot.", + execute: "suggest" + }, + morph: { + short: "", + description: "Affiche les informations pour un mot.", + execute: "morph" + }, + lemma: { + short: "", + description: "Donne le lemme d'un mot.", + execute: "lemma" + } +}; + +var cmdOne = ["json", "perf", "help", "exit"]; +var cmdMulti = ["text", "format", "check", "lexique", "spell", "suggest", "morph", "lemma"]; + +var cmdAll = [...cmdOne, ...cmdMulti]; + +function getArgVal(aArg, lArgOk) { + for (let eArgOk of lArgOk) { + if (typeof aArg[eArgOk] !== "undefined") { + return aArg[eArgOk]; + } + } + return false; +} + +function getArg(aArg, lArgOk) { + for (let eArgOk of lArgOk) { + if (typeof aArg[eArgOk] !== "undefined") { + return true; + } + } + return false; +} + +function toBool(aStr) { + return aStr === "true" || aStr === "on"; +} + +function isBool(aStr) { + if (typeof aStr === "boolean" || typeof aStr === "undefined") { + return true; + } + aStr = aStr.toLowerCase(); + return aStr === "true" || aStr === "on" || aStr === "false" || aStr === "off" || aStr === ""; +} + +function toTitle(aStr) { + return aStr.charAt(0).toUpperCase() + aStr.slice(1); +} + +function repToText(oRep) { + //console.log(oRep); + let repText = ""; + for (const action of ["Json", "Perf", "GceOption"]) { + if (action in oRep) { + repText += toTitle(action) + " " + oRep[action]; + } + } + + for (const action of ["morph", "lemma"]) { + if (action in oRep) { + if (oRep[action] == "NoText") { + repText += "\n" + toTitle(action) + ": Pas de texte à vérifier."; + } else { + if (oRep[action].length == 0) { + repText += "\nAuncun " + toTitle(action) + " existant pour: " + oRep.text; + } else { + let ascii = "├"; + let numRep = 0; + repText += "\n" + toTitle(action) + " possible de: " + oRep.text; + for (let reponse of oRep[action]) { + numRep++; + if (numRep == oRep[action].length) { + ascii = "└"; + } + repText += "\n " + ascii + " " + reponse; + } + } + } + } + } + + if ("spell" in oRep) { + if (oRep.spell == "NoText") { + repText += "\nSpell: Pas de texte à vérifier."; + } else { + repText += "\nLe mot " + (oRep.spell || oRep.text) + " " + (oRep.spell ? "existe" : "innexistant"); + } + } + + if ("format" in oRep) { + if (oRep.spell == "NoText") { + repText += "\nPas de texte à formatter."; + } else { + repText += "\nMise en forme:\n" + (oRep.format || oRep.text); + } + } + + if ("suggest" in oRep) { + if (oRep.suggest == "NoText") { + repText += "\nSuggest : Pas de texte à vérifier."; + } else { + //let numgroup = 0; + if (oRep.suggest.length == 0) { + repText += "\nAucune suggestion possible pour: " + oRep.text; + } else { + repText += "\nSuggestion possible de: " + oRep.text; + let ascii = "├"; + let numRep = 0; + for (let reponse of oRep.suggest) { + numRep++; + if (numRep == oRep.suggest.length) { + ascii = "└"; + } + repText += "\n " + ascii + " " + reponse; + } + } + } + } + + if ("lexique" in oRep) { + if (oRep.lexique == "NoText") { + repText += "\nLexique: Pas de texte à vérifier."; + } else { + repText += "\nLexique:"; + for (let reponse of oRep.lexique) { + repText += "\n" + reponse.sValue; + let ascii = "├"; + let numRep = 0; + for (let label of reponse.aLabel) { + numRep++; + if (numRep == reponse.aLabel.length) { + ascii = "└"; + } + repText += "\n " + ascii + " " + label; + } + } + } + } + + if ("check" in oRep) { + if (oRep.check == "NoText") { + repText += "\nCheck: Pas de texte à vérifier."; + } else { + let ascii1, ascii1a, numRep1, ascii2, numRep2, replength; + + ascii1 = "├"; + ascii1a = "│"; + numRep1 = 0; + replength = Object.keys(oRep.check.lGrammarErrors).length; + if (replength == 0) { + repText += "\nPas de faute de grammaire"; + } else { + repText += "\nFaute(s) de grammaire"; + for (let gramma of oRep.check.lGrammarErrors) { + numRep1++; + if (numRep1 == replength) { + ascii1 = "└"; + ascii1a = " "; + } + repText += "\n " + ascii1 + " " + gramma.nStart + "->" + gramma.nEnd + " " + gramma.sMessage; + ascii2 = "├"; + numRep2 = 0; + for (let suggestion of gramma.aSuggestions) { + numRep2++; + if (numRep2 == gramma.aSuggestions.length) { + ascii2 = "└"; + } + repText += "\n " + ascii1a + " " + ascii2 + ' "' + suggestion + '"'; + } + } + } + + ascii1 = "├"; + ascii1a = "│"; + numRep1 = 0; + replength = Object.keys(oRep.check.lSpellingErrors).length; + if (replength == 0) { + repText += "\nPas de faute d'orthographe"; + } else { + repText += "\nFaute(s) d'orthographe"; + for (let ortho of oRep.check.lSpellingErrors) { + numRep1++; + if (numRep1 == replength) { + ascii1 = "└"; + ascii1a = " "; + } + repText += "\n " + ascii1 + " " + ortho.nStart + "->" + ortho.nEnd + " " + ortho.sValue; + ascii2 = "├"; + numRep2 = 0; + for (let suggestion of ortho.aSuggestions) { + numRep2++; + if (numRep2 == ortho.aSuggestions.length) { + ascii2 = "└"; + } + repText += "\n " + ascii1a + " " + ascii2 + ' "' + suggestion + '"'; + } + } + } + } + } + + + if ("help" in oRep) { + let colorNum = 31; + for (const action of oRep.help) { + //Uniquement pour le fun on met de la couleur ;) + if(action.indexOf('===')>-1){ + console.log("\x1b["+colorNum+"m"+action+"\x1b[0m"); + colorNum = colorNum + 2; + } else { + console.log(action); + } + } + } + + if (oRep.time) { + repText += "\nExécuté en: " + oRep.time + " ms"; + } + return repText.trim("\n"); +} + +var sWord = ""; +var actionToExec = function(aArg) { + let repAction = {}; + let tStart, tEnd; + + if (!isBool(aArg.text)) { + sWord = aArg.text; + } + + repAction["text"] = sWord; + + if (getArg(aArg, ["json"])) { + repJson = getArgVal(aArg, ["json"]); + repAction["Json"] = repJson ? "ON" : "OFF"; + } + + if (getArg(aArg, ["perf"])) { + repPerf = getArgVal(aArg, ["perf"]); + repAction["Perf"] = repPerf ? "ON" : "OFF"; + } + + if (repPerf) { + tStart = performance.now(); + } + + if (getArg(aArg, ["gceoption"])) { + let sOpt = sWord.split(" "); + if (sOpt[0] == "reset") { + oGrammarChecker.resetGceOptions(); + repAction["GceOption"] = "reset"; + } else { + let bOptVal = toBool(sOpt[1]); + oGrammarChecker.setGceOption(sOpt[0], bOptVal); + repAction["GceOption"] = sOpt[0] + " " + (bOptVal ? "ON" : "OFF"); + } + } + + for (const action in aArg) { + if (cmdAction[action] && cmdAction[action].execute !== "") { + if (!isBool(aArg[action]) && aArg[action] !== "") { + repAction.text = aArg[action]; + sWord = repAction.text; + } + if (!isBool(repAction.text)) { + repAction[action] = oGrammarChecker[cmdAction[action].execute](repAction.text); + } else { + repAction[action] = "NoText"; + } + } + } + + if (getArg(aArg, ["help"])) { + repAction["help"] = []; + + repAction["help"].push("================================== Aide: =================================="); + repAction["help"].push(""); + repAction["help"].push("Il y a trois modes de fonctionnement: client / client intératif / serveur."); + + repAction["help"].push(" * le client intéractif: «gramma-cli -i»."); + repAction["help"].push(" * pour le client exemple: «gramma-cli --command \"mot/texte\"»."); + repAction["help"].push(" * le serveur se lance avec la commande «gramma-cli --server --port 8085»."); + + repAction["help"].push(""); + repAction["help"].push("========================= Les commandes/arguments: ========================"); + repAction["help"].push(""); + for (const action in cmdAction) { + repAction["help"].push(action.padEnd(15, ' ') + ': ' + cmdAction[action].description); + } + repAction["help"].push(""); + repAction["help"].push("================================== Note: =================================="); + repAction["help"].push(""); + repAction["help"].push("En mode client: les arguments sont de la forme «--argument» !"); + repAction["help"].push("En mode client intéractif: pour les commandes concernant un texte, vous"); + repAction["help"].push(" pouvez taper la commande puis entrer (pour saisir le texte) pour "); + repAction["help"].push(" terminer la saisie du texte et exécuter la commande taper /\"commande\""); + } + + if (repPerf) { + tEnd = performance.now(); + //On ajoute l"information au résultat + repAction["time"] = (Math.round((tEnd - tStart) * 1000) / 1000).toString(); + } + + if (repJson) { + return JSON.stringify(repAction); + } else { + return repToText(repAction); + } +}; + +function argToExec(aCommand, aText, rl, resetCmd = true){ + let execAct = {}; + aCommand = aCommand.toLowerCase(); + + if (!isBool(aText)) { + execAct["text"] = aText; + execAct[aCommand] = true; + } else { + execAct[aCommand] = toBool(aText); + } + + console.log(actionToExec(execAct)); + //sBufferConsole = ""; + if (resetCmd){ + sCmdToExec = ""; + } + + if (typeof(rl) !== "undefined"){ + rl.setPrompt("\x1b[36mGrammaJS\x1b[33m>\x1b[0m "); + } +} + +function completer(line) { + var hits = cmdAll.filter(function(c) { + if (c.indexOf(line) == 0) { + return c; + } + }); + return [hits && hits.length ? hits : cmdAll, line]; +} + +if (process.argv.length <= 2) { + console.log(actionToExec({help:true})); +} else { + var GrammarChecker = require("./api.js"); + var oGrammarChecker = new GrammarChecker.GrammarChecker( + ["Grammalecte", "Graphspell", "TextFormatter", "Lexicographer", "Tokenizer"], + __dirname + "/grammalecte/", + "fr" + ); + + if (argCmd.server) { + var http = require("http"); + var url = require("url"); + var querystring = require("querystring"); + + var collectRequestData = function(aRequest, aResponse, callback) { + let sBody = ""; + aRequest.on("data", chunk => { + sBody += chunk.toString(); + }); + aRequest.on("end", () => { + let oParams = querystring.parse(sBody); + //console.log(oParams /*, page*/); + callback(querystring.parse(sBody), aResponse); + }); + }; + + var reponseRequest = function(aParms, aResponse) { + aResponse.setHeader("access-control-allow-origin", "*"); + aResponse.writeHead(200, { "Content-Type": "application/json" }); + aParms["json"] = true; //Forcage de la réponse en json + aResponse.write(actionToExec(aParms)); + aResponse.end(); + }; + + var server = http.createServer(function(aRequest, aResponse) { + var sPage = url.parse(aRequest.url).pathname; + if (sPage !== "/") { + //favicon.ico + aResponse.writeHead(404, { "Content-Type": "text/plain" }); + aResponse.write("Error 404"); + aResponse.end(); + } else { + if (aRequest.method === "POST") { + collectRequestData(aRequest, aResponse, reponseRequest); + } else { + let oParams = querystring.parse(url.parse(aRequest.url).query); + reponseRequest(oParams, aResponse); + } + } + }); + server.listen(argCmd.port || 2212); + console.log("Server started on http://127.0.0.1:" + (argCmd.port || 2212) + "/"); + } else if (getArg(argCmd, ["i", "interactive"])) { + const readline = require("readline"); + const reg = /(.*?) (.*)/gm; + + process.stdin.setEncoding("utf8"); + + const rl = readline.createInterface({ + crlfDelay: Infinity, + input: process.stdin, + output: process.stdout, + completer: completer, + prompt: "\x1b[36mGrammaJS\x1b[33m>\x1b[0m " + }); + //console.log( process.stdin.isTTY ); + process.stdout.write("\x1b[31mBienvenu sur Grammalecte pour NodeJS!!!\x1b[0m\n"); + rl.prompt(); + rl.on("line", sBuffer => { + //process.stdout.write + if (sBuffer == "exit") { + console.log("\x1b[31m\x1b[5m\x1b[5mBye bye!\x1b[0m"); + process.exit(0); + } + + let lg = sBuffer.toLowerCase().trim(); + let bSpace = lg.indexOf(" ") > -1; + //sBufferConsole + //console.log("\""+sBuffer+"\""); + if (!bSpace) { + //console.log("=> ", lg.slice(0, lg.length-1), cmdAll.indexOf( lg.slice(-1) )); + if (cmdOne.indexOf(lg) > -1){ + argToExec(lg, sBuffer, rl, true); + } else if (cmdAll.indexOf(lg) > -1) { + sBufferConsole = ""; + sCmdToExec = lg; + //Prompt simple pour distinguer que c"est une suite d"une commande + rl.setPrompt("\x1b[33m>\x1b[0m "); + } else if (lg.slice(1) == sCmdToExec) { + argToExec(sCmdToExec, sBufferConsole, rl, true); + } else if (cmdAll.indexOf(lg.slice(0, lg.length - 1)) > -1) { + argToExec(lg.slice(0, lg.length - 1), sBufferConsole, rl, true); + } else if (lg == "") { + sBufferConsole += "\n"; + } + } else if (sCmdToExec == "") { + let regRep = /(.*?) (.*)/gm.exec(sBuffer); + //console.log(regRep.length,sBuffer); + if (regRep && regRep.length == 3) { + argToExec(regRep[1], regRep[2]); + } + } else { + sBufferConsole += sBuffer + "\n"; + } + + rl.prompt(); + }).on("close", () => { + console.log("\n\x1b[31m\x1b[5mBye bye!\x1b[0m"); + process.exit(0); + }); + } else { + console.log(actionToExec(argCmd)); + } +} ADDED gc_lang/fr/nodejs/minimist.js Index: gc_lang/fr/nodejs/minimist.js ================================================================== --- gc_lang/fr/nodejs/minimist.js +++ gc_lang/fr/nodejs/minimist.js @@ -0,0 +1,236 @@ +module.exports = function (args, opts) { + if (!opts) opts = {}; + + var flags = { bools : {}, strings : {}, unknownFn: null }; + + if (typeof opts['unknown'] === 'function') { + flags.unknownFn = opts['unknown']; + } + + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { + flags.allBools = true; + } else { + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + + var defaults = opts['default'] || {}; + + var argv = { _ : [] }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--')+1); + args = args.slice(0, args.indexOf('--')); + } + + function argDefined(key, arg) { + return (flags.allBools && /^--[^=]+$/.test(arg)) || + flags.strings[key] || flags.bools[key] || aliases[key]; + } + + function setArg (key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + + var value = !flags.strings[key] && isNumber(val) + ? Number(val) : val + ; + setKey(argv, key.split('.'), value); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + function setKey (obj, keys, value) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + if (o[key] === undefined) o[key] = {}; + o = o[key]; + }); + + var key = keys[keys.length - 1]; + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { + o[key] = value; + } + else if (Array.isArray(o[key])) { + o[key].push(value); + } + else { + o[key] = [ o[key], value ]; + } + } + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + var key = m[1]; + var value = m[2]; + if (flags.bools[key]) { + value = value !== 'false'; + } + setArg(key, value, arg); + } + else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } + else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + if (next !== undefined && !/^-/.test(next) + && !flags.bools[key] + && !flags.allBools + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, next, arg); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1,-1).split(''); + + var broken = false; + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j+2); + + if (next === '-') { + setArg(letters[j], next, arg) + continue; + } + + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split('=')[1], arg); + broken = true; + break; + } + + if (/[A-Za-z]/.test(letters[j]) + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j+1] && letters[j+1].match(/\W/)) { + setArg(letters[j], arg.slice(j+2), arg); + broken = true; + break; + } + else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + var key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) + && !flags.bools[key] + && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, args[i+1], arg); + i++; + } + else if (args[i+1] && /true|false/.test(args[i+1])) { + setArg(key, args[i+1] === 'true', arg); + i++; + } + else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } + else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push( + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) + ); + } + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + break; + } + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + if (opts['--']) { + argv['--'] = new Array(); + notFlags.forEach(function(key) { + argv['--'].push(key); + }); + } + else { + notFlags.forEach(function(key) { + argv._.push(key); + }); + } + + return argv; +}; + +function hasKey (obj, keys) { + var o = obj; + keys.slice(0,-1).forEach(function (key) { + o = (o[key] || {}); + }); + + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber (x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + ADDED gc_lang/fr/nodejs/readme.md Index: gc_lang/fr/nodejs/readme.md ================================================================== --- gc_lang/fr/nodejs/readme.md +++ gc_lang/fr/nodejs/readme.md @@ -0,0 +1,127 @@ +# Client/Serveur de Grammalecte pour NodeJS + +## Aide + +Il y a trois modes de fonctionnement: client / client intératif / serveur. + +* Client intéractif: «gramma-cli -i». +* Client: «gramma-cli --command \"mot/texte\"». +* Serveur: lancé avec la commande «gramma-cli --server --port NumPort». + +## Commandes + +* help : Affichie les informations que vous lisez ;) +* perf : Permet d'afficher le temps d'exécution des commandes. +* json : Réponse en format format json. +* exit : Client intéractif: Permet de le quitter. +* format : Permet de mettre en forme le texte. +* check : Vérifie la grammaire et l'orthographe d'un texte. +* lexique : Affiche le lexique du texte. +* spell : Vérifie l'existence d'un mot. +* suggest : Suggestion des orthographes possible d'un mot. +* morph : Affiche les informations pour un mot. +* lemma : Donne le lemme d'un mot. +* text : Client / Server: Définir un texte pour plusieurs actions. +* gceoption : Défini une option a utilisé par le correcteur de grammaire. + +## Client intéractif + +Pour le lancé vous devez saisir «gramma-cli -i», il est un mode question/réponse. + +Exemple pour les vérifications portant sur un mot: + +``` +CMD> gramma-cli -i +Bienvenu sur Grammalecte pour NodeJS!!! +GrammaJS> suggest salit +Suggestion possible de: salit + ├ salit + ├ salît + ├ salie + ├ salis + ├ salir + ├ salin + ├ sali + ├ salait + ├ salut + └ salât +GrammaJS> exit +``` + +Exemple pour les vérifications portant sur un texte: +``` +CMD> gramma-cli -i +Bienvenu sur Grammalecte pour NodeJS!!! +GrammaJS> format +> salut,les copains!!! +> vous allez bien ? +> /format +Mise en forme: +salut, les copains!!! +vous allez bien ? +GrammaJS> exit +``` + +**Note : Vous pouvez vérifier tout un fichier avec pour chaque ligne ayant une commande :** +**cat script.verf | gramma-cli -i** + + +## Client + +Exemple simple: +``` +CMD> gramma-cli --spell saluti +Le mot saluti innexistant + +CMD> +``` + +Exemple faisant plusiseurs action: +``` +CMD> gramma-cli --lemma --morph --suggest --text salut +Morph possible de: salut + └ >salut/:N:m:s/* +Lemma possible de: salut + └ salut +Suggestion possible de: salut + ├ salut + ├ salit + ├ salue + ├ salua + ├ saluai + ├ saluts + ├ salué + ├ saluât + ├ salât + └ salît + +CMD> +``` + +## Serveur + +Le serveur supporte les requêtes POST et GET... + +## Les fichiers + +grammalecte/* : Tout le contennu de Grammalecte pour javascript + +api.js : Un warper pour simplifié l'utilisation de Grammalecte + +gramma-cli.bat : Fait juste un appel «node gramma-cli.js .argument(s)» + +gramma-cli.js : Le code principale pour la console + +minimist.js : Une librairie pour simplifier le parssage des arguments + +readme.md : Le fichier que vous lisez (ou pas) actuellement ;) + +script.verf : Exemple de script pour faire des vérifications automatiques + +* (sous widows) type script.verf | gramma-cli -i +* (sous linux) cat script.verf | gramma-cli -i + + +## Utilisation d'une librairie (incluse) + +* [Minimist](https://github.com/substack/minimist) => Simplify parser argument ADDED gc_lang/fr/nodejs/script.verf Index: gc_lang/fr/nodejs/script.verf ================================================================== --- gc_lang/fr/nodejs/script.verf +++ gc_lang/fr/nodejs/script.verf @@ -0,0 +1,13 @@ +json false +perf true +spell salut +suggest salut +morph salut +lemma salut +gceoption typo false +check +salut comment,il vas???bienss et tu! salut commentss il vas??? +/check +gceoption typo true +check/ +lexique/