forked from google/WebFundamentals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwfUpdatedOn.js
86 lines (75 loc) · 2.37 KB
/
wfUpdatedOn.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
/**
* @fileoverview Gulp Task for updating wf_updated_on.
*
* @author Matt Gaunt
*/
'use strict';
const gulp = require('gulp');
const chalk = require('chalk');
const fse = require('fs-extra');
const moment = require('moment');
const gutil = require('gulp-util');
const wfRegEx = require('./wfRegEx');
const wfHelper = require('./wfHelper');
const MSG_UPDATE = `Updated ${chalk.bold('wf_updated_on')} in`;
/**
* Gets the list of files that have been staged.
* @return {Promise<Array<String>>} Returns array of changed Files.
*/
async function getChangedFiles() {
const cmd = `git diff --name-only --cached`;
const results = await wfHelper.promisedExec(cmd, '.');
return results.split('\n');
}
gulp.task('update-updated_on', async () => {
if (process.env.TRAVIS) {
// Do nothing on Travis.
return;
}
// List of all files that have changed
const changedFiles = await getChangedFiles();
for (const changedFile of changedFiles) {
if (changedFile.indexOf('src/content') === -1) {
// File isn't a content file, skip it.
continue;
}
if (!changedFile.endsWith('.md')) {
// File isn't a Markdown file, skip it.
continue;
}
if (changedFile.indexOf('src/content/en/ilt') >= 0) {
// File is auto-generated, skip it
continue;
}
try {
await fse.access(changedFile);
} catch (err) {
// File removed
continue;
}
const fileContents = (await fse.readFile(changedFile)).toString();
if (wfRegEx.RE_AUTO_GENERATED.exec(fileContents)) {
// File is auto-generated, skip it.
continue;
}
const matched = wfRegEx.RE_UPDATED_ON.exec(fileContents);
if (!matched) {
// Updated on not in the file - nothing to do.
continue;
}
const originalUpdatedOn = matched[0];
const originalTimestamp = matched[1];
const momentNow = moment();
if (momentNow.isSameOrBefore(originalTimestamp)) {
// Updated date is today or in the future.
continue;
}
const newUpdatedOn = originalUpdatedOn
.replace(originalTimestamp, momentNow.format(`YYYY-MM-DD`));
const newContents = fileContents.replace(originalUpdatedOn, newUpdatedOn);
await fse.writeFile(changedFile, newContents);
// Add the file to the current commit.
await wfHelper.promisedExec(`git add ${changedFile}`);
gutil.log(' ', `${MSG_UPDATE} ${chalk.cyan(changedFile)}`);
}
});