-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.js
More file actions
187 lines (154 loc) · 5.28 KB
/
Copy pathbuild.js
File metadata and controls
187 lines (154 loc) · 5.28 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
const fs = require('fs').promises;
const path = require('path');
const { execSync } = require('child_process');
const nunjucks = require('nunjucks');
const fastGlob = require('fast-glob');
const grayMatter = require('gray-matter');
const SRC = 'src';
const DEST = 'docs';
// Pretty URls with trailing-slash URL for templates
function getUrl(relPath) {
let clean = relPath
.replace(/^pages\//, '')
.replace(/\.njk$/, '')
.replace(/\/index$/, ''); // treat index.njk as the parent folder
if (clean === 'index' || clean === '') {
return '/';
}
return '/' + clean + '/';
}
// Load global data (metadata.json)
let globalData = {
site: { title: 'Untitled Site', description: '', baseUrl: '/' },
version: '0.0.0'
};
async function loadGlobalData() {
try {
const metadataPath = path.join(SRC, 'data/metadata.json');
const raw = await fs.readFile(metadataPath, 'utf-8');
const data = JSON.parse(raw);
globalData = {
...globalData,
...data,
site: { ...globalData.site, ...data?.site }
};
// Override baseUrl from environment variable (for GitHub Pages builds)
const envBaseUrl = process.env.BASE_URL;
if (envBaseUrl) {
globalData.site.baseUrl = envBaseUrl.endsWith('/') ? envBaseUrl : envBaseUrl + '/';
console.log(`✅ Using BASE_URL override: ${globalData.site.baseUrl}`);
} else {
console.log(`Using default baseUrl: ${globalData.site.baseUrl}`);
}
console.log(`Global data loaded: ${globalData.site.title} v${globalData.version}`);
} catch (err) {
console.warn('Warning: Could not load metadata.json — using defaults');
console.warn(err.message);
}
}
// Configure Nunjucks
nunjucks.configure(SRC, {
autoescape: true,
noCache: true,
trimBlocks: true,
lstripBlocks: true
});
// Copy static assets
async function copyStaticAssets() {
const staticPatterns = [
'css/other/**/*.{css}',
'js/**/*.{js,mjs}',
'img/**/*.{png,jpg,jpeg,gif,svg,webp,avif,ico}',
'fonts/**/*.{woff,woff2,ttf,otf,eot}',
'*.{ico,png,xml,txt,json,webmanifest,robots.txt}',
];
console.log('Copying static assets...');
for (const pattern of staticPatterns) {
const files = await fastGlob(path.join(SRC, pattern), { onlyFiles: true });
for (const srcFile of files) {
const relPath = path.relative(SRC, srcFile);
const destFile = path.join(DEST, relPath);
await fs.mkdir(path.dirname(destFile), { recursive: true });
await fs.copyFile(srcFile, destFile);
console.log(` copied: ${relPath}`);
}
}
}
// Main build function
async function build() {
console.time('Build completed');
await loadGlobalData();
// 1. Clean destination
await fs.rm(DEST, { recursive: true, force: true });
await fs.mkdir(DEST, { recursive: true });
// 2. Copy static assets
await copyStaticAssets();
// 3. Build & minify CSS
try {
execSync(
'npx postcss src/css/codebase-6.css -o docs/css/codebase-6.min.css --verbose',
{ stdio: 'inherit' }
);
console.log('CSS built → docs/css/codebase-6.min.css');
} catch (err) {
console.error('CSS build failed:');
console.error(err.message);
process.exit(1);
}
// 4. Render Nunjucks pages with dynamic layout + pretty URLs
const pageFiles = await fastGlob(path.join(SRC, 'pages/**/*.njk'), { onlyFiles: true });
if (pageFiles.length === 0) {
console.warn('No .njk pages found in src/pages/');
}
for (const file of pageFiles) {
const relPath = path.relative(SRC, file);
let html;
let outRel;
try {
const fileContent = await fs.readFile(file, 'utf-8');
const { data: frontMatter, content: pageContent } = grayMatter(fileContent);
const context = {
...globalData,
baseUrl: globalData.site.baseUrl,
page: {
title: frontMatter.title || globalData.site?.title || 'Untitled Page',
description: frontMatter.description || globalData.site?.description || '',
url: getUrl(relPath),
isHome: relPath === 'pages/index.njk' || relPath.endsWith('/index.njk'),
...frontMatter,
},
year: new Date().getFullYear(),
content: ''
};
const renderedPageContent = nunjucks.renderString(pageContent, context);
const layoutPath = frontMatter.layout || '_includes/layout.njk';
context.content = renderedPageContent;
html = nunjucks.render(layoutPath, context);
// Pretty URLs with trailing slash → folder/index.html
let cleanPath = relPath
.replace(/^pages\//, '')
.replace(/\.njk$/, '');
if (cleanPath === 'index' || cleanPath === '') {
outRel = 'index.html';
} else {
outRel = path.join(cleanPath, 'index.html');
}
console.log(` rendered: ${relPath} → ${outRel} (URL: ${getUrl(relPath)}) (layout: ${frontMatter.layout || 'default'})`);
} catch (err) {
console.error(`Render error in ${relPath}:`);
console.error(err.message);
continue;
}
const outFile = path.join(DEST, outRel);
await fs.mkdir(path.dirname(outFile), { recursive: true });
await fs.writeFile(outFile, html);
}
console.timeEnd('Build completed');
console.log('Build finished successfully.');
}
// Run build
build().catch(err => {
console.error('Build script error:');
console.error(err);
process.exit(1);
});