You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

94 lines
2.7 KiB

import path from 'path';
import config from 'config';
import {fileURLToPath} from 'url';
import memFs from 'mem-fs';
import editor from 'mem-fs-editor';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export function getConfigs() {
const isDev = process.env.NODE_ENV === 'development'; // Check README file in case you get "missing files" error.
const developmentBlockName = process.env.BLOCK_NAME;
return {
isDev,
developmentBlockName,
modulesPath: isDev ? '' : 'node_modules/block-dev-tool',
projectPath: isDev ? path.join('blocks', developmentBlockName) : '',
};
}
import fsExtra from "fs-extra";
export async function readJSONFile(jsonFile) {
let data = {};
try {
data = await fsExtra.readJson(jsonFile);
} catch (e) {
return {
error: true, errorMessage: getErrorHtml("JSON Syntax error. Please make sure the dataFile is valid.", e),
};
}
return data;
}
function getErrorHtml(message = '', errorMessage = '') {
return `<div style="padding: 10px 15px; font-family: Arial, sans-serif">
<p>${message}</p>
<pre style="padding: 10px 15px; background-color: #ffd0d0; border: 1px solid red;">${errorMessage}</pre>
</div>`;
}
export async function getBlockConfigs(jsonFileName = 'default',
{includeConfigs, projectPath, modulesPath, dataFiles} = {}) {
let data = await readJSONFile(path.join(projectPath, 'data', `${jsonFileName}.json`));
if (data.error) {
return data;
}
if (includeConfigs) {
Object.assign(data, {
config: Object.assign(JSON.parse(JSON.stringify(config)), // The entire config object.
{
projectDir: modulesPath, activeDataFile: jsonFileName, dataFiles: dataFiles.map((name) => {
return {
name, active: jsonFileName === name,
};
}), remToPx: config.has('remToPx') ? config.get('remToPx') : 16,
})
});
}
return data;
}
export function getBlockName(name = '') {
if (name.startsWith('@')) {
name = name.substring(1);
}
const arr = name.split('/');
return {
project: arr[0],
name: arr[1],
};
}
export async function createFiles(data, files = [], {pathDist, generatorsPath}) {
generatorsPath = generatorsPath ?? path.join(__dirname, 'generators/block/templates');
const store = memFs.create();
const filesystem = editor.create(store);
for (let file of files) {
const from = typeof file !== 'string' ? `${generatorsPath}/${file.from}` : `${generatorsPath}/${file}`;
const to = typeof file !== 'string' ? `${pathDist}/${file.to}` : `${pathDist}/${file}`;
await filesystem.copyTplAsync(from, to, data);
}
return filesystem.commit(); // Promise
}