/
index.js
360 lines (298 loc) · 11.1 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
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
var Promise = this.Promise || require('promise');
var request = require('superagent');
var async = require('async');
var DEFAULT_RETRIES = 3;
// https://github.com/Reposoft/rweb/blob/v1.6.0/repos-web/edit/upload/index.php#L24
var UPLOAD_PROP_PREFIX = 'prop_';
function ReposUpload(config) {
if (!(this instanceof ReposUpload)) {
return new ReposUpload(config);
}
if (!config.hostname) throw new Error('Missing option "hostname" [http://localhost]');
if (!config.dataRepository) throw new Error('Missing option "dataRepository" [/svn/lean-data]');
var leadingRe = /^\//;
var trailingRe = /\/$/;
if (trailingRe.test(config.hostname)) throw new Error('Invalid "hostname" option provided. Remove trailing slash!');
if (trailingRe.test(config.dataRepository)) throw new Error('Invalid "dataRepository" option provided. Remove trailing slash!');
if (!leadingRe.test(config.dataRepository)) throw new Error('Invalid "dataRepository" option provided. Include leading slash!');
var auth = config.auth || { user: '', password: '' };
// We check against undefined and not just falsy values as 0 should be valid here
var nRetries = DEFAULT_RETRIES;
if (config.nRetries !== undefined) nRetries = config.nRetries;
function createRepository(callback) {
var repoName = config.dataRepository.split('/').pop();
fileExists('/' + repoName).then(function (status) {
if (status === 200) return callback(null, status);
if (status !== 404) return callback(new Error('Unknown error, status: ' + status));
// Repository missing. Create it
request
.post(config.hostname + '/admin/repocreate')
.auth(auth.user, auth.password)
.type('form')
.accept('json')
.send({ reponame: repoName })
.end(function (err, result) {
if (err) return callback(err);
callback(null);
});
}, callback);
}
function createFile(fileUrl, data, callback) {
var versionedProps = {};
if (typeof callback === 'object' && typeof arguments[3] === 'function') {
versionedProps = callback;
callback = arguments[3];
}
var createMissing = fileExists(fileUrl)
.then(function(status) {
if (status === 200) return Promise.resolve();
if (status === 404) {
if (typeof File !== 'undefined' && data instanceof File) {
return addFile(fileUrl, data, versionedProps);
}
var dataString = compileData(data);
return addFile(fileUrl, dataString, versionedProps);
}
// Some other error, how do we handle this?
return Promise.reject(new Error('Unknown error, status: ' + status));
});
createMissing.then(function (result) {
callback(null, result);
}, callback);
}
// Like createFile but assumes an existing file
function writeFile(fileUrl, data, callback) {
var createMissing = fileExists(fileUrl)
.then(function(status) {
var dataString = compileData(data);
if (status === 200) return updateFile(fileUrl, dataString);
if (status === 404) return addFile(fileUrl, dataString);
// Some other error, how do we handle this?
return Promise.reject('Unknown error, status: ' + status);
});
createMissing.then(function (result) {
callback(null, result);
}, callback);
}
function addFile(fileUrl, fileData, versionedProps) {
return createFoldersForFile(fileUrl).then(function () {
var filename = fileUrl.split('/').pop();
var path = fileUrl
.replace(config.hostname, '')
.replace(config.dataRepository, '')
.replace(filename, '');
var base = config.dataRepository.split('/').pop();
var data = {
base: base,
target: path,
name: filename,
fromrev: 'HEAD',
message: 'repos-upload add file',
type: 'upload',
create: 'yes'
};
for (var propname in versionedProps) {
if (versionedProps.hasOwnProperty(propname)) {
data[UPLOAD_PROP_PREFIX + propname] = versionedProps[propname];
}
}
var url = config.hostname + config.dataRepository + '/?rweb=e.upload';
if (typeof File !== 'undefined' && fileData instanceof File) {
var formData = new FormData();
Object.keys(data).map(function(key) {
formData.set(key, data[key]);
});
formData.set('userfile', fileData);
data = formData;
} else {
data.usertext = fileData;
}
return postFile(url, data);
});
}
function updateFile(fileUrl, fileData) {
return createFoldersForFile(fileUrl).then(function () {
var data = {
usertext: fileData,
fromrev: 'HEAD',
message: 'repos-upload update file',
type: 'upload'
};
var filePath = fileUrl
.replace(config.hostname, '')
.replace(config.dataRepository, '');
var url = config.hostname + config.dataRepository + filePath + '/?rweb=e.upload';
return postFile(url, data);
});
}
function postFile(url, data) {
return new Promise(function(fulfill, reject) {
request
.post(url)
.auth(auth.user, auth.password)
.type(typeof FormData !== 'undefined' && data instanceof FormData ? undefined : 'form')
.accept('json')
.send(data)
.end(function(err, res) {
if (err) {
var msg = parseErrorMsg(err);
return reject(msg);
}
else if (res.ok) return fulfill(true);
else reject('Unknown error');
});
});
}
// info isn't a promise because you use it to see current status, not to fetch data
// The benefit compared to the cheaper HEAD request is that you get info about latest commit, and size directly instead of through headers
function info(path, errCallback, jsonCallback) {
request
.get(config.hostname + path)
.query({ rweb: 'json', serv: 'json' })
.set('Accept', 'application/json') // RWEB-ISSUE: understands only serv=json atm
.auth(auth.user, auth.password)
.end(function(err, res) {
// RWEB-ISSUE returns status 500 if the file does not exist
if (res.statusCode === 500 && /Could not read entry for URL/.test(res.text)) {
res.statusCode = 404; // TBD set .status too?
return errCallback(err, res);
}
if (err) return errCallback(err, res);
var svnlist = res.body;
// RWEB-ISSUE doesn't set Content-Type application/json on json resources
if (svnlist === null && res.type === 'text/plain') {
svnlist = JSON.parse(res.text);
}
var keys = Object.keys(svnlist.list);
if (keys.length !== 1) throw new Error('Unexpected info, multiple entries. Is it a folder? Use .details() instead, as info is based on ls.');
if (typeof svnlist.list[keys[0]].size === 'string') { // RWEB-ISSUE size is an integer but of string type
svnlist.list[keys[0]].size = parseInt(svnlist.list[keys[0]].size);
}
return jsonCallback(svnlist.list[keys[0]]);
});
}
// details is an expensive call that returns entry stats, recent history etc
function details(path, callback) {
var details = new Promise(function(fulfill, reject) {
request
.get(config.hostname + path)
.query({ rweb: 'details', serv: 'json' })
.set('Accept', 'application/json') // but rweb understands only serv=json atm
.auth(auth.user, auth.password)
.end(function(err, res) {
if (!res && !(err || {}).statusCode) {
return reject(new Error('Missing status code for: ' + path));
}
fulfill(res.body || JSON.parse(res.text)); // rweb up to 1.6 does not set Content-Type properly
});
});
details.then(function(json) {
callback(null, json);
});
}
function fileExists(path) {
return new Promise(function(fulfill, reject) {
request
.head(config.hostname + path).redirects(2)
.auth(auth.user, auth.password)
.end(function(err, res) {
if (!res && !(err || {}).statusCode) {
return reject(new Error('Missing status code for: ' + path));
}
fulfill((res || {}).statusCode);
});
});
}
function fetchFile(path) {
var url = config.hostname + path;
return new Promise(function(fulfill, reject) {
request
.get(url)
.auth(auth.user, auth.password)
.end(function(err, res) {
if (err) {
return reject('Unable to get file with url: "' + url + '", status: ' + err);
}
return fulfill(res.body);
});
});
}
function createFoldersForFile(fileUrl) {
var dataRepository = config.dataRepository;
var fileName = fileUrl.split('/').pop();
var folders = fileUrl
.replace(config.hostname, '')
.replace(dataRepository, '')
.replace(fileName, '')
.replace(/(^\/)|(\/$)/g, '') // Remove leading and trailing slashes
.split('/');
return fillFolders(dataRepository, folders);
}
function fillFolders(parentFolder, folders) {
if (folders.length === 0) return Promise.resolve();
var path = [parentFolder, folders[0]].join('/');
return fileExists(path + '/')
.then(function (status) {
if (status === 200) return fillFolders(path, folders.slice(1));
if (status === 404) {
var target = parentFolder.replace(config.dataRepository, '') + '/';
return addFolder(target, folders[0]).then(function () {
return fillFolders(path, folders.slice(1));
});
}
else return Promise.reject('Unkown folder status ' + status + ' for ' + path);
});
}
function addFolder(parentFolder, folderName) {
return new Promise(function (resolve, reject) {
var hostname = config.hostname;
var dataRepository = config.dataRepository;
var base = dataRepository.split('/').pop();
var data = {
base: base,
target: parentFolder,
name: folderName,
message: 'repos-upload add folder',
submit: 'Create'
};
var url = hostname + dataRepository + '/?rweb=e.mkdir';
request
.post(url)
.auth(auth.user, auth.password)
.type('form')
.accept('json')
.send(data)
.end(function (err, res) {
if (err) {
var msg = parseErrorMsg(err);
return reject(msg);
}
var body = JSON.parse(res.text);
if (body && body.successful) resolve(body.result);
else (reject(body));
});
});
}
this.createRepository = createRepository;
this.createFile = async.retryable(nRetries, createFile);
this.writeFile = async.retryable(nRetries, writeFile);
this.info = info;
this.details = async.retryable(nRetries, details);
return this;
}
function parseErrorMsg(err) {
var error;
try {
error = JSON.parse(err.response.text).error;
} catch (e) {
console.error(e);
}
var msg = error ? error.split('<br />')[0] :
'Unknown error';
return msg;
}
function compileData(data) {
if (typeof data === 'string') return data;
else return JSON.stringify(data, null, 2);
}
exports.ReposUpload = ReposUpload;