-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdemo-build.mjs
More file actions
206 lines (173 loc) · 5.75 KB
/
demo-build.mjs
File metadata and controls
206 lines (173 loc) · 5.75 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
import fs from 'fs'
import path from 'path'
import { execSync, spawnSync } from 'child_process'
import readline from 'readline'
import chalk from 'chalk'
import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'
// === CONFIG ===
const config = {
basePath: '/blockchainlab/demo',
outputDir: 'upload/demo',
afsDeployPath: '/afs/inf.ed.ac.uk/group/project/blockchainlab/html/demo'
}
const FILES_TO_MODIFY = ['src/utils/paths.ts', 'vite.config.ts']
let originalContents = {}
let didRestore = false
function ensureDirectoryExists(directory) {
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true })
}
}
function cleanDirectory(directory) {
if (fs.existsSync(directory)) {
fs.rmSync(directory, { recursive: true, force: true })
}
ensureDirectoryExists(directory)
}
function backupFiles() {
FILES_TO_MODIFY.forEach((file) => {
originalContents[file] = fs.readFileSync(file, 'utf8')
})
}
function restoreFiles() {
FILES_TO_MODIFY.forEach((file) => {
if (originalContents[file]) {
fs.writeFileSync(file, originalContents[file])
}
})
}
function updateConfig(basePath, outputDir) {
updateFile('src/utils/paths.ts', [
[/basePath\s*=\s*["'].*?["']/g, `basePath = "${basePath}"`],
[/distDir:\s*["'].*?["']/g, `distDir: "${outputDir}"`]
])
updateFile('vite.config.ts', [
[/const base\s*=\s*['"`][^'"`]*['"`]/, `const base = "${basePath}"`]
])
}
function updateFile(filePath, replacements) {
let fileContent = fs.readFileSync(filePath, 'utf8')
replacements.forEach(([regex, replacement]) => {
fileContent = fileContent.replace(regex, replacement)
})
fs.writeFileSync(filePath, fileContent)
console.log(chalk.green(`Updated ${filePath} successfully.`))
}
function buildProject(outputDir) {
console.log(chalk.cyan(`Building project...`))
ensureDirectoryExists('upload')
cleanDirectory(outputDir)
execSync('npm run build', { stdio: 'inherit' })
console.log(chalk.green(`Build completed.`))
}
function copyHtaccessFile(outputDir) {
console.log(chalk.cyan(`Copying .htaccess file...`))
try {
fs.copyFileSync('htaccess/.htaccess.demo', `${outputDir}/.htaccess`)
console.log(chalk.green(`.htaccess file copied successfully.`))
} catch (error) {
console.error(chalk.red('Failed to copy .htaccess file:', error))
process.exit(1)
}
}
function deployToAFS(localDir, afsDir, skipOutputFolder = false) {
console.log(chalk.green('\nDeploying to AFS...'))
try {
const command = skipOutputFolder
? `rsync -av --exclude 'output/' ${localDir}/ ${afsDir}/`
: `sh -c 'cp -R ${localDir}/* ${afsDir}/'`
execSync(command, { stdio: 'inherit' })
console.log(chalk.green('Deployment to AFS successful.'))
} catch (error) {
console.error(chalk.red('Deployment failed:', error))
process.exit(1)
}
}
async function prompt(question, defaultValue = '') {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
return new Promise((resolve) => {
rl.question(question, (answer) => {
rl.close()
resolve(answer.trim() === '' ? defaultValue : answer.trim())
})
})
}
async function loginToAFS() {
const username = await prompt(
'Enter your AFS username (default: zjan@INF.ED.AC.UK): ',
'zjan@INF.ED.AC.UK'
)
console.log(chalk.green(`Running kinit for ${username}...`))
if (spawnSync('kinit', [username], { stdio: 'inherit' }).status !== 0) {
console.error('kinit failed.')
process.exit(1)
}
console.log(chalk.green('Running aklog...'))
if (spawnSync('aklog', { stdio: 'inherit' }).status !== 0) {
console.error('aklog failed.')
process.exit(1)
}
console.log(chalk.green('AFS login successful.\n'))
}
function safeRestoreAndExit(code = 1) {
if (!didRestore) {
console.log(chalk.green(`Restoring configuration files before exiting...`))
restoreFiles()
didRestore = true
}
process.exit(code)
}
// === Main Execution ===
;(async () => {
const argv = yargs(hideBin(process.argv))
.option('deploy', { type: 'boolean', default: false })
.option('no-output', { type: 'boolean', default: false })
.parseSync()
const shouldDeploy = argv.deploy
const skipOutputFolder = argv['no-output']
//const shouldDeploy = process.argv.includes("--deploy");
//const skipOutputFolder = process.argv.includes("--no-output");
// Always restore on process exit (e.g., Ctrl+C)
process.on('SIGINT', () => {
console.error(chalk.yellow('\nInterrupted (SIGINT). Cleaning up...'))
safeRestoreAndExit(1)
})
process.on('uncaughtException', (err) => {
console.error('\nUncaught Exception:', err)
safeRestoreAndExit(1)
})
process.on('unhandledRejection', (reason, promise) => {
console.error('\nUnhandled Rejection:', reason)
safeRestoreAndExit(1)
})
try {
if (shouldDeploy) {
await loginToAFS()
}
console.log(chalk.blueBright('Backing up configuration files...'))
backupFiles()
console.log(chalk.blueBright('Updating configuration for build...'))
updateConfig(config.basePath, config.outputDir)
console.log(chalk.blueBright('Running build...'))
buildProject(config.outputDir)
console.log(chalk.blueBright('Copying .htaccess file...'))
copyHtaccessFile(config.outputDir)
console.log(chalk.blueBright('Restoring original configuration...'))
restoreFiles()
didRestore = true
if (shouldDeploy) {
console.log(chalk.blueBright('Deploying...'))
deployToAFS(config.outputDir, config.afsDeployPath, skipOutputFolder)
}
console.log(chalk.green('\nDemo build script completed successfully.'))
} catch (error) {
console.error(chalk.red('\nAn error occurred during the build process.'))
console.error(error.message || error)
safeRestoreAndExit(1)
//process.exit(1);
}
})()