-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.js
110 lines (96 loc) · 2.57 KB
/
types.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
'use strict';
var fs = require('fs');
var streams = require('stream');
var ShonParser = require('./shon-parser');
var JshonParser = require('./jshon-parser');
var ArrayCollector = require('./array-collector');
var ValueCollector = require('./value-collector');
// TODO var DifferenceCollector = require('./difference-collector');
// TODO SetCollector
var types = {
defaults: {},
parsers: {
shon: ShonParser,
jshon: JshonParser,
},
converters: {
number: Number,
quantity: Number,
boolean: convertBoolean,
json: convertJson,
input: InputConverter,
atinput: AtInputConverter,
output: OutputConverter
},
validators: {
number: isNumber,
quantity: isPositive
},
collectors: {
array: ArrayCollector
}
};
function isPositive(number) {
return number === number && number >= 0;
}
function isNumber(number) {
return number === number;
}
function convertBoolean(string, iterator, delegate) {
if (string === 'true') {
return true;
} else if (string === 'false') {
return false;
} else {
delegate.error('Must be true or false');
delegate.cursor();
}
}
function convertJson(string, iterator, delegate) {
try {
return JSON.parse(string);
} catch (error) {
delegate.error(error.message);
delegate.cursor(-1);
return null;
}
}
function InputConverter(args) {
this.encoding = args.encoding || 'utf8';
}
InputConverter.prototype.convert = function convert(value) {
if (value === '-') {
process.stdin.resume();
return process.stdin;
} else {
return fs.createReadStream(value, this.encoding);
}
};
function OutputConverter(args) {
this.encoding = args.encoding || 'utf8';
}
OutputConverter.prototype.convert = function convert(value) {
if (value === '-') {
return process.stdout;
} else {
return fs.createWriteStream(value, this.encoding);
}
};
function AtInputConverter(args) {
this.encoding = args.encoding || 'utf8';
}
AtInputConverter.prototype.convert = function convert(value, iterator, delegate) {
if (value.lastIndexOf('@', 0) === 0) {
var path = value.slice(1);
return InputConverter.prototype.convert.call(this, path, iterator, delegate);
} else {
var stream = new streams.Readable();
stream.setEncoding(this.encoding);
stream._read = noop;
stream.push(value);
stream.push(null);
return stream;
}
};
function noop() {}
module.exports = types;