-
Notifications
You must be signed in to change notification settings - Fork 460
/
Copy pathcreate-cohort-project.mjs
executable file
·334 lines (268 loc) · 9.84 KB
/
create-cohort-project.mjs
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#! /usr/bin/env node
import childProcess from 'node:child_process';
import { existsSync, statSync } from 'node:fs';
import { cp, rename, unlink, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import readline from 'node:readline';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import minimist from 'minimist';
import { mkdirp } from 'mkdirp';
import { Octokit } from '@octokit/rest';
import {
transformLearningObjectives,
loadYaml,
} from '@laboratoria/curriculum-parser/lib/project.js';
import { parseProject } from '@laboratoria/sdk-js';
import {
getFilesWithLocales,
defaultLocale,
supportedLocales,
getLearningObjectivesHeadings,
getLearningObjectivesHierarchy,
createLearningObjectivesMarkdown
} from './script-utils.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const uiUrl = 'https://curriculum.laboratoria.la';
const exec = promisify(childProcess.exec);
const prompt = text => new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question(text, (answer) => {
rl.close();
resolve(answer);
});
});
const ensureSrc = (src) => {
if (!src) {
throw new Error('Please specify a source dir containing a project');
}
if (!existsSync(src) || !statSync(src).isDirectory()) {
throw new Error('Source dir is not a directory!');
}
};
const ensureRepoDir = async (repoDir, opts) => {
if (existsSync(repoDir)) {
if (!statSync(repoDir).isDirectory()) {
throw new Error('Destination exists and its a file??');
}
const confirmOverwrite = await prompt(
`Dir ${repoDir} already exists.. use it anyway? [y/N]: `,
);
if (!['y', 'Y'].includes(confirmOverwrite)) {
throw new Error('Aborting');
}
} else {
if (opts.noop) {
console.log(`Would have created directory ${repoDir}`);
} else {
await mkdirp(repoDir);
}
}
};
const copy = async (src, repoDir, opts) => {
console.log(`You are about to copy all files from ${src} to ${repoDir}`);
const confirmCopy = await prompt('Are you sure you want to continue? [Y/n]: ');
if (['n', 'N'].includes(confirmCopy)) {
throw new Error('Aborting');
}
if (opts.noop) {
console.log(`Would have copied files from ${src} to ${repoDir}`);
return;
}
console.log('Copying files...');
await cp(src, repoDir, { recursive: true });
// rename / replace default files with localized content
if (opts.locale && opts.locale !== defaultLocale) {
const files = getFilesWithLocales(repoDir, [opts.locale]);
await Promise.all(files.map(filepath => rename(`${filepath}`, `${filepath.replace(`.${opts.locale}`, '')}`)));
}
const files = getFilesWithLocales(repoDir, supportedLocales.filter((loc) => loc !== (opts.locale || defaultLocale)));
// we dont need necesarily need to filter supportedLocales to remove the opts.locale since those files
// will already be renamed by the step above and should no longer exist...
return await Promise.all(files.map(filepath => unlink(`${filepath}`)));
};
const addBootcampInfo = async (repoDir) => {
const projectPkgJsonPath = path.resolve(`${repoDir}/package.json`);
if (!existsSync(projectPkgJsonPath)) {
return;
}
const pkg = Object.assign(JSON.parse(await readFile(projectPkgJsonPath)), {
bootcamp: {
createdAt: (new Date()).toISOString(),
version: process.env.npm_package_version,
commit: (await exec('git rev-parse HEAD')).stdout.trim(),
},
});
await writeFile(projectPkgJsonPath, JSON.stringify(pkg, null, 2));
};
const addExplainDevConfigFile = async ({ project, cohort, track, repoDir }) => {
if (track === 'web-dev') {
const explainDevConfigFilePath = path.resolve(`${repoDir}/explaindev.json`);
const explainDevConfig = {
project,
cohort,
}
await writeFile(explainDevConfigFilePath, JSON.stringify(explainDevConfig, null, 2));
}
};
const addLocalizedLearningObjectives = async (repoDir, opts, meta) => {
const { learningObjectives, variants } = await transformLearningObjectives(repoDir, {
lo: path.join(__dirname, '../learning-objectives'),
}, meta);
if (variants?.length && !opts.variant) {
throw new Error('Project has variants, please specify one with --variant');
}
const parsedProject = parseProject({ ...meta, learningObjectives, variants });
const combinedLearningObjectives = parsedProject.getCombinedLearningObjectives(opts.variant);
// Note: combinedLearningObjectives returns list of objects, each with a
// property `id` containing a string like: js/modules, s/modules/esm, etc
if (!combinedLearningObjectives?.length) {
return;
}
const lang = opts.locale ? opts.locale.split('-')[0] : defaultLocale;
const intl = await loadYaml(
path.join(__dirname, '../learning-objectives', 'intl', `${lang}.yml`),
);
const categoryTree = getLearningObjectivesHierarchy(combinedLearningObjectives);
const sectionTree = getLearningObjectivesHeadings(categoryTree, intl);
const text = createLearningObjectivesMarkdown(
combinedLearningObjectives,
sectionTree,
intl,
lang,
);
const readmePath = path.join(repoDir, 'README.md');
const contents = (await readFile(readmePath, 'utf8')).split('\n');
const startIndex = contents.findIndex(
line => /^## \d+\. Objetivos de aprendiza(je|gem)/i.test(line),
);
if (startIndex < 0) {
throw new Error('README.md is missing Learning Objectives heading');
}
const endIndex = (
startIndex
+ contents.slice(startIndex + 1).findIndex(line => /^## /.test(line))
);
const updatedContent = contents.slice(0, startIndex + 1)
.concat(
'',
intl.description,
text.trim(),
endIndex > startIndex ? contents.slice(endIndex) : '',
)
.join('\n')
.replace(/\.\.\/\.\.\/topics\//g, `${uiUrl}/${lang}/topics/`);
await writeFile(readmePath, updatedContent);
await unlink(path.join(repoDir, 'project.yml'));
};
const initRepo = async (repoDir, opts) => {
if (opts.noop) {
console.log('Would have initialized local repo, added files and commited');
return;
}
console.log('Initializing repo...');
await exec('git init', { cwd: repoDir });
await exec('git add .', { cwd: repoDir });
await exec('git commit -m "chore(init): Adds project files from curriculum"', { cwd: repoDir });
await exec('git branch -M main', { cwd: repoDir });
};
const createRemote = async (name, opts) => {
if (!process.env.GITHUB_TOKEN) {
throw new Error('GITHUB_TOKEN env var is not set!');
}
const org = (await prompt('GitHub org [Laboratoria]: ')) || 'Laboratoria';
if (opts.noop) {
console.log(`Would have tried to create repo on ${org}/${name}`);
return { status: 201 };
}
const octokit = new Octokit({ auth: process.env.GITHUB_TOKEN });
return octokit.repos.createInOrg({ org, name });
};
const pushChanges = async (repoDir, repo, useHttps, opts) => {
if (opts.noop) {
console.log(`Would have pushed changes to ${repo.full_name}`);
return;
}
const repoUri = (
useHttps
? `https://github.com/${repo.full_name}.git`
: `[email protected]:${repo.full_name}.git`
);
await exec(`git remote add upstream "${repoUri}"`, { cwd: repoDir });
await exec('git push -u upstream main', { cwd: repoDir });
};
const main = async (args, opts) => {
const [src, dest, prefix] = args;
ensureSrc(src);
const slug = path.basename(src).slice(3);
const repoName = `${prefix ? `${prefix}-` : ''}${slug}${opts.variant ? `-${opts.variant}` : ''}`;
const repoDir = dest ? `${dest}/${repoName}` : repoName;
await ensureRepoDir(repoDir, opts);
await copy(src, repoDir, opts);
await addBootcampInfo(repoDir);
const meta = await loadYaml(path.join(src, 'project.yml'));
await addExplainDevConfigFile({
project: slug,
cohort: prefix,
track: meta.track,
repoDir,
});
await addLocalizedLearningObjectives(repoDir, opts, meta);
await initRepo(repoDir, opts);
const confirmRemote = await prompt(
'Would you like to create a repository on GitHub and push changes? [Y/n]: ',
);
if (['n', 'N'].includes(confirmRemote)) {
console.log('Done');
return;
}
const createRemoteResponse = await createRemote(repoName, opts);
if (createRemoteResponse.status > 201) {
throw new Error(`Error creating remote repo`);
}
const remoteType = await prompt('Do you use ssh to clone with GitHub? [Y/n]: ');
const useHttps = ['n', 'N'].includes(remoteType);
console.log(`Ok, will clone repo with ${useHttps ? 'https then' : 'ssh'}.`);
await pushChanges(repoDir, createRemoteResponse.data, useHttps, opts);
console.log(`
Para continuar accede al directorio del proyecto del cohort:
cd ${repoDir}
O visita el repo directamente en GitHub:
${createRemoteResponse.data.html_url}
🚀🚀🚀
`);
};
const trimSlashes = (args) => {
return args.map(arg => (
arg[arg.length - 1] === '/'
? arg.slice(0, -1)
: arg
));
}
const printUsage = () => {
console.log(`create-cohort-project es un script para crear un nuevo proyecto del
bootcamp, para un cohort en particular.
Este es un mensaje de ayuda para que puedas usarlo.
Uso:
npm run create-cohort-project <RUTA_PROYECTO_ORIGEN> <RUTA_DESTINO> <PREFIJO_COHORT>
Ejemplo:
# crea el proyecto Markdown Links en la ruta actual para DEV999
npm run create-cohort-project projects/04-md-links ./ DEV999
# crea proyecto Fleet Management API en su variante de Java
npm run create-cohort-project projects/05-fleet-management-api / XXX999 -- --variant java
Acá puedes encontrar la documentación completa:
https://github.com/Laboratoria/curriculum/tree/main/scripts#create-cohort-project
`);
};
const { _: args, ...opts } = minimist(process.argv.slice(2));
if (args.length === 0 || opts.h || opts.help) {
printUsage();
process.exit(0);
}
main(trimSlashes(args), opts).catch((err) => {
console.error(err);
process.exit(1);
});