Repository navigation
Expand file tree
/
Copy pathbuild.js
More file actions
233 lines (217 loc) · 8.21 KB
/
Copy pathbuild.js
File metadata and controls
233 lines (217 loc) · 8.21 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
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
const fs = require('fs').promises;
const path = require('path');
const { minify } = require('terser');
const sass = require('sass');
const postcss = require('postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
// Read package information dynamically from package.json
const packageJson = require('./package.json');
const version = packageJson.version;
const phpversion = packageJson.phpversion;
const modxversion = packageJson.modxversion;
const currentYear = new Date().getFullYear();
const startYear = parseInt(packageJson.startYear) || currentYear;
const yearRange = currentYear > startYear ? `${startYear}-${currentYear}` : `${startYear}`;
const dateStr = new Date().toISOString()
.split('T')[0];
const copyrightRegex = new RegExp(`Copyright ${startYear}(-\\d{4})? by`, 'g');
const copyrightReplace = `Copyright ${yearRange} by`;
const apiRegex = new RegExp(`© ${startYear}(-\\d{4})?`, 'g');
const apiReplace = `© ${yearRange}`;
const banner = `/*!\n * ${packageJson.fullname} - ${packageJson.description}\n * Version: ${packageJson.version}\n * Build date: ${dateStr}\n */\n`;
let versionParts = version.split('-');
let versionNumber = versionParts[0];
let versionRelease = versionParts[1] || 'pl';
let versionFull = versionNumber + '-' + versionRelease;
// Helper: Replace string/regex in a file
async function replaceInFile(filePath, replacements, message = 'file') {
try {
let content = await fs.readFile(filePath, 'utf8');
replacements.forEach(({ search, replace }) => {
content = content.replace(search, replace);
});
await fs.writeFile(filePath, content, 'utf8');
console.log(`✓ Updated ${message}: ${filePath}`);
} catch (e) {
console.warn(`⚠ Error updating ${filePath}`);
}
}
// Helper: Ensure directory structure exists
async function ensureDirExists(dirPath) {
await fs.mkdir(path.dirname(dirPath), { recursive: true });
}
// Helper: Copy a file
async function copyFile(src, dest) {
try {
const fullSource = path.resolve(__dirname, src);
const fullTarget = path.resolve(__dirname, dest);
const targetDir = path.dirname(fullTarget);
await ensureDirExists(targetDir);
await fs.copyFile(fullSource, fullTarget);
console.log(`✓ Copied: ${src} -> ${dest}`);
} catch (e) {
console.warn(`⚠ Error copying ${src} -> ${dest}`);
}
}
// Helper: Copy folders recursively with an optional filter function
async function copyFolderRecursive(src, dest, filterFn = (fileName) => true) {
await ensureDirExists(dest);
const entries = await fs.readdir(src, { withFileTypes: true });
for (let entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
await copyFolderRecursive(srcPath, destPath, filterFn);
} else if (filterFn(entry.name)) {
try {
await fs.copyFile(srcPath, destPath);
console.log(`✓ Copied: ${srcPath} -> ${destPath}`);
} catch (e) {
console.warn(`⚠ Error copying ${srcPath} -> ${destPath}`);
}
}
}
}
// Helper function to compile scripts
async function compileScripts(files, dest, filename) {
console.log('Compiling scripts...');
const fileContents = await Promise.all(
files.map(f => fs.readFile(f, 'utf8'))
);
const minified = await minify(fileContents.join('\n'), {
mangle: true,
compress: true,
format: {
comments: false,
},
});
const finalCode = banner + minified.code;
await ensureDirExists(dest);
filename = filename.replace(/(\.\w+)$/i, '.min$1');
await fs.writeFile(path.join(dest, filename), finalCode, 'utf8');
}
// Helper function to compile, autoprefix and minify Sass
async function compileSass(files, intermediate, dest, filename) {
console.log('Compiling Sass & processing CSS...');
let concatenatedCss = '';
for (const file of files) {
const sassResult = await sass.compile(file, { style: 'expanded' });
const postcssResult = await postcss([
autoprefixer()
])
.process(sassResult.css, { from: undefined });
concatenatedCss += postcssResult.css + '\n';
}
concatenatedCss = concatenatedCss.replace(/\/\*[\s\(\S\)]*?\*\/\n*/g, '');
await ensureDirExists(intermediate);
await fs.writeFile(path.join(intermediate, filename), concatenatedCss, 'utf8');
const postcssResult = await postcss([
autoprefixer(),
cssnano({ preset: ['default', { discardComments: { removeAll: true } }] })
])
.process(concatenatedCss, { from: undefined });
const finalCss = postcssResult.css + '\n' + banner;
await ensureDirExists(dest);
filename = filename.replace(/(\.\w+)$/i, '.min$1');
await fs.writeFile(path.join(dest, filename), finalCss, 'utf8');
}
async function taskBump() {
console.log(`Bump (with version ${versionFull} and daterange: ${yearRange})...`);
const copyrightFiles = [
'core/components/customrequest/model/customrequest/customrequest.class.php',
'core/components/customrequest/src/CustomRequest.php',
];
for (const file of copyrightFiles) {
await replaceInFile(file, [{
search: copyrightRegex,
replace: copyrightReplace
}], 'copyright in');
}
await replaceInFile('core/components/customrequest/src/CustomRequest.php', [{
search: /version = '\d+\.\d+\.\d+-?[0-9a-z]*'/ig,
replace: `version = '${version}'`
}], 'version in');
const homepanelFiles = [
'source/js/mgr/widgets/home.panel.js',
];
for (const file of homepanelFiles) {
await replaceInFile(file, [{
search: apiRegex,
replace: apiReplace
}], 'daterange in');
}
const docFiles = [
'zensical.toml',
];
for (const file of docFiles) {
await replaceInFile(file, [{
search: apiRegex,
replace: apiReplace
}], 'daterange in');
}
await replaceInFile('docs/index.md', [{
search: /[*-] MODX Revolution \d.\d.*/g,
replace: '* MODX Revolution ' + modxversion + '+'
}, {
search: /[*-] PHP (v)?\d.\d.*/g,
replace: '* PHP ' + phpversion + '+'
}], 'requirements in');
await replaceInFile('core/components/customrequest/composer.json', [{
search: /"php": "\d.\d.*?"/g,
replace: '"php": "' + phpversion + '"'
}, {
search: /"php": ">=\d.\d.*?"/g,
replace: '"php": ">=' + phpversion + '"'
}], 'requirements in');
const buildFiles = [
'_build/config.json',
'core/components/customrequest/composer.json',
];
for (const file of buildFiles) {
await replaceInFile(file, [{
search: /"version": "\d+\.\d+\.\d+-?[0-9a-z]*"/ig,
replace: `"version": "${version}"`
}], 'version in');
}
}
async function taskScripts() {
await compileScripts([
'source/js/mgr/customrequest.js',
'source/js/mgr/helper/combo.js',
'source/js/mgr/helper/util.js',
'source/js/mgr/widgets/home.panel.js',
'source/js/mgr/widgets/configs.grid.js',
'source/js/mgr/widgets/settings.panel.js',
'source/js/mgr/sections/home.js'
], 'assets/components/customrequest/js/mgr/', 'customrequest.js');
}
async function taskSass() {
await compileSass([
'source/sass/mgr/customrequest.scss'
], 'source/css/mgr/', 'assets/components/customrequest/css/mgr/', 'customrequest.css');
}
async function taskImages() {
console.log('Copying images...');
const isImage = function (fileName) {
return /\.(png|jpg|gif|svg)$/i.test(fileName);
};
await copyFolderRecursive('source/img', 'assets/components/customrequest/img', isImage);
}
const action = process.argv[2];
if (action === 'bump') {
taskBump();
} else if (action === 'scripts') {
taskScripts();
} else if (action === 'sass') {
taskSass();
} else if (action === 'images') {
taskImages();
} else {
// Default: Beides ausführen
taskBump()
.then(() => taskScripts())
.then(() => taskSass())
.then(() => taskImages());
}
console.log('Done!');