forked from SortableJS/polymer-sortablejs
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbuild.js
182 lines (164 loc) · 6.02 KB
/
build.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
const DISABLED_PROPERTIES = [
'draggable',
'setData',
'supportPointer'
];
const fsCallbacks = require('fs'),
path = require('path'),
https = require('https'),
promisify = require('util').promisify;
const fs = {
stat: promisify(fsCallbacks.stat),
readFile: promisify(fsCallbacks.readFile),
writeFile: promisify(fsCallbacks.writeFile),
exists: fsCallbacks.existsSync
};
// From https://stackoverflow.com/a/17676794/6166832
function donwload(url, dest) {
return new Promise((resolve, reject) => {
const file = fsCallbacks.createWriteStream(dest),
request = http.get(url, response => {
response.pipe(file);
file.on('finish', () => file.close(reslove));
});
});
}
// Helper for folder lookup
function generatePath(depth, ending) {
const generatedDepth = new Array(depth).fill('..');
return path.join(__dirname, ...generatedDepth, ending);
}
let found = false;
// Look in bower_components
for (let depth = 0; depth <= 2; depth++) {
if (fs.exists(generatePath(depth, 'bower_components/Sortable/Sortable.js'))) {
found = true;
console.log('Building from version in bower_components');
loadFromFile(generatePath(depth, 'bower_components/Sortable/Sortable.js'));
break;
}
}
if (!found) {
// Look in node_modules
for (let depth = 0; depth <= 2; depth++) {
if (fs.exists(generatePath(depth, 'node_modules/Sortable/Sortable.js'))) {
found = true;
console.log('Building from version in node_modules');
loadFromFile(generatePath(depth, 'node_modules/Sortable/Sortable.js'));
break;
}
}
}
if (!found) {
downloadFromGit();
}
async function loadFromFile(filePath) {
const file = await fs.readFile(filePath, 'utf8');
proceed(file);
}
async function downloadFromGit() {
const gitUsername = process.argv.includes('-u')
? process.argv[process.argv.indexOf('-u') + 1] : 'RubaXa';
const gitBranch = process.argv.includes('-b')
? process.argv[process.argv.indexOf('-b') + 1] : 'master';
https.get(`https://raw.githubusercontent.com/${gitUsername}/Sortable/${gitBranch}/Sortable.js`, resp => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
proceed(data);
});
}).on("error", err => {
console.trace(err);
throw new Error('Couldn\'t get Sortable.js');
});
console.log(`Building from Gtihub ${gitUsername}/Sortable#${gitBranch}`);
}
async function proceed(string) {
// Get options from source code of Sortblejs
const optionsString = /var\s+defaults\s*=\s*{\s*(([^:]+:[^,}]+)+\s*)}/m.exec(string)[1],
optionsStringSplit = optionsString.split(''),
optionsArray = [];
// Read them into an array [ key, value, key, value... ]
let current = '',
depthLevel = 0,
depthExpectColon = false,
depthStringOpen = false;
for (let i in optionsStringSplit) {
const character = optionsStringSplit[i];
if (character === '{'
|| (character === '\'' && !depthStringOpen) || (character === '"' && !depthStringOpen)
|| character === '?'
|| character === '(') {
depthLevel++;
if (character === '?') depthExpectColon = true;
if (character === '\'' || character === '"') depthStringOpen = true;
if (depthLevel > 0) current += character;
} else if (character === '}'
|| (character === '\'' && depthStringOpen) || (character === '"' && depthStringOpen)
|| (depthExpectColon && character === ':')
|| character === ')') {
depthLevel--;
if (character === ':') depthExpectColon = false;
if (character === '\'' || character === '"') depthStringOpen = false;
if (depthLevel >= 0) current += character;
} else if ((character === ','
|| character === ':')
&& depthLevel === 0) {
optionsArray.push(current);
current = '';
} else if (depthLevel > 0 || /[^\s:,]/.test(character)) {
current += character;
}
if (depthLevel < 0) {
optionsArray.push(current);
break;
}
}
// Throw if read options aren't even
if (optionsArray.length % 2) {
console.log('Options that were read:', optionsArray);
throw new Error('Something went wrong when reading options');
}
// Process the array to attach types
const computedOptions = {};
let key, value, type;
optionsArray.forEach((item, index) => {
index % 2 ? value = item : key = item;
if (value && key) {
if (!DISABLED_PROPERTIES.includes(key)) {
if (value === 'false' || value === 'true') type = 'Boolean'
else if (Number(value) !== NaN) type = 'Number'
else if (/$\s*\{/.test(value)) type = 'Object'
else if (/$\s*\[/.test(value)) type = 'Array'
else type = 'String'
computedOptions[key] = { value, type };
}
key = value = type = null;
}
});
// Get template file
const template = await fs.readFile(path.join(__dirname, 'polymer-sortablejs-template.html'), 'utf8');
let generatedTemplate = template;
// Generate properties
generatedTemplate = generatedTemplate.replace(/^(\s*)\/\*properties\*\//m, (_, spacing) => {
let output = '';
for (key in computedOptions) {
const type = computedOptions[key].type,
value = computedOptions[key].value;
output += `${spacing}${key}: { type: ${type}, value: function() { return ${value} }, observer: '${key}Changed' },\n`
}
return output.slice(0, -2);
});
// Generate observers
generatedTemplate = generatedTemplate.replace(/^(\s*)\/\*propertyobservers\*\//m, (_, spacing) => {
let output = '';
for (key in computedOptions) {
if (!new RegExp(key + 'Changed').test(template))
output += `${spacing}${key}Changed: function(value) { this.sortable && this.sortable.option("${key}", value); },\n`
}
return output.slice(0, -2);
});
await fs.writeFile(path.join(__dirname, 'polymer-sortablejs.html'), generatedTemplate, 'utf8');
}