forked from WordPress/community-themes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
theme-utils.mjs
270 lines (226 loc) · 6.82 KB
/
theme-utils.mjs
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
import { spawn } from 'child_process';
import fs from 'fs';
import inquirer from 'inquirer';
import { RewritingStream } from 'parse5-html-rewriting-stream';
import { table } from 'table';
import progressbar from 'string-progressbar';
const isWin = process.platform === 'win32';
const commands = {
"escape-patterns": {
helpText: 'Escapes block patterns for pattern files that have changes (staged or unstaged).',
run: () => escapePatterns()
},
"help": {
helpText: 'Displays the main help message.',
run: (args) => showHelp(args?.[1])
},
};
(async function start() {
let args = process.argv.slice(2);
let command = args?.[0];
if (!commands[command]) {
return showHelp();
}
commands[command].run(args);
})();
function showHelp(command = '') {
if (!command || !commands.hasOwnProperty(command)) {
console.log(`
node theme-utils.mjs [command]
Available commands:
_(theme-utils.mjs help [command] for more details)_
\t${Object.keys(commands).join('\n\t')}
`);
return;
}
const { helpText, additionalArgs } = commands[command];
console.log(`
${command} ${additionalArgs ?? ''}
${helpText}
`);
}
/*
Execute a command locally.
*/
export async function executeCommand(command, logResponse) {
const timeout = 2*60*1000; // 2 min
return new Promise((resolove, reject) => {
let child;
let response = '';
let errResponse = '';
if (isWin) {
child = spawn('cmd.exe', ['/s', '/c', '"' + command + '"'], {
windowsVerbatimArguments: true,
stdio: [process.stdin, 'pipe', 'pipe'],
detached: true,
})
} else {
child = spawn(process.env.SHELL, ['-c', command], {
stdio: [process.stdin, 'pipe', 'pipe'],
detached: true,
});
}
var timer = setTimeout(() => {
try {
process.kill(-child.pid, 'SIGKILL');
} catch (e) {
console.log('Cannot kill process');
}
}, timeout);
child.stdout.on('data', (data) => {
response += data;
if (logResponse) {
console.log(data.toString());
}
});
child.stderr.on('data', (data) => {
errResponse += data;
if (logResponse) {
console.log(data.toString());
}
});
child.on('exit', (code) => {
clearTimeout(timer)
if (code !== 0) {
reject(errResponse.trim());
}
resolove(response.trim());
});
});
}
async function escapePatterns() {
// get staged files
const staged = (await executeCommand(`git diff --cached --name-only`)).split('\n');
// get unstaged, untracked files
const unstaged = (await executeCommand(`git ls-files -m -o --exclude-standard`)).split('\n');
// avoid duplicates and filter pattern files
const patterns = [...new Set([...staged, ...unstaged])].filter(file => file.match(/.*\/patterns\/.*.php/g));
// arrange patterns by theme
const themePatterns = patterns.reduce((acc, file) => {
const themeSlug = file.split('/').shift();
return {
...acc,
[themeSlug]: (acc[themeSlug] || []).concat(file)
};
}, {});
Object.entries(themePatterns).forEach(async ([themeSlug, patterns]) => {
console.log(getPatternTable(themeSlug, patterns));
const prompt = await inquirer.prompt([{
type: 'input',
message: 'Verify the theme slug',
name: "themeSlug",
default: themeSlug
}]);
if (!prompt.themeSlug) {
return;
}
patterns.forEach(file => {
const rewriter = getReWriter(prompt.themeSlug);
const tmpFile = `${file}-tmp`;
const readStream = fs.createReadStream( file, { encoding: 'UTF-8' } );
const writeStream = fs.createWriteStream( tmpFile, { encoding: 'UTF-8' } );
writeStream.on('finish', () => {
fs.renameSync(tmpFile, file);
});
readStream.pipe(rewriter).pipe(writeStream);
});
});
// Helper functions
function getReWriter(themeSlug) {
const rewriter = new RewritingStream();
rewriter.on('text', (_, raw) => {
rewriter.emitRaw(escapeText(raw, themeSlug));
});
rewriter.on('startTag', (startTag, rawHtml) => {
if (startTag.tagName === 'img') {
const attrs = startTag.attrs.filter(attr => ['src', 'alt'].includes(attr.name));
attrs.forEach(attr => {
if (attr.name === 'src') {
attr.value = escapeImagePath(attr.value);
} else if (attr.name === 'alt') {
attr.value = escapeText(attr.value, themeSlug, true);
}
});
}
rewriter.emitStartTag(startTag);
});
rewriter.on('comment', (comment, rawHtml) => {
if (comment.text.startsWith('?php')) {
rewriter.emitRaw(rawHtml);
return;
}
// escape the strings in block config (blocks that are represented as comments)
// ex: <!-- wp:search {label: "Search"} /-->
const block = escapeBlockAttrs(comment.text, themeSlug)
rewriter.emitComment({...comment, text: block})
});
return rewriter;
}
function escapeBlockAttrs(block, themeSlug) {
// Set isAttr to true if it is an attribute in the result HTML
// If set to true, it generates esc_attr_, otherwise it generates esc_html_
const allowedAttrs=[
{ name: 'label' },
{ name: 'placeholder', isAttr: true },
{ name: 'buttonText' },
{ name: 'content' }
];
const start = block.indexOf('{');
const end = block.lastIndexOf('}');
const configPrefix = block.slice(0, start);
const config = block.slice(start, end+1);
const configSuffix = block.slice(end+1);
try {
const configJson = JSON.parse(config);
allowedAttrs.forEach((attr) => {
if (!configJson[attr.name]) return;
configJson[attr.name] = escapeText(configJson[attr.name], themeSlug, attr.isAttr)
})
return configPrefix + JSON.stringify(configJson) + configSuffix;
} catch (error) {
// do nothing
return block
}
}
function escapeText(text, themeSlug, isAttr = false) {
const trimmedText = text && text.trim();
if (!themeSlug || !trimmedText || trimmedText.startsWith(`<?php`)) return text;
const escFunction = isAttr ? 'esc_attr__' : 'esc_html__';
const spaceChar = text.startsWith(' ') ? ' ' : ''
const resultText = text.replace('\'', '\\\'').trim();
return `${spaceChar}<?php echo ${escFunction}( '${resultText}', '${themeSlug}' ); ?>`;
}
function escapeImagePath(src) {
if (!src || src.trim().startsWith('<?php')) return src;
const assetsDir = 'assets';
const parts = src.split('/');
const resultSrc = parts.slice(parts.indexOf(assetsDir)).join('/');
return `<?php echo esc_url( get_template_directory_uri() ); ?>/${resultSrc}`;
}
function getPatternTable(themeSlug, patterns) {
const tableConfig = {
columnDefault: {
width: 40,
},
header: {
alignment: 'center',
content: `THEME: ${themeSlug}\n\n Following patterns may get updated with escaped strings and/or image paths`,
}
};
return table(patterns.map(p => [p]), tableConfig);
}
}
function startProgress(length) {
let current = 0;
function render() {
const [progress, percentage] = progressbar.filledBar(length, current);
console.log('\nProgress:', [progress, Math.round(percentage*100)/100], `${current}/${length}\n`);
}
render();
return {
increment() {
current++;
render();
}
};
}