refactor(@embark/embark-utils): move joinPath to embark-utils

This commit is contained in:
Iuri Matias 2019-03-27 09:44:51 -04:00
parent c65a4a7f55
commit c8475da144
23 changed files with 153 additions and 55 deletions

View File

@ -0,0 +1,4 @@
engine-strict = true
package-lock = false
save-exact = true
scripts-prepend-node-path = true

View File

@ -0,0 +1,4 @@
# `embark-utils`
Visit [embark.status.im](https://embark.status.im/) to get started with
[Embark](https://github.com/embark-framework/embark).

View File

@ -0,0 +1,66 @@
{
"name": "embark-utils",
"version": "4.0.0",
"author": "Iuri Matias <iuri.matias@gmail.com>",
"contributors": [],
"description": "Utils used by Embark",
"homepage": "https://github.com/embark-framework/embark/tree/master/packages/embark-utils#readme",
"bugs": "https://github.com/embark-framework/embark/issues",
"keywords": [
"blockchain",
"dapps",
"ethereum",
"ipfs",
"serverless",
"solc",
"solidity"
],
"files": [
"dist"
],
"license": "MIT",
"repository": {
"directory": "packages/embark-utils",
"type": "git",
"url": "https://github.com/embark-framework/embark.git"
},
"main": "./dist/index.js",
"scripts": {
"build": "cross-env BABEL_ENV=node babel src --extensions \".js,.ts\" --out-dir dist --root-mode upward --source-maps",
"ci": "npm run qa",
"clean": "npm run reset",
"lint": "npm-run-all lint:*",
"lint:js": "eslint src/",
"// lint:ts": "tslint -c tslint.json \"src/**/*.ts\"",
"package": "npm pack",
"// qa": "npm-run-all lint typecheck build package",
"qa": "npm-run-all lint build package",
"reset": "npx rimraf dist embark-*.tgz package",
"start": "npm run watch",
"// typecheck": "tsc",
"watch": "run-p watch:*",
"watch:build": "npm run build -- --verbose --watch",
"// watch:typecheck": "npm run typecheck -- --preserveWatchOutput --watch"
},
"eslintConfig": {
"extends": "../../.eslintrc.json"
},
"dependencies": {
"@babel/runtime-corejs2": "7.3.1"
},
"devDependencies": {
"@babel/cli": "7.2.3",
"@babel/core": "7.2.2",
"cross-env": "5.2.0",
"eslint": "5.7.0",
"npm-run-all": "4.1.5",
"rimraf": "2.6.3",
"tslint": "5.11.0",
"typescript": "3.3.1"
},
"engines": {
"node": ">=8.12.0",
"npm": ">=6.4.1",
"yarn": ">=1.12.3"
}
}

View File

@ -0,0 +1,12 @@
class Utils {
static joinPath() {
const path = require('path');
return path.join.apply(path.join, arguments);
}
}
module.exports = Utils;

View File

@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.json",
"include": ["src/**/*"]
}

View File

@ -0,0 +1,3 @@
{
"extends": "../../tslint.json"
}

View File

@ -92,6 +92,7 @@
"embark-vyper": "^4.0.0",
"embark-profiler": "^4.0.0",
"embark-specialconfigs": "^4.0.0",
"embark-utils": "^4.0.0",
"embarkjs": "^4.0.0",
"eth-ens-namehash": "2.0.8",
"ethereumjs-tx": "1.3.7",

View File

@ -2,7 +2,7 @@
const {delimiter} = require('path');
const findUp = require('find-up');
const {joinPath} = require('../utils/utils.js');
import {joinPath} from 'embark-utils';
function anchoredValue(anchor, value) {
if (!arguments.length) {

View File

@ -10,6 +10,7 @@ const os = require('os');
const parseJson = require('parse-json');
const path = require('path');
const utils = require('../utils/utils');
import {joinPath} from 'embark-utils';
require('colors');
function mkdirpSync(...args) { return fs.mkdirpSync(...args); }
@ -74,7 +75,7 @@ function access(...args) { return fs.access(...args); }
function removeSync(...args) { return fs.removeSync(...args); }
function anchoredPath(anchor, ...args) {
return utils.joinPath(
return joinPath(
anchoredValue(anchor),
...args.map(path => path.replace(dappPath(), ''))
);
@ -93,7 +94,7 @@ function ipcPath(basename, usePipePathOnWindows = false) {
if (process.platform === 'win32' && usePipePathOnWindows) {
return `\\\\.\\pipe\\${basename}`;
}
return utils.joinPath(
return joinPath(
tmpDir(`embark-${utils.sha512(dappPath()).slice(0, 8)}`),
basename
);
@ -103,7 +104,7 @@ function pkgPath(...args) { return anchoredPath(PKG_PATH, ...args); }
function createWriteStream(...args) { return fs.createWriteStream(...args); }
function tmpDir(...args) { return utils.joinPath(os.tmpdir(), ...args); }
function tmpDir(...args) { return joinPath(os.tmpdir(), ...args); }
function copyPreserve(sourceFilePath, targetFilePath) {
const implementation = (sourceFilePath, targetFilePath) => {
@ -111,7 +112,7 @@ function copyPreserve(sourceFilePath, targetFilePath) {
let preserved = targetFilePath;
while (fs.existsSync(preserved)) {
const extname = path.extname(targetFilePath);
preserved = utils.joinPath(
preserved = joinPath(
path.dirname(targetFilePath),
`${path.basename(targetFilePath, extname)}.${ext}${extname}`
);

View File

@ -1,4 +1,5 @@
const utils = require('../utils/utils.js');
import {joinPath} from 'embark-utils';
const constants = require('../constants');
const fs = require('./fs.js');
const deepEqual = require('deep-equal');
@ -117,7 +118,7 @@ Plugin.prototype.pathToFile = function(filename) {
if (!this.pluginPath) {
throw new Error('pluginPath not defined for plugin: ' + this.name);
}
return utils.joinPath(this.pluginPath, filename);
return joinPath(this.pluginPath, filename);
};
// TODO: add deploy provider

View File

@ -1,5 +1,5 @@
const ProcessLauncher = require('../../core/processes/processLauncher');
const utils = require('../../utils/utils.js');
import {joinPath} from 'embark-utils';
const constants = require('../../constants');
class BlockchainProcessLauncher {
@ -24,7 +24,7 @@ class BlockchainProcessLauncher {
this.blockchainProcess = new ProcessLauncher({
name: 'blockchain',
modulePath: utils.joinPath(__dirname, './blockchainProcess.js'),
modulePath: joinPath(__dirname, './blockchainProcess.js'),
logger: this.logger,
events: this.events,
embark: this.embark,

View File

@ -10,6 +10,7 @@ const os = require('os');
const parseJson = require('parse-json');
const path = require('path');
const utils = require('../../utils/utils');
import {joinPath} from 'embark-utils';
require('colors');
function restrictPath(receiver, binding, count, args) {
@ -102,7 +103,7 @@ function access(...args) { return restrictPath(fs.access, fs, 1, args); }
function removeSync(...args) { return restrictPath(fs.removeSync, fs, 1, args); }
function anchoredPath(anchor, ...args) {
return utils.joinPath(
return joinPath(
anchoredValue(anchor),
...args.map(path => path.replace(dappPath(), ''))
);
@ -121,7 +122,7 @@ function ipcPath(basename, usePipePathOnWindows = false) {
if (process.platform === 'win32' && usePipePathOnWindows) {
return `\\\\.\\pipe\\${basename}`;
}
return utils.joinPath(
return joinPath(
tmpDir(`embark-${utils.sha512(dappPath()).slice(0, 8)}`),
basename
);
@ -131,7 +132,7 @@ function pkgPath(...args) { return anchoredPath(PKG_PATH, ...args); }
function createWriteStream(...args) { return restrictPath(fs.createWriteStream, fs, 1, args); }
function tmpDir(...args) { return utils.joinPath(os.tmpdir(), ...args); }
function tmpDir(...args) { return joinPath(os.tmpdir(), ...args); }
function copyPreserve(sourceFilePath, targetFilePath) {
const implementation = (sourceFilePath, targetFilePath) => {
@ -139,7 +140,7 @@ function copyPreserve(sourceFilePath, targetFilePath) {
let preserved = targetFilePath;
while (fs.existsSync(preserved)) {
const extname = path.extname(targetFilePath);
preserved = utils.joinPath(
preserved = joinPath(
path.dirname(targetFilePath),
`${path.basename(targetFilePath, extname)}.${ext}${extname}`
);

View File

@ -1,5 +1,5 @@
let async = require('async');
const utils = require('../../utils/utils.js');
import {joinPath} from 'embark-utils';
const constants = require('../../constants');
const path = require('path');
@ -178,8 +178,8 @@ class CodeGenerator {
}
generateArtifact(artifactInput, fileName, dirName, cb = () => {}) {
const dir = utils.joinPath(this.embarkConfig.generationDir, dirName);
const filePath = utils.joinPath(dir, fileName);
const dir = joinPath(this.embarkConfig.generationDir, dirName);
const filePath = joinPath(dir, fileName);
if (typeof artifactInput !== 'string') {
artifactInput = JSON.stringify(artifactInput, null, 2);
}
@ -408,7 +408,7 @@ class CodeGenerator {
if (err) {
return next(err);
}
next(null, utils.joinPath(symlinkDir, name).replace(/\\/g, '/'));
next(null, joinPath(symlinkDir, name).replace(/\\/g, '/'));
});
},
// Remove old symlink because they are not overwritable

View File

@ -1,3 +1,4 @@
import {joinPath} from 'embark-utils';
const utils = require('../../utils/utils.js');
const namehash = require('eth-ens-namehash');
const async = require('async');
@ -380,8 +381,8 @@ class ENS {
}
this.events.emit('runcode:register', 'namehash', require('eth-ens-namehash'), () => {
let code = `\nconst namehash = global.namehash || require('${symlinkDest}');`;
code += this.fs.readFileSync(utils.joinPath(__dirname, 'ENSFunctions.js')).toString();
code += "\n" + this.fs.readFileSync(utils.joinPath(__dirname, 'embarkjs.js')).toString();
code += this.fs.readFileSync(joinPath(__dirname, 'ENSFunctions.js')).toString();
code += "\n" + this.fs.readFileSync(joinPath(__dirname, 'embarkjs.js')).toString();
code += "\nEmbarkJS.Names.registerProvider('ens', __embarkENS);";
this.embark.addCodeToEmbarkJS(code);

View File

@ -1,5 +1,6 @@
const UploadIPFS = require('./upload.js');
const utils = require('../../utils/utils.js');
import {joinPath} from 'embark-utils';
const IpfsApi = require('ipfs-api');
// TODO: not great, breaks module isolation
const StorageProcessesLauncher = require('../storage/storageProcessesLauncher');
@ -112,7 +113,7 @@ class IPFS {
this.events.emit('runcode:register', 'IpfsApi', require('ipfs-api'), () => {
let code = `\nconst IpfsApi = global.IpfsApi || require('${symlinkDest}');`;
code += "\n" + this.fs.readFileSync(utils.joinPath(__dirname, 'embarkjs.js')).toString();
code += "\n" + this.fs.readFileSync(joinPath(__dirname, 'embarkjs.js')).toString();
code += "\nEmbarkJS.Storage.registerProvider('ipfs', __embarkIPFS);";
this.embark.addCodeToEmbarkJS(code);

View File

@ -1,6 +1,7 @@
const path = require('path');
const async = require('async');
const utils = require('../../utils/utils.js');
import {joinPath} from 'embark-utils';
const ProcessLauncher = require('../../core/processes/processLauncher');
const constants = require('../../constants');
const WebpackConfigReader = require('../pipeline/webpackConfigReader');
@ -197,7 +198,7 @@ class Pipeline {
let strAssets = '';
if (!self.useDashboard) {
assets.forEach(key => {
strAssets += ('\n ' + (utils.joinPath(self.buildDir, key)).bold.dim);
strAssets += ('\n ' + (joinPath(self.buildDir, key)).bold.dim);
});
}
const timer = new LongRunningProcessTimer(
@ -218,7 +219,7 @@ class Pipeline {
const webpackProcess = new ProcessLauncher({
embark: self.embark,
plugins: self.plugins,
modulePath: utils.joinPath(__dirname, 'webpackProcess.js'),
modulePath: joinPath(__dirname, 'webpackProcess.js'),
logger: self.logger,
events: self.events,
exitCallback: code => {
@ -261,7 +262,7 @@ class Pipeline {
const isDir = targetFile.slice(-1) === '/' || targetFile.slice(-1) === '\\' || targetFile.indexOf('.') === -1;
// if it's not a directory
if (!isDir) {
self.logger.info('Pipeline: '.cyan + __("writing file") + " " + (utils.joinPath(self.buildDir, targetFile)).bold.dim);
self.logger.info('Pipeline: '.cyan + __("writing file") + " " + (joinPath(self.buildDir, targetFile)).bold.dim);
}
async.map(
files,
@ -276,8 +277,8 @@ class Pipeline {
self.logger.error('Pipeline: '.cyan + __('errors found while generating') + ' ' + targetFile);
}
let dir = targetFile.split('/').slice(0, -1).join('/');
self.logger.trace(`${'Pipeline:'.cyan} creating dir ` + utils.joinPath(self.buildDir, dir));
self.fs.mkdirpSync(utils.joinPath(self.buildDir, dir));
self.logger.trace(`${'Pipeline:'.cyan} creating dir ` + joinPath(self.buildDir, dir));
self.fs.mkdirpSync(joinPath(self.buildDir, dir));
// if it's a directory
if (isDir) {
@ -289,9 +290,9 @@ class Pipeline {
async.each(contentFiles, function (file, eachCb) {
let filename = file.path.replace(file.basedir + '/', '');
self.logger.info(`${'Pipeline:'.cyan} writing file ` + (utils.joinPath(self.buildDir, targetDir, filename)).bold.dim);
self.logger.info(`${'Pipeline:'.cyan} writing file ` + (joinPath(self.buildDir, targetDir, filename)).bold.dim);
self.fs.copy(file.path, utils.joinPath(self.buildDir, targetDir, filename), {overwrite: true}, eachCb);
self.fs.copy(file.path, joinPath(self.buildDir, targetDir, filename), {overwrite: true}, eachCb);
}, cb);
return;
}
@ -307,7 +308,7 @@ class Pipeline {
targetFile = targetFile.replace('index', 'index-temp');
placeholderPage = targetFile;
}
self.fs.writeFile(utils.joinPath(self.buildDir, targetFile), content, cb);
self.fs.writeFile(joinPath(self.buildDir, targetFile), content, cb);
}
);
},
@ -315,8 +316,8 @@ class Pipeline {
);
},
function removePlaceholderPage(next) {
let placeholderFile = utils.joinPath(self.buildDir, placeholderPage);
self.fs.access(utils.joinPath(self.buildDir, placeholderPage), (err) => {
let placeholderFile = joinPath(self.buildDir, placeholderPage);
self.fs.access(joinPath(self.buildDir, placeholderPage), (err) => {
if (err) return next(); // index-temp doesn't exist, do nothing
// rename index-temp.htm/l to index.htm/l, effectively replacing our placeholder page
@ -353,7 +354,7 @@ class Pipeline {
// Used to enable alternate import syntax:
// e.g. import {Token} from 'Embark/contracts'
// e.g. import * as Contracts from 'Embark/contracts'
let importsHelperFile = self.fs.createWriteStream(utils.joinPath(contractsDir, 'index.js'));
let importsHelperFile = self.fs.createWriteStream(joinPath(contractsDir, 'index.js'));
importsHelperFile.write('module.exports = {\n');
async.eachOf(contracts, (contract, idx, eachCb) => {

View File

@ -1,4 +1,4 @@
let utils = require('../../utils/utils.js');
import {joinPath} from 'embark-utils';
let currentSolcVersion = require('../../../../package.json').dependencies.solc;
const ProcessLauncher = require('../../core/processes/processLauncher.js');
const uuid = require('uuid/v1');
@ -42,7 +42,7 @@ class SolcW {
}
this.solcProcess = new ProcessLauncher({
embark: self.embark,
modulePath: utils.joinPath(__dirname, 'solcP.js'),
modulePath: joinPath(__dirname, 'solcP.js'),
logger: self.logger,
events: self.events,
providerUrl: self.providerUrl,

View File

@ -1,5 +1,6 @@
const shellJs = require('shelljs');
const utils = require('../../utils/utils');
import {joinPath} from 'embark-utils';
const ProcessLauncher = require('../../core/processes/processLauncher');
const constants = require('../../constants');
const {canonicalHost} = require('../../utils/host');
@ -95,7 +96,7 @@ class StorageProcessesLauncher {
if (self.processes[storageName]) {
return callback(__('Storage process already started'));
}
const filePath = utils.joinPath(__dirname, `../${storageName}/process.js`);
const filePath = joinPath(__dirname, `../${storageName}/process.js`);
this.embark.fs.access(filePath, (err) => {
if (err) {
return callback(__('No process file for this storage type (%s) exists. Please start the process locally.', storageName));

View File

@ -1,5 +1,6 @@
const UploadSwarm = require('./upload.js');
const utils = require('../../utils/utils.js');
import {joinPath} from 'embark-utils';
const SwarmAPI = require('swarm-api');
// TODO: not great, breaks module isolation
const StorageProcessesLauncher = require('../storage/storageProcessesLauncher');
@ -90,7 +91,7 @@ class Swarm {
addProviderToEmbarkJS() {
let code = "";
code += "\n" + this.fs.readFileSync(utils.joinPath(__dirname, 'embarkjs.js')).toString();
code += "\n" + this.fs.readFileSync(joinPath(__dirname, 'embarkjs.js')).toString();
code += "\nEmbarkJS.Storage.registerProvider('swarm', __embarkSwarm);";
this.embark.addCodeToEmbarkJS(code);

View File

@ -2,6 +2,7 @@ import {findNextPort} from "../../utils/network";
var {canonicalHost} = require('../../utils/host.js');
var utils = require('../../utils/utils.js');
import {joinPath} from 'embark-utils';
var Server = require('./server.js');
const opn = require('opn');
@ -151,7 +152,7 @@ class WebServer {
buildPlaceholderPage(cb) {
let html = Templates.embark_building_placeholder({buildingMsg: __('Embark is building, please wait...')});
this.fs.mkdirpSync(this.buildDir); // create buildDir if it does not exist
this.fs.writeFile(utils.joinPath(this.buildDir, 'index.html'), html, cb);
this.fs.writeFile(joinPath(this.buildDir, 'index.html'), html, cb);
}
openBrowser(cb) {

View File

@ -1,6 +1,6 @@
/* global __ __dirname module require setTimeout */
let utils = require('../../utils/utils.js');
import {joinPath} from 'embark-utils';
let Web3 = require('web3');
const {parallel} = require('async');
const {sendMessage, listenTo} = require('./js/communicationFunctions');
@ -123,11 +123,11 @@ class Whisper {
let code = "";
if (web3Version[0] === "0") {
self.isOldWeb3 = true;
code += "\n" + self.fs.readFileSync(utils.joinPath(__dirname, 'js', 'embarkjs_old_web3.js')).toString();
code += "\n" + self.fs.readFileSync(joinPath(__dirname, 'js', 'embarkjs_old_web3.js')).toString();
code += "\nEmbarkJS.Messages.registerProvider('whisper', __embarkWhisperOld);";
} else {
code += "\n" + self.fs.readFileSync(utils.joinPath(__dirname, 'js', 'communicationFunctions.js')).toString();
code += "\n" + self.fs.readFileSync(utils.joinPath(__dirname, 'js', 'embarkjs.js')).toString();
code += "\n" + self.fs.readFileSync(joinPath(__dirname, 'js', 'communicationFunctions.js')).toString();
code += "\n" + self.fs.readFileSync(joinPath(__dirname, 'js', 'embarkjs.js')).toString();
code += "\nEmbarkJS.Messages.registerProvider('whisper', __embarkWhisperNewWeb3);";
}
self.embark.addCodeToEmbarkJS(code);

View File

@ -2,6 +2,7 @@ const findUp = require('find-up');
const fs = require('../core/fs.js');
const hostedGitInfo = require('hosted-git-info');
const utils = require('./utils.js');
import {joinPath} from 'embark-utils';
const semver = require('semver');
const {promisify} = require('util');
const {execSync} = require('child_process');
@ -46,7 +47,7 @@ class TemplateGenerator {
}
async downloadAndGenerate(uri, destinationFolder, name) {
const fspath = utils.joinPath(destinationFolder, name);
const fspath = joinPath(destinationFolder, name);
this.checkPathExists(fspath);
let ext;
try {
@ -87,7 +88,7 @@ class TemplateGenerator {
map: file => {
let fixed_path = file.path.split('/');
fixed_path.shift(); // remove first directory
file.path = utils.joinPath(...fixed_path);
file.path = joinPath(...fixed_path);
return file;
}
},
@ -96,7 +97,7 @@ class TemplateGenerator {
}
generate(destinationFolder, name) {
const fspath = utils.joinPath(destinationFolder, name);
const fspath = joinPath(destinationFolder, name);
this.checkPathExists(fspath);
console.log(__('Initializing Embark template...').green);
@ -104,7 +105,7 @@ class TemplateGenerator {
const templatePkg = `embark-dapp-template-${this.templateName}`;
let templateSpecifier;
if (this.monorepoRootPath) {
templateSpecifier = utils.joinPath(
templateSpecifier = joinPath(
this.monorepoRootPath, 'dapps/templates', this.templateName
);
} else {
@ -113,12 +114,12 @@ class TemplateGenerator {
}
const tmpDir = require('fs-extra').mkdtempSync(
utils.joinPath(require('os').tmpdir(), `${this.templateName}-`)
joinPath(require('os').tmpdir(), `${this.templateName}-`)
);
execSync(`npm pack ${templateSpecifier}`, {cwd: tmpDir, stdio: 'ignore'});
const packed = utils.filesMatchingPattern(
[utils.joinPath(tmpDir, '*.tgz')]
[joinPath(tmpDir, '*.tgz')]
)[0];
this.extract(packed, fspath, () => {
@ -266,13 +267,13 @@ class TemplateGenerator {
url,
browse: decodeURIComponent(hgi.browse()),
url_fallback,
filePath_fallback: fallback && utils.joinPath(".embark/templates/", folder_fallback, "archive.zip"),
filePath_fallback: fallback && joinPath(".embark/templates/", folder_fallback, "archive.zip"),
browse_fallback: fallback && decodeURIComponent(hgi_fallback.browse()),
embarkVersion
};
if (hgi.committish) {
folder = `${hgi.user}/${hgi.project}/${hgi.committish}`;
returnObject.filePath = utils.joinPath(".embark/templates/", folder, "archive.zip");
returnObject.filePath = joinPath(".embark/templates/", folder, "archive.zip");
return returnObject;
}
return new Promise((resolve, reject) => {
@ -287,7 +288,7 @@ class TemplateGenerator {
}
folder = `${hgi.user}/${hgi.project}/${body.default_branch}`;
returnObject.url = returnObject.url.replace('/master', '/' + body.default_branch);
returnObject.filePath = utils.joinPath(".embark/templates/", folder, "archive.zip");
returnObject.filePath = joinPath(".embark/templates/", folder, "archive.zip");
resolve(returnObject);
});
});

View File

@ -5,11 +5,6 @@ const {canonicalHost} = require('./host');
const balanceRegex = /([0-9]+) ?([a-zA-Z]*)/;
function joinPath() {
const path = require('path');
return path.join.apply(path.join, arguments);
}
function dirname() {
const path = require('path');
return path.dirname.apply(path.dirname, arguments);
@ -644,7 +639,6 @@ function urlJoin(url, path) {
}
module.exports = {
joinPath,
dirname,
filesMatchingPattern,
fileMatchesPattern,