-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·181 lines (149 loc) · 5.08 KB
/
index.js
File metadata and controls
executable file
·181 lines (149 loc) · 5.08 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
#!/usr/bin/env node
import fs from 'node:fs/promises'
import path from 'node:path'
import { program } from 'commander'
import Mustache from 'mustache'
import { fileURLToPath } from 'node:url'
import {
createDirectory,
createTemplate,
exitWithScriptError,
findNearestTemplatronDir,
getAnswers,
getAvailableTemplates,
getConfig,
getConfirm,
initializeTemplatron,
makeFilesTree,
parseAndGenerateFile,
removeTemplate
} from './functions.js'
Mustache.tags = ['<%', '%>']
const CWD = process.cwd()
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const VERSION = await fs.readFile(path.join(__dirname, 'package.json'), 'utf8').then(JSON.parse).then(pkg => pkg.version)
// CLI configuration
program
.version(VERSION, '-v, --version')
.usage('<template> <name>\n templatron [options]')
.option('-l, --list', 'list available templates for current working directory')
.option('-c, --create <template_name>', 'creates a new template boilerplate in the current working directory')
.option('-r, --remove <template_name>', 'removes a template from the current working directory')
.argument('[template]', 'Name of the template to use (see --list option)')
.argument('[name]', 'Name of the file to create with the template')
.allowExcessArguments(false)
.allowUnknownOption(false)
program.parse()
const OPTS = program.opts()
const ARGS = program.args;
const TEMPLATES_PATH = await findNearestTemplatronDir(CWD);
if (!TEMPLATES_PATH) {
await initializeTemplatron()
}
// Listing available templates if asked
if (OPTS.list) {
const filesList = await fs.readdir(TEMPLATES_PATH, { withFileTypes: true })
const templatesList = filesList.filter(file => file.isDirectory()).map(file => file.name)
console.log(getAvailableTemplates(templatesList, TEMPLATES_PATH), '\n')
process.exit(0)
}
// Create a new template
if (OPTS.create) {
await createTemplate(OPTS.create);
process.exit(0);
}
// Remove a template
if (OPTS.remove) {
await removeTemplate(OPTS.remove);
process.exit(0);
}
if (!OPTS.list && (!ARGS[0] || !ARGS[1])) {
exitWithScriptError('Arguments [template] and [name] are required\n\nFor more info:\n\n templatron --help')
}
// Get arguments template name and element's name
const template = program.args[0]
const name = program.args[1]
// -------------
// Script starts
// -------------
try {
// Get list of available templates in /_templates/ folder
const templatesList = await fs.readdir(TEMPLATES_PATH)
if (!templatesList.includes(template)) {
exitWithScriptError(`Unknown template: ${template}\n${getAvailableTemplates(templatesList, TEMPLATES_PATH)}`)
}
// Loads config file for the selected template
const templatePath = path.join(TEMPLATES_PATH, template)
const config = await getConfig(templatePath)
console.log(`\n 🤖 Using template \x1b[33m${templatePath}\x1b[0m …\n`)
// Asks for user input
const answers = await getAnswers(config.filesToGenerate, name)
// Prepares data for mustache template
const templateData = {
name,
...Object.fromEntries(
Object.entries(answers)
.filter(([key]) => key !== 'targetDirectory')
.map(([key, value]) => [
key,
{ yes: value === 'Yes', no: value === 'No' },
])
),
}
// Computes final target directory that will contain the generated files
const targetDirectory = path.join(
CWD,
answers.targetDirectory,
answers.createNewDirectory ? name : ''
)
// Computes a list of files to generate, depending on what the user selected at previous step
const confirmedFilesToGenerate = config.filesToGenerate
.filter(
(file, index) =>
index === 0 ||
(answers[file.varName] === 'Yes' && !!file.templateFileName)
)
.map((file) => ({
templateFileName: path.join(templatePath, file.templateFileName),
renderedFileName: path.join(
targetDirectory,
Mustache.render(file.templateFileName.replace('.mustache', ''), {
name,
})
),
data: templateData,
}))
// Presents a tree of files that are going to be generated …
console.log('\nThis will generate all these files:\n')
console.log(
makeFilesTree({
baseRoot: path.join(CWD, answers.targetDirectory),
newDirectoryName: answers.createNewDirectory ? name : null,
fileNames: confirmedFilesToGenerate.map(({ renderedFileName }) =>
path.basename(renderedFileName)
),
}),
'\n'
)
// … and asks for confirmation before creating files
const confirm = await getConfirm()
if (!confirm.ok) {
exitWithScriptError('Cancelled')
}
// Creates directory for the new template files if user selected it
if (answers.createNewDirectory) {
await createDirectory(targetDirectory)
}
// Generate files
await Promise.all(confirmedFilesToGenerate.map(parseAndGenerateFile))
// Present report of generated files
console.log('\n✅ Successfully generated files:\n')
console.log(
confirmedFilesToGenerate
.map(({ renderedFileName }) => ` - ${renderedFileName}`)
.join('\n'),
'\n'
)
} catch (err) {
exitWithScriptError(err.message)
}