Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(api): saveHTMLOnDisk option #398

Merged
merged 1 commit into from
Jul 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -210,12 +210,22 @@ export interface ReportChart {
}

export interface ReportOptions {
/**
* Location where the report will be saved.
*
* If not provided, default to cwd if HTML or PDF is saved on disk, or a temp directory else.
*/
reportOutputLocation?: string | null;
/**
* Save the PDF on disk (in the current working directory)
* Save the PDF on disk
* @default false
*/
savePDFOnDisk?: boolean;
/**
* Save the HTML on disk
* @default false
*/
saveHTMLOnDisk?: boolean;
}
```

Expand Down
47 changes: 40 additions & 7 deletions src/api/report.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,27 +7,60 @@ import fs from "node:fs/promises";
import { buildStatsFromNsecurePayloads } from "../analysis/extractScannerData.js";
import { HTML, PDF } from "../reporting/index.js";

/**
* Determine the final location of the report (on current working directory or in a temporary directory)
* @param {string} location
* @param {object} options
* @param {boolean} options.includesPDF
* @param {boolean} options.savePDFOnDisk
* @param {boolean} options.saveHTMLOnDisk
* @returns {Promise<string>}
*/
async function reportLocation(location, options) {
const {
includesPDF,
savePDFOnDisk,
saveHTMLOnDisk
} = options;

if (location) {
return location;
}

if ((includesPDF && savePDFOnDisk) || saveHTMLOnDisk) {
return process.cwd();
}

return fs.mkdtemp(path.join(os.tmpdir(), "nsecure-report-"));
}

export async function report(
scannerDependencies,
reportConfig,
reportOptions = Object.create(null)
) {
const {
reportOutputLocation = null,
savePDFOnDisk = false
savePDFOnDisk = false,
saveHTMLOnDisk = false
} = reportOptions;
const includesPDF = reportConfig.reporters.includes("pdf");
const includesHTML = reportConfig.reporters.includes("html");
if (!includesPDF && !includesHTML) {
throw new Error("At least one reporter must be enabled (pdf or html)");
}

const [pkgStats, finalReportLocation] = await Promise.all([
buildStatsFromNsecurePayloads(scannerDependencies, {
isJson: true,
reportConfig
}),
reportOutputLocation === null ?
fs.mkdtemp(path.join(os.tmpdir(), "nsecure-report-")) :
Promise.resolve(reportOutputLocation)
reportLocation(reportOutputLocation, { includesPDF, savePDFOnDisk, saveHTMLOnDisk })
]);

let reportHTMLPath;
try {
const reportHTMLPath = await HTML(
reportHTMLPath = await HTML(
{
pkgStats,
repoStats: null
Expand All @@ -47,8 +80,8 @@ export async function report(
return reportHTMLPath;
}
finally {
if (reportOutputLocation === null) {
await fs.rm(finalReportLocation, {
if (reportHTMLPath && (!includesHTML || saveHTMLOnDisk === false)) {
await fs.rm(reportHTMLPath, {
force: true,
recursive: true
});
Expand Down
70 changes: 68 additions & 2 deletions test/api/report.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import path from "node:path";
import os from "node:os";
import fs from "node:fs/promises";
import fsSync from "node:fs";
import { describe, test } from "node:test";
import assert from "node:assert";

Expand Down Expand Up @@ -51,8 +52,8 @@ const kReportPayload = {
]
};

describe("(API) report", () => {
test("Given a scanner Payload it should successfully generate a PDF", async() => {
describe("(API) report", { concurrency: 1 }, () => {
test("it should successfully generate a PDF and should not save PDF or HTML", async() => {
const reportOutputLocation = await fs.mkdtemp(
path.join(os.tmpdir(), "test-runner-report-pdf-")
);
Expand All @@ -68,6 +69,34 @@ describe("(API) report", () => {
assert.ok(Buffer.isBuffer(generatedPDF));
assert.ok(isPDF(generatedPDF));

const files = (await fs.readdir(reportOutputLocation, { withFileTypes: true }))
.flatMap((dirent) => (dirent.isFile() ? [dirent.name] : []));
assert.deepEqual(
files,
[]
);
}
finally {
await fs.rm(reportOutputLocation, { force: true, recursive: true });
}
});

test("should save HTML when saveHTMLOnDisk is truthy", async() => {
const reportOutputLocation = await fs.mkdtemp(
path.join(os.tmpdir(), "test-runner-report-pdf-")
);

const payload = await from("sade");

const generatedPDF = await report(
payload.dependencies,
{ ...kReportPayload, reporters: ["pdf", "html"] },
{ reportOutputLocation, saveHTMLOnDisk: true }
);
try {
assert.ok(Buffer.isBuffer(generatedPDF));
assert.ok(isPDF(generatedPDF));

const files = (await fs.readdir(reportOutputLocation, { withFileTypes: true }))
.flatMap((dirent) => (dirent.isFile() ? [dirent.name] : []));
assert.deepEqual(
Expand All @@ -79,6 +108,43 @@ describe("(API) report", () => {
await fs.rm(reportOutputLocation, { force: true, recursive: true });
}
});

test("should save PDF when savePDFOnDisk is truthy", async() => {
const reportOutputLocation = await fs.mkdtemp(
path.join(os.tmpdir(), "test-runner-report-pdf-")
);

const payload = await from("sade");

const generatedPDFPath = await report(
payload.dependencies,
{ ...kReportPayload, reporters: ["pdf", "html"] },
{ reportOutputLocation, savePDFOnDisk: true }
);
try {
assert.ok(typeof generatedPDFPath === "string");
assert.ok(fsSync.existsSync(generatedPDFPath), "when saving PDF, we return the path to the PDF instead of the buffer");

const files = (await fs.readdir(reportOutputLocation, { withFileTypes: true }))
.flatMap((dirent) => (dirent.isFile() ? [dirent.name] : []));
assert.deepEqual(
files,
["test_runner.pdf"]
);
}
finally {
await fs.rm(reportOutputLocation, { force: true, recursive: true });
}
});

test("should throw when no reporter is enabled", async() => {
const payload = await from("sade");

await assert.rejects(
() => report(payload.dependencies, { ...kReportPayload, reporters: [] }),
{ message: "At least one reporter must be enabled (pdf or html)" }
);
});
});

function isPDF(buf) {
Expand Down