This repository has been archived by the owner on Aug 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bump-hash.js
79 lines (67 loc) · 1.72 KB
/
bump-hash.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
/**
* Calc index.js contents hash and bump it to header comment.
*/
const fs = require('fs');
const crypto = require('crypto');
const { EOL } = require('os');
const TARGET_FILE = 'src/index.js';
const EXCLUDE_LINES_REGEXP = /^\s*(\/\*|\/\/|\*)/i; // exclude js comments
main();
function main() {
const lines = readFile(TARGET_FILE);
const { hash, hashLineIndex } = findHashLine(lines) || createHashLine(lines);
const newHash = calcHash(lines);
if (newHash !== hash) {
lines[hashLineIndex] = buildHashLine(newHash);
saveFile(TARGET_FILE, lines);
console.log(`Hash updated: ${newHash}`);
} else {
console.log(`Hash not changed: ${newHash}`);
}
}
function findHashLine(lines) {
for (const [ index, line ] of lines.entries()) {
const hash = matchHashLine(line);
if (hash) {
return {
hash,
hashLineIndex: index,
};
}
}
}
/**
* If hash line ot found, insert it at first index.
*/
function createHashLine(lines) {
lines.unshift('');
return {
hash: '',
hashLineIndex: 0,
};
}
function calcHash(lines) {
const string = lines
.filter(Boolean)
.filter(line => !line.match(EXCLUDE_LINES_REGEXP))
.map(line => line.replace(/\s+/g, ' '))
.join('');
return crypto.createHash('md5')
.update(string)
.digest('hex');
}
function matchHashLine(line) {
const matches = line.match(/^\s*\/\/ build:.*?\[([a-z0-9]+)]/i);
return matches && matches[1];
}
function buildHashLine(hash) {
return `// build: ${new Date().toString()} [${hash}]`;
}
function readFile(file) {
const content = fs.readFileSync(file, 'utf8');
return content.split(EOL);
}
function saveFile(file, lines) {
const content = lines.join(EOL);
fs.writeFileSync(file, content);
}