Skip to content

Commit

Permalink
refactor(build): move file extension check into filecheck
Browse files Browse the repository at this point in the history
  • Loading branch information
caugner committed Nov 28, 2022
1 parent 292f322 commit bf748cb
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 18 deletions.
19 changes: 1 addition & 18 deletions build/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import zlib from "node:zlib";
import chalk from "chalk";
import cliProgress from "cli-progress";
import { program } from "@caporal/core";
import FileType from "file-type";
import { prompt } from "inquirer";

import { Document, slugToFolder, translationsOf } from "../content";
Expand Down Expand Up @@ -221,23 +220,7 @@ async function buildDocuments(
}

for (const filePath of fileAttachments) {
// Ensure that binary files contain what their extension indicates.
if (/\.(mp3|mp4|ttf|webm|woff2?)$/i.test(filePath)) {
const ext = filePath.split(".").pop();
const type = await FileType.fromFile(filePath);
if (!type) {
throw new Error(
`Failed to detect type of file attachment: ${filePath}`
);
}
if (ext.toLowerCase() !== type.ext) {
throw new Error(
`Unexpected type '${type.mime}' (*.${ext}) detected for file attachment: ${filePath}.`
);
}
}

// We *could* use symlinks instead. But, there's no point :
// We *could* use symlinks instead. But, there's no point :)
// Yes, a symlink is less disk I/O but it's nominal.
fs.copyFileSync(filePath, path.join(outPath, path.basename(filePath)));
}
Expand Down
14 changes: 14 additions & 0 deletions filecheck/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,20 @@ export async function checkFile(filePath, options: CheckerOptions = {}) {
);
}

// Ensure that binary files contain what their extension indicates.
if (/\.(mp3|mp4|ttf|webm|woff2?)$/i.test(filePath)) {
const ext = filePath.split(".").pop();
const type = await FileType.fromFile(filePath);
if (!type) {
throw new Error(`Failed to detect type of file attachment: ${filePath}`);
}
if (ext.toLowerCase() !== type.ext) {
throw new Error(
`Unexpected type '${type.mime}' (*.${ext}) detected for file attachment: ${filePath}.`
);
}
}

// FileType can't check for .svg files.
// So use special case for files called '*.svg'
if (path.extname(filePath) === ".svg") {
Expand Down

0 comments on commit bf748cb

Please sign in to comment.