snippeteer/lib/snippets/copyright/file_mapper.ts

35 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-04-16 07:45:48 +02:00
/*
* Copyright (C) SapphireCode - All Rights Reserved
* This file is part of Snippeteer which is released under BSD-3-Clause.
* See file 'LICENSE' for full license details.
2020-05-07 18:40:35 +02:00
* Created by Timo Hocker <timo@scode.ovh>, May 2020
2020-04-16 07:45:48 +02:00
*/
2020-04-15 20:21:00 +02:00
/* eslint-disable no-await-in-loop */
import path from 'path';
import fs from 'fs-extra';
export class FileMapper {
public static async map_all_files (
folder: string,
2020-05-24 19:43:13 +02:00
mutator: (data: string, file: string, args: Array<unknown>) => string|null,
2020-09-24 12:08:31 +02:00
opts: Array<unknown> = []
2020-04-15 20:21:00 +02:00
): Promise<void> {
const files = await fs.readdir (folder);
for (const file of files) {
if ([ 'node_modules' ].includes (file))
continue;
const abs_path = path.join (folder, file);
if ((await fs.stat (abs_path)).isDirectory ()) {
2020-09-24 12:08:31 +02:00
await FileMapper.map_all_files (abs_path, mutator, opts);
2020-04-15 20:21:00 +02:00
continue;
}
const data = await fs.readFile (abs_path, 'utf-8');
2020-09-24 12:08:31 +02:00
const res = mutator (data, file, opts);
2020-04-15 20:21:00 +02:00
if (res === null)
continue;
await fs.writeFile (abs_path, res, 'utf-8');
}
}
}