UNPKG

2.79 kBJavaScriptView Raw
1/**
2 * @module
3 * @see {@link https://www.npmjs.com/package/flow-bin|Flow}
4 */
5
6"use strict";
7
8const fs = require("fs").promises;
9const spawn = require("child_process").spawn;
10const flow = require("flow-bin");
11const SEVERITY = require("../severity");
12
13/**
14 * Initialise un checker pour Flow.
15 *
16 * @returns {object} Le patron et les options par défaut.
17 */
18const configure = function () {
19 return {
20 "patterns": "*.js",
21 "linters": { "flow-bin": null }
22 };
23};
24
25/**
26 * Exécute une commande.
27 *
28 * @param {string} command La commande qui sera exécutée.
29 * @param {Array.<string>} args Les arguments passés à l'exécutable.
30 * @param {string} stdin Les données d'entrée.
31 * @returns {Promise.<string>} Les retours de la commande.
32 */
33const exec = function (command, args, stdin) {
34 return new Promise((resolve, reject) => {
35 const child = spawn(command, args);
36 let stdout = "";
37 let stderr = "";
38 child.stdout.on("data", (data) => {
39 stdout += data.toString();
40 });
41 child.stderr.on("data", (data) => {
42 stderr += data.toString();
43 });
44 child.on("close", (code) => {
45 if (0 === code) {
46 resolve(stdout);
47 } else {
48 reject(stderr);
49 }
50 });
51 child.stdin.write(stdin);
52 child.stdin.end();
53 });
54};
55
56/**
57 * Vérifie un fichier avec le linter <strong>Flow</strong>.
58 *
59 * @param {string} file Le fichier qui sera vérifié.
60 * @param {number} level Le niveau de sévérité minimum des notifications
61 * retournées.
62 * @returns {Promise.<Array.<object>>} Une promesse retournant la liste des
63 * notifications.
64 */
65const wrapper = async function (file, level) {
66 if (SEVERITY.ERROR > level) {
67 return [];
68 }
69
70 const source = await fs.readFile(file, "utf-8");
71 const raw = await exec(flow, ["check-contents", "--json", file], source);
72 return JSON.parse(raw).errors
73 .map(({ message }) => {
74 const messages = [];
75 const locations = [];
76 for (const { descr, loc } of message) {
77 messages.push(descr);
78 if (undefined === loc) {
79 continue;
80 }
81 locations.push({
82 "line": loc.start.line,
83 "column": loc.start.column,
84 "lineEnd": loc.end.line,
85 "columnEnd": loc.end.column
86 });
87 }
88
89 return {
90 "file": file,
91 "linter": "flow-bin",
92 "message": messages.join(" "),
93 "locations": locations
94 };
95 });
96};
97
98module.exports = { configure, wrapper };