This repository has been archived by the owner on Dec 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgulpfile.js
541 lines (450 loc) · 16.8 KB
/
gulpfile.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// Gulp file to merge sections into a single document and convert to HTML/PDF
// 06/19/2017 - James Ritchie Carroll
//
// Prerequisties needed for execution:
// Install Node Package Manager: https://nodejs.org/en/download/
// Install wkhtmltopdf: https://wkhtmltopdf.org/downloads.html
// Add "C:\Program Files\wkhtmltopdf\bin" to your path
// From command line after NPM install:
// npm install gulp
// npm install --global gulp-cli
// npm install gulp-util
// npm install gulp-clean
// npm install gulp-concat
// npm install showdown
// npm install --save showdown-emoji
// npm install gulp-html2pdf
// npm install gulp-exec
// npm install gulp-notify
//
// To execute, just type "gulp" from command window
const gulp = require("gulp");
const clean = require('gulp-clean');
const concat = require("gulp-concat");
const showdown = require("showdown");
const emojis = require("showdown-emoji");
const gutil = require("gulp-util");
const through = require("through2");
const html2pdf = require('gulp-html2pdf');
const exec = require("gulp-exec");
const notify = require("gulp-notify");
// Define non-relative URL paths for any relative paths
const rawPath = "https://raw.githubusercontent.com/sttp/Specification/master/";
const viewPath = "https://github.com/sttp/Specification/blob/master/";
// Define section file that contains version number
const versionFile = "Sections/TitlePage.md";
// Define primary footer title for PDF - will be suffixed with updated version
const footerTitle = "STTP Draft Specification - v";
// Define the section files in the order that they should appear
// in the target single combined markdown document:
const sections = [
"Sections/TitlePage.md",
"Sections/Preface.md",
"Sections/README.md" /* TOC */,
"Sections/Introduction.md",
"Sections/BusinessCase.md",
"Sections/Definitions.md",
"Sections/Overview.md",
"Sections/EstablishingConnections.md",
"Sections/CommandsAndResponses.md",
"Sections/Commands.md",
"Sections/Responses.md",
"Sections/DataPointStructure.md",
"Sections/DataPointEncodingTypes.md",
"Sections/DataPointCharacteristics.md",
"Sections/Metadata.md",
"Sections/Compression.md",
"Sections/Security.md",
/* Balance of sections */
"Sections/References.md",
"Sections/Contributors.md",
"Sections/History.md",
"Sections/FunctionalRequirements.md",
"Sections/APIReference.md",
"Sections/IEEE_C37.118Mapping.md",
"Sections/OtherProtocols.md",
"Sections/TSSCAlgorithm.md",
"Sections/Templates.md"
];
// Define map of markdown file links to intra-page section headers, note
// that GitHub makes all header links lowercase and spaces become dashes:
const sectionLinks = [
/* Section link mappings */
[ "(TitlePage.md)", "(#user-content-title-page)" ],
[ "(Preface.md)", "(#disclaimer)" ],
[ "(README.md)", "(#table-of-contents)" ],
[ "(Introduction.md)", "(#introduction)" ],
[ "(BusinessCase.md)", "(#business-case)" ],
[ "(Definitions.md)", "(#definitions-and-nomenclature)" ],
[ "(Overview.md)", "(#protocol-overview)" ],
[ "(DesignPhilosophies.md)", "(#design-philosophies)" ],
[ "(EstablishingConnections.md)", "(#establishing-connections)" ],
[ "(CommandsAndResponses.md)", "(#commands-and-responses)" ],
[ "(Commands.md)", "(#commands)" ],
[ "(Responses.md)", "(#responses)" ],
[ "(DataPointStructure.md)", "(#data-point-structure)" ],
[ "(DataPointEncodingTypes.md)", "(#data-point-encoding-types)" ],
[ "(DataPointCharacteristics.md)", "(#data-point-characteristics)" ],
[ "(Metadata.md)", "(#metadata)" ],
[ "(Compression.md)", "(#compression)" ],
[ "(Security.md)", "(#security)" ],
/* Balance of sections */
[ "(References.md)", "(#references-and-notes)" ],
[ "(Contributors.md)", "(#contributors)" ],
[ "(History.md)", "(#major-version-history)" ],
[ "(FunctionalRequirements.md)", "(#appendix-a---initial-team-requirements)" ],
[ "(APIReference.md)", "(#appendix-b---sttp-api-reference)" ],
[ "(IEEE_C37.118Mapping.md)", "(#appendix-c---ieee-c37118-mapping)" ],
[ "(OtherProtocols.md)", "(#appendix-d---other-protocol-evaluations)" ],
[ "(TSSCAlgorithm.md)", "(#appendix-e---STTP-Templates)" ],
[ "(Templates.md)", "(#appendix-F---tssc-algorithm)" ],
[ "(ToDoList.md)", "(#specification-development-to-do-list)" ],
/* Special replacements */
[ "(References.md#", "(#" ],
[ "(Commands.md#", "(#" ],
[ "(DataPointStructure.md#", "(#" ],
[ "(QuestionsSummary.md)", "(" + viewPath + "Sections/QuestionsSummary.md)" ],
[ "(../LICENSE)", "(" + viewPath + "LICENSE)" ]
];
// Any git functionality expects existing "git" environmental variable
const isWin = /^win/.test(process.platform);
const git = isWin ? "\"%git%\"" : "#git#";
const versionPattern = /^\*\*Version:\*\*\s+\d+\.\d+\.\d+.*$/gm;
const execReportOptions = {
err: true, // default = true, false means don't write err
stderr: true, // default = true, false means don't write stderr
stdout: false // default = true, false means don't write stdout
};
var currentVersion = null;
var updatedVersion = null;
var forcePush = false;
var referenceMappings = {};
var sectionMap = null;
showdown.setFlavor("github");
function replaceAll(sourceText, findText, replaceWith, ignoreCase) {
return sourceText.replace(new RegExp(
findText.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"),
(ignoreCase ? "gi" : "g")), (typeof replaceWith == "string") ?
replaceWith.replace(/\$/g, "$$$$") : replaceWith);
}
function getLongDate(date) {
const monthNames = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
if (!date)
date = new Date();
const day = date.getDate();
const monthIndex = date.getMonth();
const year = date.getFullYear();
return monthNames[monthIndex] + " " + day + ", " + year;
}
function checkDocumentVersion() {
return through.obj(function(file, encoding, cb) {
const versionLineMatch = file.contents.toString().match(versionPattern);
if (versionLineMatch) {
const versionNumber = versionLineMatch[0].match(/\d+\.\d+\.\d+/)[0];
console.log("Current version number = " + versionNumber);
currentVersion = versionNumber;
this.push(file);
cb(null, file);
}
else {
cb(new Error("Failed to find version pattern: \"**Version:** #.#.#\""));
}
});
}
function incrementDocumentVersion() {
return through.obj(function(file, encoding, cb) {
const lastDotIndex = currentVersion.lastIndexOf(".");
const revision = parseInt(currentVersion.substring(lastDotIndex + 1)) + 1;
updatedVersion = currentVersion.substr(0, lastDotIndex) + "." + revision;
const updatedMarkdown = file.contents.toString().replace(versionPattern,
"**Version:** " + updatedVersion + " - " + getLongDate());
file.contents = new Buffer(updatedMarkdown);
this.push(file);
cb(null, file);
});
}
function pushDocumentUpdates() {
return through.obj(function(file, encoding, cb) {
const stdout = file.exec ? file.exec.stdout : null;
const stderr = file.exec ? file.exec.stderr : null;
const pushUpdates =
forcePush ||
(stdout && stdout.length > 0) ||
(stderr && stderr.length > 0);
if (pushUpdates) {
console.log("Committing new compiled documents to local repo...");
const message = "Updated compiled documents - version " + updatedVersion;
gulp.src("README.md")
.pipe(exec(git + " add ."))
.pipe(exec.reporter(execReportOptions))
.pipe(exec(git + " commit -m \"" + message + "\""))
.pipe(exec.reporter(execReportOptions))
.pipe(notify("Tagging local repo with new version number..."))
.pipe(exec(git + " tag -f v" + updatedVersion))
.pipe(exec.reporter(execReportOptions))
.pipe(notify("Pushing updates to remote repo..."))
.pipe(exec(git + " push"))
.pipe(exec.reporter(execReportOptions));
}
this.push(file);
cb(null, file);
});
}
function updateSectionLinks() {
return through.obj(function(file, encoding, cb) {
var sourceMarkdown = file.contents.toString();
for (let i = 0; i < sectionLinks.length; i++) {
findText = sectionLinks[i][0];
replaceWith = sectionLinks[i][1];
sourceMarkdown = replaceAll(sourceMarkdown, findText, replaceWith);
}
file.contents = new Buffer(sourceMarkdown);
this.push(file);
cb(null, file);
});
}
function markdown2html() {
return through.obj(function(file, encoding, cb) {
const converter = new showdown.Converter({ extensions: [emojis] });
const sourceMarkdown = file.contents.toString();
var destinationHtml = converter.makeHtml(sourceMarkdown);
// Convert local image links to non-relative permanent paths
destinationHtml = replaceAll(
destinationHtml,
"<img src=\"Images/",
"<img src=\"" + rawPath + "Output/Images/"
);
// Remove "#user-content-" prefixes for page level bookmarks
destinationHtml = replaceAll(destinationHtml, "#user-content-", "#");
file.contents = new Buffer(destinationHtml);
file.path = gutil.replaceExtension(file.path, ".html");
this.push(file);
cb(null, file);
});
}
function loadReferenceMapping() {
return through.obj(function(file, encoding, cb) {
const mappings = file.contents.toString().split(/\r\n|\n/);
for (let i = 0; i < mappings.length; i++) {
if (mappings[i].startsWith("//"))
continue;
const mapping = mappings[i].split(",");
if (mapping.length == 2)
referenceMappings[mapping[0]] = mapping[1];
}
for (let key in referenceMappings) {
if (referenceMappings.hasOwnProperty(key)) {
console.log("Mapping \"" + key + "\" to \"" +
referenceMappings[key] + "\"");
}
}
this.push(file);
cb(null, file);
});
}
function updateReferences() {
return through.obj(function(file, encoding, cb) {
if (file.contents) {
const referenceContent = "](References.md#user-content-ref"
var sourceMarkdown = file.contents.toString();
console.log("Processing \"" + file.path + "\"...");
for (let key in referenceMappings) {
if (referenceMappings.hasOwnProperty(key)) {
const value = referenceMappings[key];
sourceMarkdown = replaceAll(sourceMarkdown,
"[" + key + referenceContent + key + ")",
"[" + value + referenceContent + value + ")"
);
}
}
file.contents = new Buffer(sourceMarkdown);
}
this.push(file);
cb(null, file);
});
}
function truncateSectionMap() {
return through.obj(function(file, encoding, cb) {
const lines = file.contents.toString().split(/\r\n|\n/);
sectionMap = lines[0] + "\r\n";
for (let i = 1; i < lines.length; i++) {
sectionMap += lines[i] + "\r\n";
if (lines[i].startsWith("|:-"))
break;
}
this.push(file);
cb(null, file);
});
}
function appendToSectionMap() {
return through.obj(function(file, encoding, cb) {
const lines = file.contents.toString().split(/\r\n|\n/);
var headingLevel = 0;
// Map sections at heading levels 1 to 3
for (let i = 0; i < lines.length; i++) {
if (lines[i].startsWith("####"))
headingLevel = 0;
else if (lines[i].startsWith("###"))
headingLevel = 3;
else if (lines[i].startsWith("##"))
headingLevel = 2;
else if (lines[i].startsWith("#"))
headingLevel = 1;
else
headingLevel = 0;
if (headingLevel > 0) {
const filename = file.relative;
const sectionTitle = lines[i].substr(headingLevel + 1).trim();
const sectionAnchor = sectionTitle
.toLowerCase()
.replace(/[^\w\- ]+/g, " ")
.replace(/\s+/g, "-")
.replace(/\-+$/, "");
sectionMap += "| [" + sectionTitle + " (" + headingLevel + ")](" +
filename + "#" + sectionAnchor + ") | [" + filename + "](" +
filename + ") |\r\n";
}
}
if (sectionMap == null)
sectionMap = "";
file.contents = new Buffer(sectionMap);
file.path = "Sections/SectionMap.md";
this.push(file);
cb(null, file);
});
}
gulp.task("check-version", [], function() {
console.log("Checking document version...");
return gulp.src(versionFile)
.pipe(checkDocumentVersion());
});
gulp.task("clear-output", [ "check-version" ], function() {
console.log("Clearing output folder...");
return gulp.src([
"Output/Images/",
"Output/Include/",
"Output/*"
], { read: false })
.pipe(clean());
});
gulp.task("increment-version", [ "clear-output" ], function() {
console.log("Incrementing document version number...")
return gulp.src(versionFile)
.pipe(incrementDocumentVersion())
.pipe(gulp.dest("Sections/"));
});
gulp.task("copy-to-output", [ "increment-version" ], function() {
console.log("Copying target files to output folder...");
gulp.src("Sections/Images/*.png")
.pipe(gulp.dest("Output/Images/"));
return gulp.src("Sections/Include/*")
.pipe(gulp.dest("Output/Include/"));
});
gulp.task("merge-markdown", [ "copy-to-output" ], function() {
console.log("Combining all markdown into a single file...");
return gulp.src(sections)
.pipe(concat("README.md"))
.pipe(updateSectionLinks())
.pipe(gulp.dest("Output/"));
});
gulp.task("convert-to-html", [ "merge-markdown" ], function() {
console.log("Converting markdown to HTML...");
return gulp.src("Output/README.md")
.pipe(markdown2html())
.pipe(gulp.dest("Output/"));
});
gulp.task("complete-html", [ "convert-to-html" ], function() {
console.log("Adding header and footer to HTML...");
return gulp.src([
"Output/Include/_header.html",
"Output/README.html",
"Output/Include/_footer.html"
])
.pipe(concat("sttp-specification.html"))
.pipe(gulp.dest("Output/"));
});
gulp.task("convert-to-pdf", [ "complete-html" ], function() {
console.log("Converting HTML to PDF...");
const options = {
marginLeft: 20,
marginRight: 20,
marginTop: 20,
marginBottom: 20,
footerSpacing: 5,
footerFontName: "Segoe UI",
footerFontSize: 8,
footerLeft: getLongDate(),
footerCenter: footerTitle + updatedVersion,
footerRight: "[page] / [toPage]",
footerLine: false
};
return gulp.src("Output/sttp-specification.html")
.pipe(html2pdf(options))
.pipe(gulp.dest("Output/"));
});
gulp.task("update-section-map", [ "convert-to-pdf" ], function() {
console.log("Updating section map...");
gulp.src("Sections/SectionMap.md")
.pipe(truncateSectionMap());
return gulp.src(sections)
.pipe(appendToSectionMap())
.pipe(gulp.dest("Sections/"));
});
gulp.task("clean-up", [ "update-section-map" ], function() {
console.log("Removing temporary files...");
return gulp.src([
"Output/Include/",
"Output/README.html"
], { read: false })
.pipe(clean());
});
// This task will recompile output documents and increment the version
gulp.task("default", [ "clean-up" ]);
// This task will recompile output documents, increment the version and
// push the updated files
gulp.task("push-changes", [ "clean-up" ], function() {
forcePush = true;
return gulp.src("README.md")
.pipe(pushDocumentUpdates());
});
// This task will recompile output documents, increment the version and
// push the updated files if there have been any remote check-ins - this
// is useful for an automated nightly-build operation that should only
// run when there have been changes pushed to the remote repository.
// When scheduling this task to run, the "update-repo" task should be
// called before calling the "push-changes-if-remote-updated" task - this
// assumes that the automated build repostory will not be the source of
// any content updates besides incrementing the version number and
// compiling the new documents.
gulp.task("push-changes-if-remote-updated", [ "clean-up" ], function() {
console.log("Checking for remote updates...");
const options = { continueOnError: true };
return gulp.src("README.md")
.pipe(exec(git + " log v" + currentVersion + "..", options))
.pipe(pushDocumentUpdates());
});
// This task will reset the local repository to the remote - be careful
gulp.task("update-repo", function() {
console.log("Updating local repo...");
return gulp.src("README.md")
.pipe(exec(git + " gc"))
.pipe(exec.reporter(execReportOptions))
.pipe(exec(git + " fetch"))
.pipe(exec.reporter(execReportOptions))
.pipe(exec(git + " reset --hard origin/master"))
.pipe(exec.reporter(execReportOptions))
.pipe(exec(git + " clean -f -d -x"))
.pipe(exec.reporter(execReportOptions));
});
// This task will renumber the references in section markdown files
gulp.task("renumber-references", function() {
console.log("Renumbering references...");
gulp.src("refmap.txt")
.pipe(loadReferenceMapping());
return gulp.src("Sections/*.md")
.pipe(updateReferences())
.pipe(gulp.dest("Sections/"));
});