UNPKG

tia

Version:

Time is All (logs driven test engine with ExtJs support)

299 lines 9.68 kB
"use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const fs = __importStar(require("fs")); const path = __importStar(require("path")); const textUtils = __importStar(require("./text-utils")); const childProcess = __importStar(require("child_process")); /* globals gT, gIn */ // TODO: сделать так, чтобы тесты работали под правами специально заведеного юзера. // У этого юзера будет доступ к тестовой директории только на чтение. // Права на запись у него будут только в его home. // Перед тестом (после подключения всех require), юзер процесса будет подменяться (process.setuid(id)). // Весь test suite будет копироваться в директорию юзера и работать оттуда. // gT.fileUtilsCheckPath = function(path){ // // }; /** * Checks that file or directory absent by statSync, without checking for catch reason (ENOENT or no). * * @param fileOrDirPath * @returns {boolean} */ function isAbsent(fileOrDirPath) { try { fs.statSync(fileOrDirPath); } catch (e) { return true; } return false; } exports.isAbsent = isAbsent; function isEtalonAbsent(jsPath) { const etPath = textUtils.jsToEt(jsPath); try { fs.statSync(etPath); } catch (e) { return true; } return false; } exports.isEtalonAbsent = isEtalonAbsent; function safeUnlink(fileOrDirPath) { try { fs.unlinkSync(fileOrDirPath); } catch (e) { // No handling intentionaly. } } exports.safeUnlink = safeUnlink; function safeReadFile(fileOrDirPath) { let res = ''; try { res = fs.readFileSync(fileOrDirPath, gT.engineConsts.logEncoding); } catch (e) { gIn.tracer.msg3(`safeReadFile: No such file: ${fileOrDirPath}`); // No handling intentionaly. } return res; } exports.safeReadFile = safeReadFile; function backupDif(fileOrDirPath) { try { fs.renameSync(fileOrDirPath, `${fileOrDirPath}.old`); } catch (e) { // No handling intentionaly. } } exports.backupDif = backupDif; function isDirectory(fileOrDirPath) { let stat; try { stat = fs.statSync(fileOrDirPath); } catch (e) { return false; } return stat.isDirectory(); } exports.isDirectory = isDirectory; function rmPngs(jsPath) { const dir = path.dirname(jsPath); const start = path.basename(textUtils.changeExt(jsPath, '')); fs.readdirSync(dir).forEach(fileName => { const filePath = path.join(dir, fileName); if (!isDirectory(filePath) && filePath.endsWith('.png') && fileName.startsWith(start)) { safeUnlink(filePath); } }); } exports.rmPngs = rmPngs; function rmDir(dir, removeSelf) { let files; try { files = fs.readdirSync(dir); } catch (e) { return; } if (files.length > 0) { for (let i = 0; i < files.length; i++) { const filePath = path.join(dir, files[i]); const fdata = fs.lstatSync(filePath); try { if (fdata.isSymbolicLink()) { fs.unlinkSync(filePath); } if (fdata.isFile()) { fs.unlinkSync(filePath); } } catch (e) { gIn.tracer.err(`rmDir: ${gIn.textUtils.excToStr(e)}`); } if (fdata.isDirectory()) { rmDir(filePath, true); } } } if (removeSelf) { fs.rmdirSync(dir); } } exports.rmDir = rmDir; function emptyDir(dir) { rmDir(dir); } exports.emptyDir = emptyDir; function safeRename(oldPath, newPath) { safeUnlink(newPath); try { fs.renameSync(oldPath, newPath); } catch (e) { // No handling intentionaly. } } exports.safeRename = safeRename; // Removes file, if exists. function createEmptyFileSync(fileOrDirPath) { fs.closeSync(fs.openSync(fileOrDirPath, 'w')); } exports.createEmptyFileSync = createEmptyFileSync; function createEmptyLog(fileOrDirPath) { gIn.logger.setLogFile(gIn.textUtils.jsToLog(fileOrDirPath)); createEmptyFileSync(gIn.logger.getLogFile()); } exports.createEmptyLog = createEmptyLog; function fileToStdout(file) { console.log(fs.readFileSync(file, { encoding: gT.engineConsts.logEncoding })); } exports.fileToStdout = fileToStdout; function fileToStderr(file) { // console.error(fs.readFileSync(file, {encoding: gT.engineConsts.logEncoding})); gIn.cLogger.errln(fs.readFileSync(file, { encoding: gT.engineConsts.logEncoding })); } exports.fileToStderr = fileToStderr; function saveJson(obj, file) { fs.writeFileSync(file, JSON.stringify(obj, null, 2), { encoding: gT.engineConsts.logEncoding }); } exports.saveJson = saveJson; function collectArcPaths(dirInfo, arcPaths) { if (!dirInfo.diffed) { return; } // Absense of 'children' property says that it is test and not directory, // we should not allow to use this function for not directory. for (const curInfo of dirInfo.children) { // eslint-disable-line no-restricted-syntax if (Object.prototype.hasOwnProperty.call(curInfo, 'children')) { collectArcPaths(curInfo, arcPaths); } else if (curInfo.diffed) { arcPaths.push(gIn.textUtils.changeExt(curInfo.path, '')); } } } function getDirectoryAlias(dirPath) { const pathArr = dirPath.split(path.sep); const last = pathArr.pop(); if (last !== gT.engineConsts.suiteDirName) { throw new Error(`getDirectoryAlias: Incorrect path format: ${dirPath}`); } const alias = pathArr.pop(); if (!alias) { throw new Error(`getDirectoryAlias: Incorrect path format: ${dirPath}`); } return alias; } exports.getDirectoryAlias = getDirectoryAlias; function archiveSuiteDir(dirInfo) { if (!gT.cLParams.enableEmail || !gT.suiteConfig.attachArchiveToMail || !gT.suiteConfig.mailRecipientList) { return null; } const alias = getDirectoryAlias(dirInfo.path); const arcName = `${alias}_${new Date() .toISOString() .slice(0, 19) .replace(/:/g, '_')}.zip`; const suitePathWOSuiteDirName = path.resolve(gT.cLParams.rootDir, dirInfo.path, '..'); const wholeSuiteArcRelPath = path.relative(suitePathWOSuiteDirName, dirInfo.path); const resultArchivePath = path.resolve(suitePathWOSuiteDirName, arcName); if (!gT.suiteConfig.attachOnlyDiffs) { try { childProcess.execSync(`cd ${suitePathWOSuiteDirName} && zip -r ${arcName} "${wholeSuiteArcRelPath}"/*`, { stdio: [null, null, null], windowsHide: true, }); } catch (e) { gIn.tracer.err(`zip stderr: ${e.stderr.toString()}`); gIn.tracer.err(`zip stdout: ${e.stdout.toString()}`); throw new Error('Error with zip (whole)'); } return resultArchivePath; } // Only diffs handling. const diffedPathsToArc = []; collectArcPaths(dirInfo, diffedPathsToArc); if (diffedPathsToArc.length === 0) { gIn.tracer.msg3('Archieve: No diffs, no archieve'); return null; } const diffedRelativePathsToArc = diffedPathsToArc.map(diffedArcPath => { const relativePath = `"${path.relative(suitePathWOSuiteDirName, diffedArcPath)}"*`; return relativePath; }); try { childProcess.execSync(`cd ${suitePathWOSuiteDirName} && zip -r ${arcName} ${diffedRelativePathsToArc.join(' ')}`, { stdio: [null, null, null] }); } catch (e) { gIn.tracer.err(`zip stderr: ${e.stderr.toString()}`); gIn.tracer.err(`zip stdout: ${e.stdout.toString()}`); throw new Error('Error with zip (diffs only)'); } return resultArchivePath; } exports.archiveSuiteDir = archiveSuiteDir; function mkdir(dirPath) { try { fs.mkdirSync(dirPath, { recursive: true }); } catch (e) { gIn.tracer.msg3(e.toString()); } } exports.mkdir = mkdir; function mkDirRecursive(targetDir, subDirsArr) { let curPath = targetDir; subDirsArr.forEach(dir => { curPath = path.join(curPath, dir); mkdir(curPath); }); } exports.mkDirRecursive = mkDirRecursive; function rmLastDirSep(dir) { if (dir.endsWith(path.sep)) { return dir.slice(0, -1); } return dir; } exports.rmLastDirSep = rmLastDirSep; // One of filenames. function whichDirContain(base, fileNames, excludeThisBase) { const dirList = fs.readdirSync(base); for (const name of dirList) { if (name === 'node_modules') { continue; } const newBase = path.join(base, name); if (newBase === excludeThisBase) { continue; } if (fileNames.includes(name)) { return base; } if (fs.statSync(newBase).isDirectory()) { const dir = whichDirContain(newBase, fileNames, excludeThisBase); if (dir) { return dir; } } } return null; } exports.whichDirContain = whichDirContain; //# sourceMappingURL=file-utils.js.map