forked from bobobo1618/docpad-plugin-sunny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsunny.plugin.js
265 lines (244 loc) · 9.52 KB
/
sunny.plugin.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Generated by CoffeeScript 2.5.1
(function() {
// Yay requires.
var TaskGroup, doUpload, handle, handleEnv, handleEnvPrefix, http, mime, sunny, uploadData, util,
boundMethodCheck = function(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new Error('Bound instance method accessed before binding'); } };
sunny = require('sunny');
mime = require('mime');
http = require('http');
util = require('util');
({TaskGroup} = require('taskgroup'));
uploadData = function(container, path, headers, data, retryLimit, retries, next) {
var doIt, writeStream;
// Test for whether to retry the upload.
retries = retries != null ? retries : 0;
retryLimit = retryLimit != null ? retryLimit : 2;
doIt = !retryLimit || (retryLimit && (retries <= retryLimit)) || retryLimit === -1 ? true : false;
if (doIt) {
if (retries) {
console.log(`Retrying upload of ${path} to ${container.name}: Attempts: ${retries}`);
}
//Open the stream and do the write.
writeStream = container.putBlob(path, headers);
writeStream.on('error', function(err) {
console.log(`Error uploading ${path} to ${container.name}`);
// Recall this function with the retry counter incremented. Yay recursion!
return uploadData(container, path, headers, data, retryLimit, retries + 1, next);
});
writeStream.on('end', function(results, meta) {
console.log(`Uploaded ${path} to ${container.name}`);
return next();
});
writeStream.write(data);
return writeStream.end();
} else {
return next(`Upload for ${path} to ${container.name} has failed ${retries} times. Giving up.`);
}
};
// Does the upload after Sunny has been set up and such.
doUpload = function(docpad, container, acl, retryLimit, next) {
var cloudHeaders, tasks;
// Seems obvious enough. Sets files to public read in the cloud.
if (acl != null) {
if (acl === false) {
cloudHeaders = {};
} else {
cloudHeaders = {
"acl": acl
};
}
} else {
cloudHeaders = {
"acl": 'public-read'
};
}
tasks = new TaskGroup().once('complete', function(err) {
return next(err);
});
docpad.getFiles({
write: true
}).forEach(function(file) {
var data, err, headers, key, length, path, ref, type, value;
path = file.attributes.relativeOutPath;
// Gets the correct data from Docpad.
data = file.get('contentRendered') || file.get('content') || (file.getData && file.getData()) || file.getContent() || "";
if (!data) {
return next(`No data for file ${path}`);
}
length = data.length;
type = mime.lookup(path); //file.get('contentType')
headers = {
"Content-Length": length,
"Content-Type": type
};
try {
// Merge the headers with those Docpad has.
if (file.get('headers') != null) {
ref = file.get('headers');
for (key in ref) {
value = ref[key];
headers[key] = value;
} //and file.get('headers').length?
}
} catch (error) {
err = error;
console.log(err);
console.dir(file);
}
return tasks.addTask(function(complete) {
return uploadData(container, path, {
headers: headers,
cloudHeaders: cloudHeaders
}, data, retryLimit, 0, complete);
});
});
return tasks.run();
};
handle = function(docpad, sunnyConfig, sunnyContainer, defaultACL, retryLimit, next) {
var connection, containerReq;
// Test the configuration and try it.
if ((sunnyConfig.provider != null) && (sunnyConfig.account != null) && (sunnyConfig.secretKey != null) && (sunnyContainer != null)) {
// Get a connection to the provider.
connection = sunny.Configuration.fromObj(sunnyConfig).connection;
// Prepare a request to the provider for the container. Checks to make sure the container exists.
containerReq = connection.getContainer(sunnyContainer, {
validate: true
});
containerReq.on('error', function(err) {
return console.log(`Received error trying to connect to provider: \n ${err}`);
});
containerReq.on('end', function(results, meta) {
var container;
if (results) { // not sure exactly how, but the 'end' can get called more than once with null params on the second call
container = results.container;
console.log(`Got container ${container.name}.`);
// Do the upload.
return doUpload(docpad, container, defaultACL, retryLimit, next);
}
});
return containerReq.end();
} else {
return next(`One of the config variables is missing. Printing config:
${util.inspect(sunnyConfig)}
Container is ${sunnyContainer}`);
}
};
handleEnvPrefix = function(docpad, prefix, next) {
var sunnyACL, sunnyConfig, sunnyContainer, sunnyRetryLimit;
sunnyConfig = {
provider: process.env[`${prefix}PROVIDER`],
account: process.env[`${prefix}ACCOUNT`],
secretKey: process.env[`${prefix}SECRETKEY`],
ssl: process.env[`${prefix}SSL`],
authUrl: process.env[`${prefix}AUTHURL`]
};
sunnyContainer = process.env[`${prefix}CONTAINER`];
sunnyACL = process.env[`${prefix}ACL`];
sunnyRetryLimit = process.env[`${prefix}RETRY_LIMIT`];
// Parse the environment variable for ssl.
sunnyConfig.ssl = (typeof sunnyConfig.ssl === 'string') && (sunnyConfig.ssl.toLowerCase() === 'true');
return handle(docpad, sunnyConfig, sunnyContainer, sunnyACL, sunnyRetryLimit, next);
};
handleEnv = function(docpad, config, next) {
var i, len, prefix, ref, results1;
if (config.envPrefixes.length > 0) {
ref = config.envPrefixes;
results1 = [];
for (i = 0, len = ref.length; i < len; i++) {
prefix = ref[i];
results1.push(handleEnvPrefix(docpad, prefix, next));
}
return results1;
} else {
return handleEnvPrefix(docpad, "DOCPAD_SUNNY_", next);
}
};
module.exports = function(BasePlugin) {
var docpadSunnyPlugin;
return docpadSunnyPlugin = (function() {
class docpadSunnyPlugin extends BasePlugin {
constructor() {
super(...arguments);
// {
// sunny:{
// provider: undefined
// account: undefined
// secretKey: undefined
// ssl: undefined
// authUrl: undefined
// },
// container: undefined,
// acl: undefined
// retryLimit: undefined
// }
this.deployWithSunny = this.deployWithSunny.bind(this);
this.consoleSetup = this.consoleSetup.bind(this);
}
deployWithSunny(next) {
var config, docpad, errMsg;
boundMethodCheck(this, docpadSunnyPlugin);
docpad = this.docpad;
config = this.getConfig();
if (config.cloudConfigs.length > 0 || config.configFromEnv) {
docpad.log('info', `Found ${config.cloudConfigs.length} configurations in file.`);
return this.docpad.generate(function(err) {
var cloudConfig, i, len, ref, tasks;
if (err) {
return next(err);
}
tasks = new TaskGroup().once('complete', function(err) {
return next(err);
});
if (config.configFromEnv) {
docpad.log('info', "Grabbing configs from environment.");
tasks.addTask(function(complete) {
return handleEnv(docpad, config, complete);
});
}
ref = config.cloudConfigs;
for (i = 0, len = ref.length; i < len; i++) {
cloudConfig = ref[i];
tasks.addTask(function(complete) {
return handle(docpad, cloudConfig.sunny, cloudConfig.container, cloudConfig.acl, cloudConfig.retryLimit, complete);
});
}
return tasks.run();
});
} else {
errMsg = 'No configs found';
docpad.log('warn', errMsg);
return next(errMsg);
}
}
consoleSetup(opts) {
var commander, config, consoleInterface, docpad;
boundMethodCheck(this, docpadSunnyPlugin);
docpad = this.docpad;
config = this.getConfig();
({consoleInterface, commander} = opts);
commander.command('deploy-sunny').description("Deploys your website to any provider allowed by Sunny.").action(consoleInterface.wrapAction(this.deployWithSunny));
return this;
}
};
docpadSunnyPlugin.prototype.name = "sunny";
docpadSunnyPlugin.prototype.config = {
defaultACL: 'public-read',
onlyIfProduction: true,
configFromEnv: false,
envPrefixes: [],
cloudConfigs: []
};
return docpadSunnyPlugin;
}).call(this);
};
//writeAfter: (opts, next)->
// next?()
// if (not @config.onlyIfProduction) or (process.env.NODE_ENV is "production")
// if @config.configFromEnv
// console.log "Sunny plugin getting config from environment..."
// handleEnv @docpad, @config
// if @config.cloudConfigs.length > 0
// console.log "Found #{@config.cloudConfigs.length} configurations in config file."
// for cloudConfig in @config.cloudConfigs
// handle @docpad, cloudConfig.sunny, cloudConfig.container, cloudConfig.acl, cloudConfig.retryLimit
}).call(this);