-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
105 lines (86 loc) · 2.91 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
'use strict';
const unzip = require('unzip2');
const fs = require('fs');
const path = require('path');
const archiver = require('archiver');
const spawnSync = require('child_process').spawnSync;
const Bluebird = require('bluebird');
const glob = require('glob-all');
const rimraf = require('rimraf');
const _ = require('lodash');
class ServerlessPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.hooks = {
'after:deploy:createDeploymentArtifacts': this.transform.bind(this),
};
}
transform() {
return new Bluebird((resolve, reject) => {
const servicePath = this.serverless.config.servicePath;
// unzip
const stream = fs.createReadStream(path.join(servicePath, `.serverless/${this.serverless.service.service}.zip`))
.pipe(unzip.Extract({ path: path.join(servicePath, '.serverless/tmpCoffeeDirectory') }));
stream.on('error', (error) => {
reject(error);
});
stream.on('finish', () => {
// compile
const args = [
'--compile',
'tmpCoffeeDirectory'
];
const options = {
cwd: path.join(servicePath, '.serverless'),
};
var pathToCoffee = path.join(__dirname, '..', '.bin/coffee');
if (!fs.existsSync(pathToCoffee))
pathToCoffee = 'coffee'
const result = spawnSync(pathToCoffee, args, options);
const sterr = result.stderr.toString();
if (sterr) {
reject(sterr);
}
// zip
this.serverless.cli.log('Packaging service with compiled files...');
const patterns = ['**'];
const tmpCoffeeDirectory = '.serverless/tmpCoffeeDirectory';
const zip = archiver.create('zip');
const artifactFilePath = `.serverless/${this.serverless.service.service}.zip`;
this.serverless.utils.writeFileDir(artifactFilePath);
const output = fs.createWriteStream(artifactFilePath);
output.on('open', () => {
zip.pipe(output);
const files = glob.sync(patterns, {
cwd: tmpCoffeeDirectory,
dot: true,
silent: true,
follow: true,
});
files.forEach((filePath) => {
const fullPath = path.resolve(tmpCoffeeDirectory, filePath);
const stats = fs.statSync(fullPath);
if (!stats.isDirectory(fullPath)) {
zip.append(fs.readFileSync(fullPath), {
name: filePath,
mode: stats.mode,
});
}
});
zip.finalize();
});
zip.on('error', err => reject(err));
output.on('close', () => {
try {
rimraf.sync(tmpCoffeeDirectory, { disableGlob: true });
} catch (err) {
reject(err);
}
resolve(artifactFilePath);
});
});
});
}
}
module.exports = ServerlessPlugin;