forked from mvanede/webpack-version-file-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (68 loc) · 1.87 KB
/
index.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
"use strict";
const fs = require('fs');
const path = require('path');
const _ = require('underscore');
const ejs = require('ejs');
const chalk = require('chalk');
function VersionFile(options) {
var self = this;
var defaultOptions = {
outputFile: 'version.txt',
template: 'version.ejs',
templateString: '',
extras: {}
};
//Set default config data
var optionsObject = options || {};
self.options = _.defaults(optionsObject, defaultOptions);
// Check for missing arguments
if (!this.options.packageFile) {
throw new Error(chalk.red('Expected path to packageFile'))
}
try {
self.options['package'] = require(self.options.packageFile);
} catch (err) {
throw new Error(chalk.red(err))
}
}
VersionFile.prototype.apply = function() {
var self = this;
self.options.currentTime = new Date();
/*
* If we are given a template string in the config, then use it directly.
* But if we get a file path, fetch the content then use it.
*/
if (self.options.templateString) {
self.writeFile(self.options.templateString);
} else {
fs.readFile(self.options.template, {
encoding: 'utf8'
}, function(error, content) {
if (error) {
throw error;
return;
}
self.writeFile(content);
});
}
};
/**
* Renders the template and writes the version file to the file system.
* @param templateContent
*/
VersionFile.prototype.writeFile = function(templateContent) {
var self = this;
var fileContent = ejs.render(templateContent, self.options);
self.ensureDirExists(path.dirname(self.options.outputFile));
fs.writeFileSync(self.options.outputFile, fileContent, {
flag: 'w'
});
}
VersionFile.prototype.ensureDirExists = function(dirpath) {
try {
fs.mkdirSync(dirpath, { recursive: true });
} catch (err) {
if (err.code !== 'EEXIST') throw err;
}
}
module.exports = VersionFile;