Skip to content

Commit f5b3938

Browse files
committed
🎨 重构为异步操作.
1 parent 7da6dbf commit f5b3938

File tree

4 files changed

+143
-102
lines changed

4 files changed

+143
-102
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@micro-app/plugin-deploy-command",
3-
"version": "0.0.1",
3+
"version": "0.0.3",
44
"description": "[Plugin] auto deploy command plugin.",
55
"main": "src/index.js",
66
"scripts": {

src/deployCommit.js

Lines changed: 112 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,21 @@ const path = require('path');
55
const chalk = require('chalk');
66
const fs = require('fs');
77

8-
module.exports = function deployCommit(api, isHooks, deployConfig) {
8+
module.exports = function deployCommit(api, args, deployConfig) {
99
const logger = api.logger;
10-
const microAppConfig = api.self;
11-
const micros = api.micros;
12-
const microsConfig = api.microsConfig;
13-
const currentNodeModules = microAppConfig.nodeModules;
14-
const currentPkgInfo = microAppConfig.package;
10+
const root = api.root;
11+
// const micros = api.micros;
12+
// const microsConfig = api.microsConfig;
13+
// const currentNodeModules = microAppConfig.nodeModules;
14+
// const currentPkgInfo = microAppConfig.package;
15+
16+
api.applyPluginHooks('beforeCommandDeploy', { args, config: deployConfig });
1517

16-
api.applyPluginHooks('beforeCommandDeploy', { isHooks, logger, deployConfig, microsConfig });
18+
const isHooks = args.hooks;
1719

1820
const gitURL = deployConfig.git || '';
1921
if (!gitURL || typeof gitURL !== 'string') {
20-
logger.logo(`${chalk.yellow('need "deploy.git: \'ssh://...\'" in "micro-app.config.js"')}`);
22+
logger.warn('Need "deploy.git: \'ssh://...\'" in "micro-app.config.js"');
2123
return;
2224
}
2325
const gitPath = gitURL.replace(/^git\+/ig, '').split('#')[0];
@@ -51,7 +53,7 @@ module.exports = function deployCommit(api, isHooks, deployConfig) {
5153
}
5254

5355
if (!commitHash || typeof commitHash !== 'string') {
54-
logger.logo(`${chalk.yellow('Not Found commit Hash!')}`);
56+
logger.warn('Not Found commit Hash!');
5557
return;
5658
}
5759

@@ -62,88 +64,118 @@ module.exports = function deployCommit(api, isHooks, deployConfig) {
6264
}
6365
}
6466

65-
const gitRoot = path.resolve(microAppConfig.root, '.git');
67+
const gitRoot = path.resolve(root, '.git');
6668
if (fs.statSync(gitRoot).isDirectory()) {
6769
const deployDir = path.resolve(gitRoot, 'micro-deploy');
6870
if (fs.existsSync(deployDir)) {
6971
shelljs.rm('-rf', deployDir);
7072
}
7173
fs.mkdirSync(deployDir);
74+
7275
if (fs.statSync(deployDir).isDirectory()) {
73-
const execStr = `git clone "${gitPath}" -b ${gitBranch} "${deployDir}"`;
74-
logger.logo(`Deploy: ${chalk.blueBright(gitPath)}`);
75-
logger.logo(`Branch: ${chalk.blueBright(gitBranch)}`);
76-
logger.logo(`Hash: ${chalk.blueBright(commitHash)}`);
77-
logger.logo(`Name: ${chalk.blueBright(gitUser.name)}`);
78-
logger.logo(`Email: ${chalk.blueBright(gitUser.email)}`);
79-
const result = shelljs.exec(execStr, { silent: true });
80-
if (result.code) {
81-
logger.logo(`${result.code}: ${chalk.yellow(result.stderr.trim().split('\n').reverse()[0])}`);
82-
} else {
83-
const pkg = require(path.resolve(deployDir, 'package.json')) || {};
84-
const { dependencies = {}, devDependencies = {} } = pkg;
85-
const deps = Object.assign({}, dependencies, devDependencies);
86-
87-
const MICRO_APP_CONFIG_NAME = microAppConfig.packageName;
88-
if (deps[MICRO_APP_CONFIG_NAME]) {
89-
const gitp = deps[MICRO_APP_CONFIG_NAME];
90-
// update
91-
const ngitp = gitp.replace(/#[-_\d\w]+$/igm, `#${commitHash}`);
92-
93-
if (gitp === ngitp) {
94-
// not change
95-
shelljs.rm('-rf', deployDir);
96-
logger.logo(chalk.yellow('NOT MODIFIED!'));
97-
return;
98-
}
99-
if (ngitp) {
100-
if (dependencies[MICRO_APP_CONFIG_NAME]) {
101-
dependencies[MICRO_APP_CONFIG_NAME] = ngitp;
102-
}
103-
if (devDependencies[MICRO_APP_CONFIG_NAME]) {
104-
devDependencies[MICRO_APP_CONFIG_NAME] = ngitp;
105-
}
106-
fs.writeFileSync(path.resolve(deployDir, 'package.json'), JSON.stringify(pkg, null, 4), 'utf8');
76+
return runDeploy(api, args, deployConfig, { deployDir, gitPath, gitBranch, commitHash, gitUser, currBranch, gitMessage }).then(() => {
77+
if (fs.existsSync(deployDir)) {
78+
shelljs.rm('-rf', deployDir);
79+
}
10780

108-
// git config
109-
if (gitUser.name && typeof gitUser.name === 'string') {
110-
shelljs.exec(`git config user.name ${gitUser.name}`, { silent: true, cwd: deployDir });
111-
}
112-
if (gitUser.email && typeof gitUser.email === 'string') {
113-
shelljs.exec(`git config user.email ${gitUser.email}`, { silent: true, cwd: deployDir });
114-
}
115-
// commit + push
116-
const { message } = api.applyPluginHooks('modifyCommandDeployMessage', {
117-
message: `:package: auto deploy ${MICRO_APP_CONFIG_NAME} - ${currBranch} - ${commitHash.substr(0, 8)}${gitMessage}`,
118-
branch: currBranch,
119-
gitMessage,
120-
commitHash,
121-
name: MICRO_APP_CONFIG_NAME,
122-
});
123-
const spinner = logger.spinner('Auto Deploy...');
124-
spinner.start();
125-
const { code } = shelljs.exec(`git commit -a -m "${message}"`, { cwd: deployDir });
126-
if (code === 0) {
127-
const { code } = shelljs.exec('git push', { cwd: deployDir });
128-
if (code === 0) {
129-
shelljs.rm('-rf', deployDir);
130-
spinner.succeed(chalk.green('Success !'));
131-
return;
132-
}
133-
}
134-
spinner.fail(chalk.red('Fail !'));
135-
}
81+
api.applyPluginHooks('afterCommandDeploy', { args, config: deployConfig });
82+
}).catch(() => {
83+
if (fs.existsSync(deployDir)) {
84+
shelljs.rm('-rf', deployDir);
13685
}
137-
}
138-
}
86+
logger.error('Fail! Check your config, please');
13987

140-
if (fs.existsSync(deployDir)) {
141-
shelljs.rm('-rf', deployDir);
88+
api.applyPluginHooks('afterCommandDeploy', { args, config: deployConfig });
89+
});
14290
}
143-
logger.logo(chalk.redBright('Fail! Check your config, please'));
144-
} else {
145-
logger.logo(`${chalk.yellow('not found git')}`);
14691
}
14792

148-
api.applyPluginHooks('afterCommandDeploy', { isHooks, logger, deployConfig, microsConfig });
93+
logger.warn('Not Found git');
94+
95+
api.applyPluginHooks('afterCommandDeploy', { args, config: deployConfig });
14996
};
97+
98+
99+
function runDeploy(api, args, deployConfig, { deployDir, gitPath, gitBranch, commitHash, gitUser, currBranch, gitMessage }) {
100+
const logger = api.logger;
101+
const microAppConfig = api.self;
102+
103+
const execStr = `git clone "${gitPath}" -b ${gitBranch} "${deployDir}"`;
104+
logger.logo(`Deploy: ${chalk.blueBright(gitPath)}`);
105+
logger.logo(`Branch: ${chalk.blueBright(gitBranch)}`);
106+
logger.logo(`Hash: ${chalk.blueBright(commitHash)}`);
107+
logger.logo(`Name: ${chalk.blueBright(gitUser.name)}`);
108+
logger.logo(`Email: ${chalk.blueBright(gitUser.email)}`);
109+
const result = shelljs.exec(execStr, { silent: true });
110+
if (result.code) {
111+
logger.logo(`${result.code}: ${chalk.yellow(result.stderr.trim().split('\n').reverse()[0])}`);
112+
} else {
113+
const pkg = require(path.resolve(deployDir, 'package.json')) || {};
114+
const { dependencies = {}, devDependencies = {} } = pkg;
115+
const deps = Object.assign({}, dependencies, devDependencies);
116+
117+
const MICRO_APP_CONFIG_NAME = microAppConfig.packageName;
118+
if (deps[MICRO_APP_CONFIG_NAME]) {
119+
const gitp = deps[MICRO_APP_CONFIG_NAME];
120+
// update
121+
const ngitp = gitp.replace(/#[-_\d\w]+$/igm, `#${commitHash}`);
122+
123+
if (gitp === ngitp) {
124+
// not change
125+
logger.warn('NOT MODIFIED!');
126+
return Promise.resolve();
127+
}
128+
if (ngitp) {
129+
if (dependencies[MICRO_APP_CONFIG_NAME]) {
130+
dependencies[MICRO_APP_CONFIG_NAME] = ngitp;
131+
}
132+
if (devDependencies[MICRO_APP_CONFIG_NAME]) {
133+
devDependencies[MICRO_APP_CONFIG_NAME] = ngitp;
134+
}
135+
fs.writeFileSync(path.resolve(deployDir, 'package.json'), JSON.stringify(pkg, null, 4), 'utf8');
136+
137+
// git config
138+
if (gitUser.name && typeof gitUser.name === 'string') {
139+
shelljs.exec(`git config user.name ${gitUser.name}`, { silent: true, cwd: deployDir });
140+
}
141+
if (gitUser.email && typeof gitUser.email === 'string') {
142+
shelljs.exec(`git config user.email ${gitUser.email}`, { silent: true, cwd: deployDir });
143+
}
144+
// commit + push
145+
const { message } = api.applyPluginHooks('modifyCommandDeployMessage', {
146+
args, config: deployConfig,
147+
message: `:package: auto deploy ${MICRO_APP_CONFIG_NAME} - ${currBranch} - ${commitHash.substr(0, 8)}${gitMessage}`,
148+
branch: currBranch,
149+
gitMessage,
150+
commitHash,
151+
name: MICRO_APP_CONFIG_NAME,
152+
});
153+
154+
if (!message) {
155+
logger.error('modifyCommandDeployMessage() must be retrun { message } !!!');
156+
return Promise.reject();
157+
}
158+
159+
return new Promise((resolve, reject) => {
160+
const spinner = logger.spinner('Auto Deploy...');
161+
spinner.start();
162+
shelljs.exec(`git commit -a -m "${message}"`, { cwd: deployDir }, function(code, stdout, stderr) {
163+
if (code === 0) {
164+
shelljs.exec('git push', { cwd: deployDir }, function(code, stdout, stderr) {
165+
if (code === 0) {
166+
spinner.succeed(chalk.green('Success !'));
167+
return resolve();
168+
}
169+
spinner.fail(chalk.red('Fail !') + stderr);
170+
return reject(stderr);
171+
});
172+
}
173+
spinner.fail(chalk.red('Fail !') + stderr);
174+
return reject(stderr);
175+
});
176+
});
177+
}
178+
}
179+
}
180+
return Promise.resolve();
181+
}

src/index.js

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,17 @@
22

33
module.exports = function DeployCommand(api, opts = {}) {
44

5+
api.assertVersion('>=0.1.5');
6+
57
const path = require('path');
68
const chalk = require('chalk');
79
const tryRequire = require('try-require');
810

911
// commands
1012
require('./commands/version')(api);
1113

12-
api.registerMethod('beforeCommandDeploy', {
13-
type: api.API_TYPE.EVENT,
14-
description: '发布前事件',
15-
});
16-
api.registerMethod('afterCommandDeploy', {
17-
type: api.API_TYPE.EVENT,
18-
description: '发布后事件',
19-
});
20-
api.registerMethod('modifyCommandDeployMessage', {
21-
type: api.API_TYPE.MODIFY,
22-
description: '发布消息二次编辑事件',
23-
});
14+
// methods
15+
require('./methods')(api, opts);
2416

2517
// start
2618
api.registerCommand('deploy', {
@@ -29,7 +21,7 @@ module.exports = function DeployCommand(api, opts = {}) {
2921
options: {
3022
'-': 'deploy last commit',
3123
'--hooks': 'git commit hooks.',
32-
'-c <config>': '指定配置文件路径, 相对于根路径. (默认为根目录下的: "micro-app.deploy.config.js")',
24+
'--config <config>': '指定配置文件路径, 相对于根路径. 默认为根目录下的: "micro-app.deploy.config.js"',
3325
},
3426
details: `
3527
Examples:
@@ -38,18 +30,18 @@ Examples:
3830
${chalk.gray('# git hooks')}
3931
micro-app deploy --hooks
4032
${chalk.gray('# config file')}
41-
micro-app deploy -c micro-app.deploy.config.js
33+
micro-app deploy --config micro-app.deploy.config.js
4234
4335
Config:
4436
{
45-
git: '',
37+
git: '', ${chalk.gray('// git 地址')}
4638
${chalk.gray('branch: \'\',')}
47-
branch: {
39+
branch: { ${chalk.gray('// git branch')}
4840
name: '',
4941
extends: true,
5042
},
51-
message: '',
52-
user: {
43+
message: '', ${chalk.gray('// git commit message')}
44+
user: { ${chalk.gray('// git user info')}
5345
name: '',
5446
email: '',
5547
},
@@ -58,17 +50,16 @@ Config:
5850
}, args => {
5951
const logger = api.logger;
6052

61-
const isHooks = args.hooks;
6253
const configFile = args.c || 'micro-app.deploy.config.js';
6354
const deployConfig = tryRequire(path.resolve(api.root, configFile));
6455

6556
if (!deployConfig || typeof deployConfig !== 'object') {
66-
logger.logo(`${chalk.yellow('need "micro-app.deploy.config.js"')}`);
57+
logger.warn('Not Found "micro-app.deploy.config.js"');
6758
return;
6859
}
6960

7061
const deployCommit = require('./deployCommit');
71-
return deployCommit(api, isHooks, Object.assign({}, deployConfig, opts));
62+
return deployCommit(api, args, Object.assign({}, deployConfig, opts));
7263
});
7364

7465

src/methods.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
module.exports = function registerMethods(api, opts = {}) {
4+
5+
api.registerMethod('beforeCommandDeploy', {
6+
type: api.API_TYPE.EVENT,
7+
description: '发布前事件',
8+
});
9+
api.registerMethod('afterCommandDeploy', {
10+
type: api.API_TYPE.EVENT,
11+
description: '发布后事件',
12+
});
13+
api.registerMethod('modifyCommandDeployMessage', {
14+
type: api.API_TYPE.MODIFY,
15+
description: '发布消息二次编辑事件',
16+
});
17+
18+
};

0 commit comments

Comments
 (0)