forked from oleynikd/gulp-wp-file-header
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
124 lines (113 loc) · 2.5 KB
/
index.js
File metadata and controls
124 lines (113 loc) · 2.5 KB
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
/* globals require, module */
/* jslint node: true */
'use strict';
var _ = require('lodash'),
fs = require('fs'),
p = require('path'),
pad = require('pad');
var fields = {
'themename': 'Theme Name',
'homepage': 'Theme URI',
'description': 'Description',
'version': 'Version',
'author': 'Author',
'authoruri': 'Author URI',
'keywords': 'Tags',
'textdomain': 'Text Domain',
'template': 'Template',
'license': 'License',
'licenseuri': 'License URI',
};
module.exports = function (path) {
return new WPFileHeader(path);
};
/**
* WPFileHeader constructor.
* @param {string} path package.json filepath.
* @constructor
*/
var WPFileHeader = function (path) {
if (typeof path === 'undefined') {
path = './package.json';
}
this.manifest_path = p.normalize(path);
};
/**
* Modifes style.css.
* This will also create one if not exists, but will not create directories.
*
* @param {string=} style style.css filepath. Default './style.css'.
* @param {Function=} cb Callback function to be called.
* @return {void}
*/
WPFileHeader.prototype.patch = function (style, callback) {
var commentsPattern = /(?:\/\*(?:[\s\S]*?)\*\/\s?)|(?:([\s;])+\/\/(?:.*)$)/;
if (typeof style === 'undefined' || typeof style === 'function') {
callback = style;
style = './style.css';
}
style = p.normalize(style);
fs.readFile(this.manifest_path, 'utf8', function (err, manifest) {
if (err) {
if (callback) {
callback(err);
}
else {
throw err;
}
}
else {
manifest = JSON.parse(manifest);
fs.readFile(style, 'utf8', function (err, data) {
if (err && err.code !== 'ENOENT') {
if (callback) {
callback(err);
}
else {
throw err;
}
}
else {
if (typeof data === 'undefined') {
data = '';
}
if (commentsPattern.test(data)) {
data = data.replace(commentsPattern, '');
}
data = createContent(manifest) + data;
fs.writeFile(style, data, function (err) {
if (err) {
if (callback) {
callback(err);
}
else {
throw err;
}
}
else {
if (callback) {
callback(null);
}
}
});
}
});
}
});
};
/**
* Creates style.css header content.
*
* @param {Object} manifest
* @return {string}
*/
var createContent = function (manifest) {
var out = "/*\n";
_.forEach(fields, function (n, key) {
if (typeof manifest[key] != 'undefined') {
out += pad(n + ':', 20) + manifest[key] + "\n";
}
});
out += "*/\n";
return out;
};