-
Notifications
You must be signed in to change notification settings - Fork 0
/
datapackage.js
343 lines (320 loc) · 8.94 KB
/
datapackage.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
var JSV = require("JSV").JSV
, url = require('url')
, request = require('request')
, marked = require('marked')
, csv = require('csv')
, dpkgCreateReadStream = require('./lib/createReadStream')
;
var dpSchema = {
"title": "Data Package",
"type" : "object",
"properties": {
name: {
type: 'string',
required: true
},
title: {
type: 'string'
},
sources: {
type: 'array'
},
licenses: {
type: 'array'
},
resources: {
type: 'array',
required: true
}
}
};
// Validate the provided DataPackage.json file
//
// @param raw: datapackage.json string to validate (note method will take
// care of parsing the string and checking it is valid JSON)
exports.validate= function(raw) {
var env = JSV.createEnvironment();
try {
var json = JSON.parse(raw);
} catch(e) {
return { valid: false, errors: [{message: 'Invalid JSON'}]};
}
var required = [ 'name', 'resources' ];
var recommended = [
'title',
'licenses',
'datapackage_version',
'description',
'sources',
'keywords'
];
var report = env.validate(json, dpSchema);
var errors = report.errors;
if (errors.length === 0) {
return {
valid: true,
errors: []
};
} else {
return {
valid: false,
errors: errors
};
}
}
exports.validateUrl = function(dpurl, callback) {
request(dpurl, function(err, response, body) {
if (err) {
callback({
valid: false,
errors: [{
message: err.toString()
}]
});
}
else if (response.statusCode !== 200) {
callback({
valid: false,
errors: [{
message: 'Error loading the datapackage.json file. HTTP Error code: ' + response.statusCode
}]
});
} else {
callback(exports.validate(body));
}
});
}
// Load a datapackage.json from a URL and normalize it
//
// Normalize is as per `normalize`
exports.load = function(datapackage_url, cb) {
var datapackage_url = exports.normalizeDataPackageUrl(datapackage_url);
var base = datapackage_url.replace(/datapackage.json$/g, '');
request(datapackage_url, function(error, response, body) {
if (error) {
cb(error);
return;
} else if (response.statusCode != 200) {
cb({message: 'Unable to access file. Status code: ' + response.statusCode});
return;
}
// TODO: handle bad JSON
try {
var datapackage = JSON.parse(body);
} catch(e) {
cb({message: 'datapackage.json is invalid JSON. Details: ' + e.message});
return;
}
// now dig up and use README if it exists
var readme_url = base + 'README.md'
request(readme_url, function(err, resp, body) {
if (!err) {
datapackage['readme'] = body.replace(/\r\n/g, '\n');
}
datapackage = exports.normalize(datapackage, base);
cb(null, datapackage);
});
});
};
// ## loadMany
//
// Load all the Data Packages info at the provided urls and return in one big
// hash (keyed by Data Package names)
//
// @return: via the callback
exports.loadMany = function(urls, callback) {
var output = {}
, count = urls.length
;
function done() {
count--;
if (count == 0) {
callback(null, output);
}
}
urls.forEach(function(url) {
exports.load(url, function(err, dpjson) {
if (err) {
console.error(url, err)
} else {
output[dpjson.name] = dpjson;
}
done();
});
});
}
exports.normalizeDataPackageUrl = function(url) {
var ghNotRaw = 'https://github.com';
if (url.indexOf(ghNotRaw) != -1 && url.indexOf('datapackage.json') == -1) {
url = url.replace(ghNotRaw, 'https://raw.github.com') + '/master/datapackage.json';
}
if (url.indexOf('datapackage.json') == -1) {
url = url.replace(/\/$/, '');
url += '/datapackage.json'
}
return url;
};
// Normalize a DataPackage DataPackage.json in various ways
//
// @param datapackage: datapackage object (already parsed from JSON)
// @param url: [optional] url to datapackage.json or the root directory in which it is contained
exports.normalize = function(datapackage, url_) {
var base = url_ ? url_.replace(/datapackage.json$/g, '') : '';
// ensure certain fields exist
if (! ('description' in datapackage)) {
datapackage.description = '';
}
// set description as first paragraph of readme if no description
if (!datapackage.description && 'readme' in datapackage) {
var html = marked(datapackage.readme);
html = html.replace(/<p>/g, '\n<p>');
var plain = stripTags(html).split('\n\n')[0].replace(' \n', '').replace('\n', ' ').replace(/^ /, '');
datapackage.description = plain;
} else if (!datapackage.readme) {
datapackage.readme = datapackage.description;
}
datapackage.readme_html = marked(datapackage.readme);
datapackage.resources.forEach(function(info) {
if (!info.url && info.path) {
info.url = base + info.path;
}
if (!info.name) {
info.name = _nameFromUrl(info.url);
}
// upgrade for change in JTS spec - https://github.com/dataprotocols/dataprotocols/issues/60
if (info.schema && info.schema.fields) {
info.schema.fields = info.schema.fields.map(function(field) {
if (!field.name) {
field.name = field.id;
// TODO: (?) do we also want delete the id attribute
// delete field.id;
}
return field;
});
}
});
// special cases for github data packages
if (base.indexOf('raw.github.com') != -1) {
var offset = base.split('/').slice(3,5).join('/');
var githubrepo = 'https://github.com/' + offset;
if (!('homepage' in datapackage)) {
datapackage.homepage = githubrepo;
}
if (!('bugs' in datapackage)) {
datapackage.bugs = {
url: githubrepo + '/issues'
}
}
}
// have a stab at setting a sensible homepage if none there yet
if (!('homepage' in datapackage)) {
datapackage.homepage = base;
}
return datapackage;
}
// Create a DataPackage.json
//
// @param info: a hash containing data to use for datapackage info
// most importantly it can contain a url or resource.url pointing
// to a data file (CSV). This file will be analyzed and used to
// create the resource entry in the datapackage.json.
exports.create = function(info, cb) {
if (info === null) {
info = {};
}
var out = {};
out.name = info.name || '';
out.title = info.title || '';
out.description = info.description || '';
if (!info.licenses) {
out.licenses = [{
'id': 'odc-pddl',
'name': 'Public Domain Dedication and License',
'version': '1.0',
'url': 'http://opendatacommons.org/licenses/pddl/1.0/'
}];
}
if (!out.resources) {
out.resources = [];
if ('url' in info || 'resource.url' in info) {
var resurl = info.url || info['resource.url'];
var name = _nameFromUrl(resurl);
var tmp = {
name: name,
url: resurl,
format: 'csv',
mediatype: 'text/csv'
};
var stream = request(resurl);
stream.on('response', function(resp) {
if (resp.statusCode != 200) {
var err = {
message: 'Got error code ' + resp.statusCode + ' while attempting to access ' + resurl
}
cb(err, out);
} else {
exports.createJsonTableSchema(stream, function(error, schema) {
tmp.schema = schema;
out.resources.push(tmp);
cb(null, out);
});
}
});
return;
}
}
cb(null, out);
}
// Create a (JSON Table) Schema for CSV data in input stream
exports.createJsonTableSchema = function(stream, cb) {
var out = {};
var parser = csv();
parser.from(stream)
// note somewhat HACKy approach to only processing the first bit of the file
.transform(
function(data, idx, callback) {
if (idx==0) {
out.fields = data.map(function(field) {
// field.type = field.type in jtsmap ? jtsmap[field.type] : field.type;
return {
id: field,
description: '',
type: 'string'
}
});
cb(null, out);
throw new Error('Stop parsing');
}
},
{parallel: 1}
)
.on('error', function(err) {
parser.pause();
// do these for good measure ...
stream.pause();
stream.destroy();
// now rethrow the error
if (err.message != 'Stop parsing') {
throw err
}
})
;
}
exports.createReadStream = dpkgCreateReadStream;
// ========================================================
// Utilities
// Create a name from a URL (no extension)
// e.g. http://.../abc/xyz.fbc.csv?... => xyz.fbc
function _nameFromUrl(url_) {
var name = url.parse(url_).pathname.split('/').pop();
if (name.indexOf('.') != -1) {
var _parts = name.split('.');
_parts.pop();
name = _parts.join('.');
}
return name;
}
var stripTags = function(str){
if (str == null) return '';
return String(str).replace(/<\/?[^>]+>/g, '');
}