ring-websites-toolbelt
Version:
Ring Publishing Platform tool to work with Ring Websites
108 lines (87 loc) • 3.35 kB
JavaScript
const fs = require('fs');
const fse = require('fs-extra');
const path = require('path');
const { zip } = require('zip-a-folder');
class FilesProvider {
constructor(themeJson, ucsConfig) {
this.zipDir = path.join('../__temp_dir_for_zip');
}
getConfigJson(configPath, partialsPath, schemesPath, ocdnLocation) {
let configJson = {};
let partialsJson = null;
try {
configJson = JSON.parse(fs.readFileSync(configPath, "utf8"));
} catch (e) {
throw new Error(`Cannot read ${configPath} file. Reason: ` + e);
}
if (fs.existsSync(partialsPath)) {
try {
partialsJson = JSON.parse(fs.readFileSync(partialsPath, "utf8"));
} catch (e) {
throw new Error(`Cannot read ${partialsPath} file. Reason: ` + e);
}
}
const nodesColorScheme = this.getNodesColorSchemes(schemesPath);
ocdnLocation = ocdnLocation[ocdnLocation.length-1] === '/' ? ocdnLocation.slice(0,-1) : ocdnLocation; // remove '/' if it is last char
configJson.ocdn = {
'static_url': ocdnLocation,
'color_schemes': nodesColorScheme
};
if (partialsJson) {
configJson.themePartials = partialsJson;
}
return configJson;
}
async createZipDir(srcPath, destFolder, excludeFilters = []) {
const splitPath = srcPath.split('/');
const zipDir = path.join(`${this.zipDir}${destFolder ? `/${destFolder}` : '' }`);
if (fs.existsSync(this.zipDir)) {
fse.removeSync(this.zipDir);
}
fse.ensureDirSync(zipDir, { recursive: true });
fse.copySync(srcPath, zipDir, {
filter: (src, dest) => !excludeFilters.includes(path.basename(src))
});
}
async compressDir(srcPath, destFolder, destFile, excludeFilters) {
try {
srcPath = path.join(srcPath);
srcPath = path.join(srcPath.endsWith('/') ? srcPath.slice(0, -1) : srcPath);
this.createZipDir(srcPath, destFolder, excludeFilters);
await zip(this.zipDir, destFile);
fse.removeSync(this.zipDir);
console.info("File", destFile, "is finised.");
} catch (error) {
console.error('Error while compressing theme', error);
throw error;
}
}
async compressFiles(files, destFolder, destFile) {
throw new Error('Not implemented');
}
async removeCompressedFile(file) {
try {
//remove zipped dir
if (fs.existsSync(file)) {
fs.unlinkSync(file);
}
} catch (e) {
throw new Error('Cannot delete existing zipped dir. Reason: ' + e);
}
}
getNodesColorSchemes(path) {
let nodesColorScheme = [];
const isExists = fs.existsSync(path);
if (!isExists) {
return nodesColorScheme;
}
nodesColorScheme = fs.readdirSync(path);
// remove last 5 characters '.yaml'
// e.g. onet.facet.yaml -> onet.facet
for (let i = 0, len = nodesColorScheme.length; i < len; i++) {
nodesColorScheme[i] = nodesColorScheme[i].slice(0, -5);
}
return nodesColorScheme;
}
}
module.exports = FilesProvider;