summaryrefslogtreecommitdiff
path: root/src/actions/checkDependencies.ts
blob: 4234bf98b1518f585a40bbaac6e2644928c29d19 (plain) (blame)
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
import fs from "fs/promises";
import ora, { type Ora } from "ora";
import type { Config, Project } from "../types.js";
import { getConfig } from "../utils/config.js";
import { exec, type ExecException } from "child_process";

export async function checkDependencies() {
  const spinner = ora("Getting all Project Data").start();

  const config: Config = await getConfig();
  let projectAudits: PromiseSettledResult<Project>[];
  let projects: Promise<Project>[] = [];

  try {
    const entries = await fs.readdir(config.path, { withFileTypes: true });

    for (let entry of entries) {
      if (!entry.isDirectory()) {
        continue;
      }

      let dirFullPath = `${config.path}${entry.name}`;
      const projectDir = await fs.readdir(dirFullPath);

      if (projectDir.includes("package.json")) {
        let auditPromise = getAuditPromise(dirFullPath, entry.name, spinner);
        projects.push(auditPromise);
      }
    }

    projectAudits = await Promise.allSettled(projects);

    spinner.succeed("Got the Data successfully");

    return projectAudits;
  } catch (error) {
    spinner.fail("Ups and Error :(");
    throw error;
  }
}

async function getAuditPromise(
  path: string,
  dirname: string,
  spinner: Ora,
): Promise<Project> {
  await pullLatest(path, spinner);

  spinner.text = "getting audit";

  let { stdout } = await promiseExec(`cd "${path}" && npm audit --json`);

  let output = JSON.parse(stdout);
  let project: Project = { projectName: dirname, ...output };
  if (project.error) {
    throw new Error(
      `${dirname} could not be audited, maybe package lock is corrupted`,
    );
  }

  return project;
}

async function pullLatest(path: string, spinner: Ora) {
  spinner.text = "pulling latest";
  await promiseExec(`cd "${path}" && git pull`);
}

function promiseExec(
  cmd: string,
): Promise<{ error: ExecException | null; stdout: string; stderr: string }> {
  return new Promise((resolve, _) => {
    exec(cmd, (error, stdout, stderr) => {
      resolve({ error, stdout, stderr });
    });
  });
}