@ipp/cli
Version:
An image build orchestrator for the modern web
98 lines (97 loc) • 3.31 kB
JavaScript
;
/**
* Image Processing Pipeline - Copyright (c) Marcus Cemes
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.searchForImages = void 0;
const common_1 = require("@ipp/common");
const denque_1 = __importDefault(require("denque"));
const fs_1 = require("fs");
const path_1 = require("path");
const object_stream_1 = require("../lib/stream/object_stream");
const SUPPORTED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".webp", ".tiff", ".gif", ".svg"];
var Type;
(function (Type) {
Type[Type["FILE"] = 0] = "FILE";
Type[Type["DIRECTORY"] = 1] = "DIRECTORY";
})(Type || (Type = {}));
function searchForImages(paths) {
return (0, object_stream_1.createObjectStream)(searchPaths(paths));
}
exports.searchForImages = searchForImages;
async function* searchPaths(paths) {
for (const path of paths) {
for await (const result of searchPath(path)) {
yield result;
}
}
}
async function* searchPath(path) {
switch (await getFileType(path)) {
case Type.FILE: {
const parsedPath = (0, path_1.parse)(path);
if (isImage(parsedPath.base))
yield {
root: parsedPath.dir,
file: parsedPath.base,
};
break;
}
case Type.DIRECTORY:
for await (const result of walkDirectory(path)) {
yield result;
}
}
}
async function* walkDirectory(path) {
const queue = new denque_1.default([path]);
while (queue.length !== 0)
try {
const currentPath = queue.shift();
const dir = await fs_1.promises.opendir(currentPath);
for await (const item of dir)
switch (getType(item)) {
case Type.DIRECTORY:
queue.push((0, path_1.resolve)(currentPath, item.name));
break;
case Type.FILE:
if (isImage(item.name))
yield {
root: path,
file: (0, path_1.relative)(path, (0, path_1.resolve)(currentPath, item.name)),
};
}
}
catch (err) {
yield formatError(err, path);
}
}
function formatError(err, path) {
if (!(err instanceof Error))
return new common_1.Exception("Search Error: Thrown object was not an Error");
return new common_1.Exception(`Search error for ${path}: ${err.message}`).extend(err);
}
function isImage(name) {
return SUPPORTED_EXTENSIONS.includes((0, path_1.parse)(name).ext);
}
function getType(entry) {
if (entry.isFile())
return Type.FILE;
if (entry.isDirectory())
return Type.DIRECTORY;
return null;
}
async function getFileType(path) {
const stat = await fs_1.promises.stat(path);
if (stat.isFile())
return Type.FILE;
if (stat.isDirectory())
return Type.DIRECTORY;
return null;
}