-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
277 lines (252 loc) · 6.89 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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import path from 'path'
import { fileURLToPath } from 'url'
import { execSync, spawn } from 'child_process'
import fs from 'fs-extra' // https://github.com/jprichardson/node-fs-extra/
import { globby as glob } from 'globby' // https://github.com/sindresorhus/globby
import chalk from 'picocolors'
import { Eta } from 'eta'
import createCaseConverter from './case.js'
import { prompt } from './prompt.js'
const changeCase = createCaseConverter()
const __dirname = path.dirname(fileURLToPath(import.meta.url))
/**
* Create project from template
*/
export async function createProject(options = {}) {
const {
defaultProjectName = '',
cwd = process.cwd(),
project: projectConfig,
} = options
const questions = [
{
type: 'select',
name: 'type',
message: 'Select project type',
choices: [
{
name: 'Static HTML Page',
value: 'static',
},
{
name: 'WordPress plugin',
value: 'plugin',
},
{
name: 'WordPress theme',
value: 'theme',
},
{
name: 'WordPress site',
value: 'site',
},
],
},
{
type: 'input',
name: 'name',
required: true,
message:
'Project name ' +
chalk.gray('- Lowercase alphanumeric with optional dash "-"'),
// when: (data) => (data.name ? false : true),
default: (data) => data.name,
validate: (value) => {
return value && !value.startsWith('.') && !value.includes('..')
},
filter: (value) => changeCase.kebab(value),
},
{
type: 'confirm',
name: 'overwrite',
message: 'Remove existing project?',
when: async (data) => {
const exists = await fs.pathExists(path.join(cwd, data.name))
if (exists) {
console.log(`Project folder "${data.name}" already exists`)
}
return exists
},
default: false,
async after(data) {
if (data.overwrite === false) {
process.exit(1)
return
}
// Value already sanitized in validate() of name question
const projectPath = path.join(cwd, data.name)
console.log('Remove', projectPath)
await fs.rm(projectPath, {
recursive: true,
})
},
},
{
type: 'input',
name: 'title',
required: true,
message: 'Project title ' + chalk.gray('- Press enter for default'),
default: (data) => changeCase.title(data.name),
},
{
type: 'input',
name: 'description',
message: 'Project description ' + chalk.gray('- Can be empty'),
},
]
const project = {
name: 'untitled',
title: 'Untitled',
description: '',
...(projectConfig ||
(await prompt(questions, {
name: defaultProjectName,
}))),
}
const projectName = project.name
const projectPath = path.join(cwd, projectName)
// Create project folder and copy template
console.log(
`Create project "${projectName}" ` +
chalk.gray('- Press CTRL + C to quit at any time'),
)
await fs.mkdir(projectPath, {
recursive: true,
})
const templatePath = path.join(__dirname, project.type)
console.log('Copy template type', project.type)
const ignore = [
'build',
'bun.lockb',
'.gitkeep',
'node_modules',
'package-lock.json',
'vendor',
]
await fs.copy(templatePath, projectPath, {
filter: (filePath) => {
/**
* Check file path relative to template folder, in case it's inside
* node_modules.
*/
const folders = path.relative(templatePath, filePath).split('/')
for (const folder of folders) {
if (ignore.includes(folder)) return false
}
return true
},
})
/**
* Replace placeholders <% %> using Eta template engine
*/
const templateContext = {
project,
...changeCase,
}
// https://eta.js.org/docs/api
const eta = new Eta({
useWith: true,
autoEscape: false,
autoTrim: false,
})
const etaOptions = {
async: true,
}
/**
* File extensions to process
*/
const extensions = [
'css',
'html',
'js',
'json',
'jsx',
'md',
'php',
'scss',
'ts',
'tsx',
'txt',
]
for (const file of await glob(`**/*.{${extensions.join(',')}}`, {
ignore: ['node_modules'],
gitignore: true,
cwd: projectPath,
})) {
const filePath = path.join(projectPath, file)
let content = await fs.readFile(filePath, 'utf8')
if (content.includes('<%')) {
console.log('Process', file)
// https://eta.js.org/docs/syntax/async
try {
const fn = await eta.compile(content, {
...etaOptions,
// Support include() relative to tempate file
async include(target) {
const dirPath = path.dirname(filePath)
// Resolve relative file path
const targetFilePath = path.resolve(dirPath, target)
try {
return await fs.readFile(targetFilePath, 'utf8')
} catch (e) {
console.log(
'Error building template',
path.relative(projectPath, filePath),
)
console.error(e.message)
}
return ''
},
})
content = await eta.renderAsync(fn, templateContext)
} catch (e) {
console.error(e)
continue
}
}
/**
* Alternative syntax for placeholders - Added for convenience of
* developing project templates directly, because the <% %> format
* can be a syntax error in source files.
*/
content = content
.replaceAll('project-title', project.title)
.replaceAll('project-description', project.description)
.replaceAll('project-name', project.name)
.replaceAll('project_name', changeCase.snake(project.name))
.replaceAll('PROJECT_NAME', changeCase.constant(project.name))
await fs.writeFile(filePath, content)
}
const run = (command, options = { silent: false }) =>
new Promise((resolve, reject) => {
try {
execSync(command, {
stdio: options.silent ? null : 'inherit',
cwd: projectPath,
})
resolve()
} catch (e) {
reject(e)
}
})
const pluginPath = path.join(projectPath, 'tangible-plugin.php')
if (await fs.exists(pluginPath)) {
const entryFile = `${project.name}.php`
console.log('Rename plugin entry file to', entryFile)
await fs.rename(pluginPath, path.join(projectPath, entryFile))
console.log('Create folder at vendor/tangible')
await fs.mkdir(path.join(projectPath, 'vendor/tangible'), {
recursive: true,
})
}
console.log('Install dependencies')
try {
await run(`bun install`, { silent: true })
} catch (e) {
await run(`npm install --audit=false --loglevel=error`, { silent: true })
}
console.log(`
Start by running:
cd ${projectName}
npm run start`)
}