Skip to content

Commit 40c3d98

Browse files
0x-r4bbitmichaelsbradleyjr
authored andcommitted
feat(plugins/scripts-runner): introduce exec command to run scripts
This commit introduces a new feature that enables users to run (migration) scripts. Similar to deployment hooks, scripts are functions that may perform operations on newly deployed Smart Contracts. Therefore a script needs to export a function that has access to some dependencies: ``` // scripts/001-some-script.js module.exports = async ({contracts, web3, logger}) => { ... }; ``` Where `contracts` is a map of newly deployed Smart Contract instances, `web3` a blockchain connector instance and `logger` Embark's logger instance. Script functions can but don't have to be `async`. To execute such a script users use the newly introduced `exec` command: ``` $ embark exec development scripts/001-some-script.js ``` In the example above, `development` defines the environment in which Smart Contracts are being deployed to as well as where tracking data is stored. Alternativey, users can also provide a directory in which case Embark will try to execute every script living inside of it: ``` $ embark exec development scripts ``` Scripts can fail and therefore emit an error accordingly. When this happens, Embark will abort the script execution (in case multiple are scheduled to run) and informs the user about the original error: ``` .. 001_foo.js running.... Script '001_foo.js' failed to execute. Original error: Error: Some error ``` It's recommended for scripts to emit proper instances of `Error`. (Migration) scripts can be tracked as well but there are a couple of rules to be aware of: - Generally, tracking all scripts that have been executed by default is not a good thing because some scripts might be one-off operations. - OTOH, there might be scripts that should always be tracked by default - Therefore, we introduce a dedicated `migrations` directory in which scripts live that should be tracked by default - Any other scripts that does not live in the specified `migrations` directory will not be tracked **unless** - The new `--track` option was provided For more information see: https://notes.status.im/h8XwB7xkR7GKnfNh6OnPMQ
1 parent 0f59e0c commit 40c3d98

File tree

22 files changed

+927
-32
lines changed

22 files changed

+927
-32
lines changed

packages/core/core/constants.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -108,5 +108,6 @@
108108
},
109109
"environments": {
110110
"development": "development"
111-
}
112-
}
111+
},
112+
"defaultMigrationsDir": "migrations"
113+
}

packages/core/core/src/config.ts

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import { readJsonSync } from 'fs-extra';
2727
const cloneDeep = require('lodash.clonedeep');
2828
const { replaceZeroAddressShorthand } = AddressUtils;
2929

30-
import { getBlockchainDefaults, getContractDefaults } from './configDefaults';
30+
import { getBlockchainDefaults, getContractDefaults, embarkConfigDefaults } from './configDefaults';
3131

3232
const constants = readJsonSync(path.join(__dirname, '../constants.json'));
3333

@@ -45,6 +45,7 @@ export interface EmbarkConfig {
4545
generationDir?: string;
4646
plugins?: any;
4747
buildDir?: string;
48+
migrations: string;
4849
}
4950

5051
export class Config {
@@ -83,7 +84,7 @@ export class Config {
8384

8485
events: Events;
8586

86-
embarkConfig: any = {};
87+
embarkConfig: EmbarkConfig = embarkConfigDefaults;
8788

8889
context: any;
8990

@@ -629,17 +630,7 @@ export class Config {
629630
}
630631

631632
loadEmbarkConfigFile() {
632-
const configObject = {
633-
options: {
634-
solc: {
635-
"optimize": true,
636-
"optimize-runs": 200
637-
}
638-
},
639-
generationDir: "embarkArtifacts"
640-
};
641-
642-
this.embarkConfig = recursiveMerge(configObject, this.embarkConfig);
633+
this.embarkConfig = recursiveMerge(embarkConfigDefaults, this.embarkConfig);
643634

644635
const contracts = this.embarkConfig.contracts;
645636
// determine contract 'root' directories

packages/core/core/src/configDefaults.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,22 @@ import { join } from "path";
44

55
const constants = readJsonSync(join(__dirname, '../constants.json'));
66

7+
export const embarkConfigDefaults = {
8+
contracts: [],
9+
config: '',
10+
migrations: 'migrations',
11+
versions: {
12+
solc: "0.6.1"
13+
},
14+
options: {
15+
solc: {
16+
"optimize": true,
17+
"optimize-runs": 200
18+
}
19+
},
20+
generationDir: "embarkArtifacts"
21+
};
22+
723
export function getBlockchainDefaults(env) {
824
const defaults = {
925
clientConfig: {

packages/core/core/src/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,9 @@ export interface Configuration {
9191
cert: string;
9292
};
9393
};
94+
contractsConfig: {
95+
tracking?: boolean | string;
96+
};
9497
plugins: EmbarkPlugins;
9598
reloadConfig(): void;
9699
}

packages/embark/src/cmd/cmd.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ class Cmd {
1515
this.demo();
1616
this.build();
1717
this.run();
18+
this.exec();
1819
this.console();
1920
this.blockchain();
2021
this.simulator();
@@ -174,6 +175,30 @@ class Cmd {
174175
});
175176
}
176177

178+
exec() {
179+
program
180+
.command('exec [environment] [script|directory]')
181+
.option('-t, --track', __('Force tracking of migration script', false))
182+
.description(__("Executes specified scripts or all scripts in 'directory'"))
183+
.action((env, target, options) => {
184+
embark.exec({
185+
env,
186+
target,
187+
forceTracking: options.track
188+
}, (err) => {
189+
if (err) {
190+
console.error(err.message ? err.message : err);
191+
process.exit(1);
192+
}
193+
console.log('Done.');
194+
// TODO(pascal): Ideally this shouldn't be needed.
195+
// Seems like there's a pending child process at this point that needs
196+
// to be stopped.
197+
process.exit(0);
198+
});
199+
});
200+
}
201+
177202
console() {
178203
program
179204
.command('console [environment]')

packages/embark/src/cmd/cmd_controller.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,44 @@ class EmbarkController {
352352
});
353353
}
354354

355+
exec(options, callback) {
356+
357+
const engine = new Engine({
358+
env: options.env,
359+
embarkConfig: options.embarkConfig || 'embark.json'
360+
});
361+
362+
engine.init({}, () => {
363+
engine.registerModuleGroup("coreComponents", {
364+
disableServiceMonitor: true
365+
});
366+
engine.registerModuleGroup("stackComponents");
367+
engine.registerModuleGroup("blockchain");
368+
engine.registerModuleGroup("compiler");
369+
engine.registerModuleGroup("contracts");
370+
engine.registerModulePackage('embark-deploy-tracker', {
371+
plugins: engine.plugins
372+
});
373+
engine.registerModulePackage('embark-scripts-runner');
374+
375+
engine.startEngine(async (err) => {
376+
if (err) {
377+
return callback(err);
378+
}
379+
try {
380+
await engine.events.request2("blockchain:node:start", engine.config.blockchainConfig);
381+
const [contractsList, contractDependencies] = await compileSmartContracts(engine);
382+
await engine.events.request2("deployment:contracts:deploy", contractsList, contractDependencies);
383+
await engine.events.request2('scripts-runner:initialize');
384+
await engine.events.request2('scripts-runner:execute', options.target, options.forceTracking);
385+
} catch (err) {
386+
return callback(err);
387+
}
388+
callback();
389+
});
390+
});
391+
}
392+
355393
console(options) {
356394
this.context = options.context || [constants.contexts.run, constants.contexts.console];
357395
const REPL = require('./dashboard/repl.js');
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
embark-scripts-runner
2+
==========================
3+
4+
> Embark Scripts Runner
5+
6+
Plugin to run migration scripts for Smart Contract Deployment
7+
8+
Visit [embark.status.im](https://embark.status.im/) to get started with
9+
[Embark](https://github.com/embarklabs/embark).
10+
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
{
2+
"name": "embark-scripts-runner",
3+
"version": "5.1.0",
4+
"description": "Embark Scripts Runner",
5+
"repository": {
6+
"directory": "packages/plugins/scripts-runner",
7+
"type": "git",
8+
"url": "https://github.com/embarklabs/embark/"
9+
},
10+
"author": "Iuri Matias <[email protected]>",
11+
"license": "MIT",
12+
"bugs": "https://github.com/embarklabs/embark/issues",
13+
"keywords": [],
14+
"files": [
15+
"dist/"
16+
],
17+
"main": "./dist/index.js",
18+
"types": "./dist/index.d.ts",
19+
"embark-collective": {
20+
"build:node": true,
21+
"typecheck": true
22+
},
23+
"scripts": {
24+
"_build": "npm run solo -- build",
25+
"_typecheck": "npm run solo -- typecheck",
26+
"ci": "npm run qa",
27+
"clean": "npm run reset",
28+
"lint": "npm-run-all lint:*",
29+
"lint:ts": "tslint -c tslint.json \"src/**/*.ts\"",
30+
"qa": "npm-run-all lint _typecheck _build test",
31+
"reset": "npx rimraf dist embark-*.tgz package",
32+
"solo": "embark-solo",
33+
"test": "jest"
34+
},
35+
"dependencies": {
36+
"async": "2.6.1",
37+
"@babel/runtime-corejs3": "7.7.4",
38+
"core-js-pure": "3.6.4",
39+
"embark-core": "^5.2.0-nightly.1",
40+
"embark-i18n": "^5.1.1",
41+
"embark-logger": "^5.1.2-nightly.0",
42+
"embark-utils": "^5.2.0-nightly.1",
43+
"fs-extra": "8.1.0",
44+
"web3": "1.2.4"
45+
},
46+
"devDependencies": {
47+
"@babel/core": "7.7.4",
48+
"@types/node": "^10.5.3",
49+
"babel-jest": "24.9.0",
50+
"embark-solo": "^5.1.1-nightly.2",
51+
"embark-testing": "^5.1.0",
52+
"jest": "24.9.0",
53+
"npm-run-all": "4.1.5",
54+
"rimraf": "3.0.0",
55+
"tmp-promise": "1.1.0"
56+
},
57+
"engines": {
58+
"node": ">=10.17.0",
59+
"npm": ">=6.11.3",
60+
"yarn": ">=1.19.1"
61+
},
62+
"jest": {
63+
"collectCoverage": true,
64+
"testEnvironment": "node",
65+
"testMatch": [
66+
"**/test/**/*.js"
67+
],
68+
"transform": {
69+
"\\.(js|ts)$": [
70+
"babel-jest",
71+
{
72+
"rootMode": "upward"
73+
}
74+
]
75+
}
76+
}
77+
}
78+
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import path from 'path';
2+
import { Stats } from 'fs';
3+
4+
enum FileType {
5+
SymbolicLink = 'symbolic link',
6+
Socket = 'socket',
7+
Unknown = 'unknown'
8+
}
9+
10+
export class InitializationError extends Error {
11+
12+
name = 'InitalizationError';
13+
14+
constructor(public innerError: Error) {
15+
super();
16+
this.message = `Failed to initalize tracking file: Orignal Error: ${innerError}`;
17+
}
18+
}
19+
20+
export class UnsupportedTargetError extends Error {
21+
22+
name = 'UnsupportedTargetError';
23+
24+
constructor(public stats: Stats) {
25+
super();
26+
// We can't access `this` before `super()` is called so we have to
27+
// set `this.message` after that to get a dedicated error message.
28+
this.setMessage();
29+
}
30+
31+
private setMessage() {
32+
let ftype = FileType.Unknown;
33+
if (this.stats.isSymbolicLink()) {
34+
ftype = FileType.SymbolicLink;
35+
} else if (this.stats.isSocket()) {
36+
ftype = FileType.Socket;
37+
}
38+
this.message = `Script execution target not supported. Expected file path or directory, got ${ftype} type.`;
39+
}
40+
}
41+
42+
export class ScriptExecutionError extends Error {
43+
44+
name = 'ScriptExecutionError';
45+
46+
constructor(public target: string, public innerError: Error) {
47+
super();
48+
this.message = `Script '${path.basename(target)}' failed to execute. Original error: ${innerError.stack}`;
49+
}
50+
}
51+
52+
export class ScriptTrackingError extends Error {
53+
54+
name = 'ScriptTrackingError';
55+
56+
constructor(public innerError: Error) {
57+
super();
58+
this.message = `Couldn't track script due execption. Original error: ${innerError.stack}`;
59+
}
60+
}

0 commit comments

Comments
 (0)