flecks/packages/create-app/build/tree.js

72 lines
1.8 KiB
JavaScript
Raw Normal View History

2024-01-20 04:59:13 -06:00
const {createReadStream, createWriteStream} = require('fs');
const {mkdir, stat} = require('fs/promises');
2022-03-01 01:52:56 -06:00
2024-01-21 06:56:53 -06:00
const {glob, JsonStream} = require('@flecks/core/server');
2024-01-20 04:59:13 -06:00
const minimatch = require('minimatch');
const {dirname, join} = require('path');
2022-03-01 01:52:56 -06:00
2024-01-20 04:59:13 -06:00
module.exports = class FileTree {
2022-03-01 01:52:56 -06:00
constructor(files = {}) {
this.files = files;
}
addDirectory(path) {
this.files[path] = null;
}
addFile(path, stream) {
this.files[path] = stream;
}
glob(glob) {
return Object.keys(this.files).filter((path) => minimatch(path, glob, {dot: true}));
}
static async loadFrom(cwd) {
2024-01-13 01:59:01 -06:00
const paths = await glob('**/*', {cwd, dot: true});
2022-03-01 01:52:56 -06:00
return new FileTree(
await paths
.reduce(
async (r, path) => {
const origin = join(cwd, path);
const stats = await stat(origin);
return {
...await r,
[path]: stats.isDirectory() ? null : createReadStream(origin),
};
},
{},
),
);
}
pipe(path, stream) {
this.files[path] = this.files[path] ? this.files[path].pipe(stream) : undefined;
}
async writeTo(destination) {
2024-01-21 06:56:53 -06:00
// Pretty print all JSON.
this.glob('**/*.json')
.forEach((path) => {
this.pipe(path, new JsonStream.PrettyPrint());
});
2022-03-01 01:52:56 -06:00
return Promise.all(
Object.entries(this.files)
.map(async ([path, stream]) => {
if (null === stream) {
2022-03-09 17:18:27 -06:00
return mkdir(join(destination, path), {recursive: true});
2022-03-01 01:52:56 -06:00
}
await mkdir(dirname(join(destination, path)), {recursive: true});
return new Promise((resolve, reject) => {
const writer = createWriteStream(join(destination, path));
writer.on('finish', resolve);
writer.on('error', reject);
stream.pipe(writer);
});
}),
);
}
2024-01-20 04:59:13 -06:00
};