All files / src/command run.ts

0% Statements 0/36
0% Branches 0/12
0% Functions 0/7
0% Lines 0/35
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                                                                                                                                                                                   
import { readFile, exists } from "fs";
import { promisify } from "util";
import { relative } from "path";
import ignore from "ignore";
import pick from "lodash/pick";
import flow from "lodash/flow";
import {
  combineParsers,
  parseFiles,
  filterExpired,
  Plugin
} from "@hygiene/core";
import * as reporters from "../reporter";
 
export interface Options {
  json: boolean;
  glob: string;
  ignorePattern?: string;
  ignorePath: string;
  ignore: boolean;
}
 
const readFileAsync = promisify(readFile);
const existsAsync = promisify(exists);
 
export const createFilter = async ({
  ignorePattern,
  ignorePath,
  cwd
}: {
  ignorePattern?: string;
  ignorePath: string;
  cwd: string;
}) => {
  const blacklist = ignore();
  if (ignorePath) {
    if (await existsAsync(ignorePath)) {
      // TODO: Verbose logging
      blacklist.add(await readFileAsync(ignorePath, "utf8"));
    } else {
      // TODO: Verbose logging
    }
  }
  if (ignorePattern) {
    // TODO: Verbose logging
    blacklist.add(ignorePattern);
  }
 
  // https://www.npmjs.com/package/ignore#1-pathname-should-be-a-pathrelative-d-pathname
  return flow(
    (path: string) => relative(cwd, path),
    (path: string) => {
      try {
        return !blacklist.ignores(path);
      } catch (e) {
        if (e.message.includes("relative")) {
          return true;
        }
 
        throw e;
      }
    }
  );
};
 
export const run = ({ plugins }: { plugins: Plugin<any, any>[] }) => async (
  argv: Options
) => {
  const { glob, json, ignore, ignorePattern, ignorePath } = argv;
 
  const bodyParser = combineParsers(...plugins);
  const report = json ? reporters.json : reporters.text;
  const filter = ignore
    ? await createFilter({
        ignorePattern,
        ignorePath,
        cwd: process.cwd()
      })
    : () => true;
  const pluginConfigs = plugins.map(plugin =>
    pick(argv, Object.keys(plugin.getConfigDefinition()))
  );
 
  const comments = await parseFiles(glob, bodyParser, {
    filter
  });
  const expiredComments = await filterExpired(comments, plugins, pluginConfigs);
  return report(expiredComments, plugins, pluginConfigs);
};