@learnpack/learnpack 5.0.27 → 5.0.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -11
- package/lib/commands/breakToken.d.ts +10 -0
- package/lib/commands/breakToken.js +23 -0
- package/lib/commands/init.js +78 -44
- package/lib/commands/publish.js +29 -2
- package/lib/commands/start.js +9 -12
- package/lib/managers/config/index.js +77 -77
- package/lib/managers/server/routes.js +1 -5
- package/lib/managers/session.js +8 -0
- package/lib/models/session.d.ts +1 -0
- package/lib/utils/api.d.ts +11 -1
- package/lib/utils/api.js +49 -11
- package/lib/utils/creatorUtilities.d.ts +7 -2
- package/lib/utils/creatorUtilities.js +88 -6
- package/lib/utils/rigoActions.d.ts +6 -0
- package/lib/utils/rigoActions.js +16 -0
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/src/commands/breakToken.ts +36 -0
- package/src/commands/init.ts +113 -55
- package/src/commands/publish.ts +34 -2
- package/src/commands/start.ts +10 -14
- package/src/managers/config/index.ts +715 -715
- package/src/managers/server/routes.ts +1 -3
- package/src/managers/session.ts +11 -0
- package/src/models/session.ts +1 -0
- package/src/utils/api.ts +60 -12
- package/src/utils/creatorUtilities.ts +101 -7
- package/src/utils/rigoActions.ts +30 -0
@@ -1,715 +1,715 @@
|
|
1
|
-
import * as path from "path"
|
2
|
-
import * as fs from "fs"
|
3
|
-
import * as shell from "shelljs"
|
4
|
-
import { exec } from "child_process"
|
5
|
-
import { promisify } from "util"
|
6
|
-
|
7
|
-
import Console from "../../utils/console"
|
8
|
-
import watch from "../../utils/watcher"
|
9
|
-
import {
|
10
|
-
ValidationError,
|
11
|
-
NotFoundError,
|
12
|
-
InternalError,
|
13
|
-
} from "../../utils/errors"
|
14
|
-
|
15
|
-
import defaults from "./defaults"
|
16
|
-
import { exercise } from "./exercise"
|
17
|
-
|
18
|
-
import { rmSync } from "../file"
|
19
|
-
import {
|
20
|
-
IConfigObj,
|
21
|
-
TConfigObjAttributes,
|
22
|
-
TMode,
|
23
|
-
TAgent,
|
24
|
-
} from "../../models/config"
|
25
|
-
import {
|
26
|
-
IConfigManagerAttributes,
|
27
|
-
IConfigManager,
|
28
|
-
} from "../../models/config-manager"
|
29
|
-
import { IFile } from "../../models/file"
|
30
|
-
|
31
|
-
/* exercise folder name standard */
|
32
|
-
const execAsync = promisify(exec)
|
33
|
-
|
34
|
-
// eslint-disable-next-line
|
35
|
-
const fetch = require("node-fetch")
|
36
|
-
// eslint-disable-next-line
|
37
|
-
const chalk = require("chalk")
|
38
|
-
|
39
|
-
/* exercise folder name standard */
|
40
|
-
|
41
|
-
/**
|
42
|
-
* Retrieves the configuration path for the learnpack package.
|
43
|
-
*
|
44
|
-
* @returns An object containing the configuration file path and the base directory.
|
45
|
-
* @throws NotFoundError if the learn.json file is not found in the current folder.
|
46
|
-
*/
|
47
|
-
const getConfigPath = () => {
|
48
|
-
const possibleFileNames = ["learn.json", ".learn/learn.json"]
|
49
|
-
const config = possibleFileNames.find(file => fs.existsSync(file)) || null
|
50
|
-
if (config && fs.existsSync(".breathecode"))
|
51
|
-
return { config, base: ".breathecode" }
|
52
|
-
if (config === null)
|
53
|
-
throw NotFoundError(
|
54
|
-
"learn.json file not found on current folder, is this a learnpack package?"
|
55
|
-
)
|
56
|
-
return { config, base: ".learn" }
|
57
|
-
}
|
58
|
-
|
59
|
-
const getExercisesPath = (base: string) => {
|
60
|
-
const possibleFileNames = ["./exercises", base + "/exercises", "./"]
|
61
|
-
return possibleFileNames.find(file => fs.existsSync(file)) || null
|
62
|
-
}
|
63
|
-
|
64
|
-
const getGitpodAddress = () => {
|
65
|
-
if (shell.exec("gp -h", { silent: true }).code === 0) {
|
66
|
-
return shell
|
67
|
-
.exec("gp url", { silent: true })
|
68
|
-
.stdout.replace(/(\r\n|\n|\r)/gm, "")
|
69
|
-
}
|
70
|
-
|
71
|
-
Console.debug("Gitpod command line tool not found")
|
72
|
-
return "http://localhost"
|
73
|
-
}
|
74
|
-
|
75
|
-
const getCodespacesNamespace = () => {
|
76
|
-
// Example: https://orange-rotary-phone-wxpg49q5gcg4rp-3000.app.github.dev
|
77
|
-
|
78
|
-
const codespace_name = shell
|
79
|
-
.exec("echo $CODESPACE_NAME", { silent: true })
|
80
|
-
.stdout.replace(/(\r\n|\n|\r)/gm, "")
|
81
|
-
|
82
|
-
if (
|
83
|
-
!codespace_name ||
|
84
|
-
codespace_name === "" ||
|
85
|
-
codespace_name === undefined ||
|
86
|
-
codespace_name === "$CODESPACE_NAME"
|
87
|
-
) {
|
88
|
-
return null
|
89
|
-
}
|
90
|
-
|
91
|
-
return codespace_name
|
92
|
-
}
|
93
|
-
|
94
|
-
export default async ({
|
95
|
-
grading,
|
96
|
-
mode,
|
97
|
-
disableGrading,
|
98
|
-
version,
|
99
|
-
}: IConfigManagerAttributes): Promise<IConfigManager> => {
|
100
|
-
const confPath = getConfigPath()
|
101
|
-
Console.debug("This is the config path: ", confPath)
|
102
|
-
|
103
|
-
let configObj: IConfigObj = {}
|
104
|
-
|
105
|
-
if (confPath) {
|
106
|
-
const learnJsonContent = fs.readFileSync(confPath.config)
|
107
|
-
let hiddenBcContent = {}
|
108
|
-
|
109
|
-
if (fs.existsSync(confPath.base + "/config.json")) {
|
110
|
-
hiddenBcContent = fs.readFileSync(confPath.base + "/config.json")
|
111
|
-
hiddenBcContent = JSON.parse(hiddenBcContent as string)
|
112
|
-
if (!hiddenBcContent)
|
113
|
-
throw new Error(
|
114
|
-
`Invalid ${confPath.base}/config.json syntax: Unable to parse.`
|
115
|
-
)
|
116
|
-
}
|
117
|
-
|
118
|
-
const jsonConfig = JSON.parse(`${learnJsonContent}`)
|
119
|
-
|
120
|
-
if (!jsonConfig)
|
121
|
-
throw new Error(`Invalid ${confPath.config} syntax: Unable to parse.`)
|
122
|
-
|
123
|
-
let session: number
|
124
|
-
|
125
|
-
// add using id to the installation
|
126
|
-
if (!jsonConfig.session) {
|
127
|
-
session = Math.floor(Math.random() * 10_000_000_000_000_000_000)
|
128
|
-
} else {
|
129
|
-
session = jsonConfig.session
|
130
|
-
delete jsonConfig.session
|
131
|
-
}
|
132
|
-
|
133
|
-
configObj = deepMerge(hiddenBcContent, {
|
134
|
-
config: jsonConfig,
|
135
|
-
session: session,
|
136
|
-
})
|
137
|
-
} else {
|
138
|
-
throw ValidationError(
|
139
|
-
"No learn.json file has been found, make sure you are in the correct directory. To start a new LearnPack package run: $ learnpack init my-course-name"
|
140
|
-
)
|
141
|
-
}
|
142
|
-
|
143
|
-
configObj = deepMerge(defaults || {}, configObj, {
|
144
|
-
config: {
|
145
|
-
grading: grading || configObj.config?.grading,
|
146
|
-
configPath: confPath.config,
|
147
|
-
},
|
148
|
-
})
|
149
|
-
if (!configObj.config)
|
150
|
-
throw InternalError("Config object not found")
|
151
|
-
|
152
|
-
configObj.config.outputPath = confPath.base + "/dist"
|
153
|
-
|
154
|
-
Console.debug("This is your configuration object: ", {
|
155
|
-
...configObj,
|
156
|
-
exercises: configObj.exercises ?
|
157
|
-
configObj.exercises.map(e => e.slug) :
|
158
|
-
[],
|
159
|
-
})
|
160
|
-
|
161
|
-
// auto detect agent (if possible)
|
162
|
-
const codespaces_workspace = getCodespacesNamespace()
|
163
|
-
Console.debug("This is the codespace namespace: ", codespaces_workspace)
|
164
|
-
|
165
|
-
if (!configObj.config.editor) {
|
166
|
-
configObj.config.editor = {}
|
167
|
-
}
|
168
|
-
|
169
|
-
Console.debug(
|
170
|
-
"This is the agent, and this should be null an the beginning: ",
|
171
|
-
configObj.config?.editor?.agent
|
172
|
-
)
|
173
|
-
|
174
|
-
if (configObj.config?.editor?.agent) {
|
175
|
-
if (configObj.config.suggestions) {
|
176
|
-
configObj.config.suggestions.agent = configObj.config.editor.agent
|
177
|
-
} else {
|
178
|
-
configObj.config.suggestions = { agent: configObj.config.editor.agent }
|
179
|
-
}
|
180
|
-
}
|
181
|
-
|
182
|
-
if (shell.which("gp") && configObj && configObj.config) {
|
183
|
-
Console.debug("Gitpod detected")
|
184
|
-
configObj.address = getGitpodAddress()
|
185
|
-
configObj.config.publicUrl = `https://${
|
186
|
-
configObj.config.port
|
187
|
-
}-${configObj.address?.slice(8)}`
|
188
|
-
configObj.config.editor.agent = "vscode"
|
189
|
-
} else if (configObj.config && Boolean(codespaces_workspace)) {
|
190
|
-
Console.debug("Codespaces detected: ", codespaces_workspace)
|
191
|
-
configObj.address = `https://${codespaces_workspace}.github.dev`
|
192
|
-
configObj.config.publicUrl = `https://${codespaces_workspace}-${configObj.config.port}.app.github.dev`
|
193
|
-
configObj.config.editor.agent = "vscode"
|
194
|
-
} else {
|
195
|
-
Console.debug("Neither Gitpod nor Codespaces detected, using localhost.")
|
196
|
-
configObj.address = `http://localhost:${configObj.config.port}`
|
197
|
-
configObj.config.publicUrl = `http://localhost:${configObj.config.port}`
|
198
|
-
configObj.config.editor.agent =
|
199
|
-
process.env.TERM_PROGRAM === "vscode" ? "vscode" : "os"
|
200
|
-
}
|
201
|
-
|
202
|
-
if (configObj.config.editor.agent === "vscode" && isCodeCommandAvailable()) {
|
203
|
-
const extensionName = "learn-pack.learnpack-vscode"
|
204
|
-
|
205
|
-
if (!isExtensionInstalled(extensionName)) {
|
206
|
-
Console.info(
|
207
|
-
"The LearnPack extension is not installed, trying to install it automatically."
|
208
|
-
)
|
209
|
-
|
210
|
-
if (!installExtension(extensionName)) {
|
211
|
-
configObj.config.warnings = {
|
212
|
-
extension: EXTENSION_INSTALLATION_STEPS,
|
213
|
-
}
|
214
|
-
Console.warning(
|
215
|
-
"The LearnPack extension is not installed and this tutorial is meant to be run inside VSCode. Please install the LearnPack extension."
|
216
|
-
)
|
217
|
-
}
|
218
|
-
}
|
219
|
-
}
|
220
|
-
|
221
|
-
if (
|
222
|
-
configObj.config.suggestions &&
|
223
|
-
configObj.config.editor &&
|
224
|
-
configObj.config.suggestions.agent !== null &&
|
225
|
-
configObj.config.suggestions.agent !== configObj.config.editor.agent
|
226
|
-
) {
|
227
|
-
Console.warning(
|
228
|
-
`The suggested agent "${configObj.config.suggestions.agent}" is different from the detected agent "${configObj.config.editor.agent}"`
|
229
|
-
)
|
230
|
-
|
231
|
-
try {
|
232
|
-
configObj.config.warnings = {
|
233
|
-
...configObj.config.warnings, // Ensure we don't overwrite other warnings
|
234
|
-
agent: buildAgentWarning(
|
235
|
-
configObj.config.editor.agent,
|
236
|
-
configObj.config.suggestions.agent
|
237
|
-
),
|
238
|
-
}
|
239
|
-
} catch {
|
240
|
-
Console.error("IMPOSSIBLE TO SET WARNING")
|
241
|
-
}
|
242
|
-
}
|
243
|
-
|
244
|
-
if (configObj.config && !configObj.config.publicUrl)
|
245
|
-
configObj.config.publicUrl = `${configObj.address}:${configObj.config.port}`
|
246
|
-
|
247
|
-
if (configObj.config && !configObj.config.editor.mode && mode) {
|
248
|
-
configObj.config.editor.mode = mode as TMode
|
249
|
-
}
|
250
|
-
|
251
|
-
configObj.config.editor.mode =
|
252
|
-
process.env.TERM_PROGRAM === "vscode" ? "extension" : "preview"
|
253
|
-
|
254
|
-
if (version)
|
255
|
-
configObj.config.editor.version = version
|
256
|
-
else if (configObj.config.editor.version === null) {
|
257
|
-
Console.debug("Config version not found, downloading default.")
|
258
|
-
const resp = await fetch(
|
259
|
-
"https://raw.githubusercontent.com/learnpack/ide/master/package.json"
|
260
|
-
)
|
261
|
-
const packageJSON = await resp.json()
|
262
|
-
configObj.config.editor.version = packageJSON.version || "4.0.2"
|
263
|
-
}
|
264
|
-
|
265
|
-
configObj.config.dirPath = "./" + confPath.base
|
266
|
-
configObj.config.exercisesPath = getExercisesPath(confPath.base) || "./"
|
267
|
-
|
268
|
-
if (configObj.config.variables) {
|
269
|
-
const allowedCommands = new Set(["ls", "pwd", "echo", "node", "python"])
|
270
|
-
|
271
|
-
const variableKeys = Object.keys(configObj.config.variables)
|
272
|
-
const promises = []
|
273
|
-
|
274
|
-
for (const v of variableKeys) {
|
275
|
-
if (Object.prototype.hasOwnProperty.call(configObj.config.variables, v)) {
|
276
|
-
const variable = configObj.config.variables[v]
|
277
|
-
|
278
|
-
if (typeof variable === "string") {
|
279
|
-
continue
|
280
|
-
}
|
281
|
-
|
282
|
-
const type = variable.type
|
283
|
-
|
284
|
-
if (type === "command") {
|
285
|
-
const promise = (async () => {
|
286
|
-
try {
|
287
|
-
// Validate the command
|
288
|
-
if (!allowedCommands.has(variable.source.split(" ")[0])) {
|
289
|
-
throw new Error("Command not allowed")
|
290
|
-
}
|
291
|
-
|
292
|
-
// Execute the code and replace the value
|
293
|
-
const { stdout } = await execAsync(variable.source)
|
294
|
-
if (!configObj.config || !configObj.config.variables)
|
295
|
-
return
|
296
|
-
|
297
|
-
configObj.config.variables[v] = stdout.trim()
|
298
|
-
} catch (error) {
|
299
|
-
console.error(`Error executing code: ${error}`)
|
300
|
-
}
|
301
|
-
})()
|
302
|
-
promises.push(promise)
|
303
|
-
} else if (type === "string") {
|
304
|
-
configObj.config.variables[v] = variable.source
|
305
|
-
}
|
306
|
-
}
|
307
|
-
}
|
308
|
-
|
309
|
-
await Promise.all(promises)
|
310
|
-
}
|
311
|
-
|
312
|
-
return {
|
313
|
-
validLanguages: {},
|
314
|
-
get: () => {
|
315
|
-
return configObj
|
316
|
-
},
|
317
|
-
validateEngine: function (language: string, server: any, socket: any) {
|
318
|
-
// eslint-disable-next-line
|
319
|
-
const alias = (_l: string) => {
|
320
|
-
const map: any = {
|
321
|
-
python3: "python",
|
322
|
-
}
|
323
|
-
if (map[_l])
|
324
|
-
return map[_l]
|
325
|
-
return _l
|
326
|
-
}
|
327
|
-
|
328
|
-
// decode aliases
|
329
|
-
language = alias(language)
|
330
|
-
|
331
|
-
if (this.validLanguages[language])
|
332
|
-
return true
|
333
|
-
|
334
|
-
Console.debug(`Validating engine for ${language} compilation`)
|
335
|
-
let result = shell.exec("learnpack plugins", { silent: true })
|
336
|
-
|
337
|
-
if (
|
338
|
-
result.code === 0 &&
|
339
|
-
result.stdout.includes(`@learnpack/${language}`)
|
340
|
-
) {
|
341
|
-
this.validLanguages[language] = true
|
342
|
-
return true
|
343
|
-
}
|
344
|
-
|
345
|
-
Console.info(`Language engine for ${language} not found, installing...`)
|
346
|
-
// Install the compiler in their new versions
|
347
|
-
result = shell.exec(`learnpack plugins:install @learnpack/${language}`, {
|
348
|
-
silent: true,
|
349
|
-
})
|
350
|
-
if (result.code === 0) {
|
351
|
-
socket.log(
|
352
|
-
"compiling",
|
353
|
-
"Installing the python compiler, you will have to reset the exercises after installation by writing on your terminal: $ learnpack run"
|
354
|
-
)
|
355
|
-
Console.info(
|
356
|
-
`Successfully installed the ${language} exercise engine, \n please start learnpack again by running the following command: \n ${chalk.white(
|
357
|
-
"$ learnpack start"
|
358
|
-
)}\n\n `
|
359
|
-
)
|
360
|
-
server.terminate()
|
361
|
-
return false
|
362
|
-
}
|
363
|
-
|
364
|
-
this.validLanguages[language] = false
|
365
|
-
socket.error(`Error installing ${language} exercise engine`)
|
366
|
-
Console.error(`Error installing ${language} exercise engine`)
|
367
|
-
Console.log(result.stdout)
|
368
|
-
throw InternalError(`Error installing ${language} exercise engine`)
|
369
|
-
},
|
370
|
-
logout: () => {
|
371
|
-
if (configObj.config) {
|
372
|
-
rmSync(configObj.config.dirPath + "/.session")
|
373
|
-
}
|
374
|
-
},
|
375
|
-
clean: () => {
|
376
|
-
if (configObj.config) {
|
377
|
-
if (configObj.config.outputPath) {
|
378
|
-
rmSync(configObj.config.outputPath)
|
379
|
-
}
|
380
|
-
|
381
|
-
rmSync(configObj.config.dirPath + "/_app")
|
382
|
-
rmSync(configObj.config.dirPath + "/reports")
|
383
|
-
rmSync(configObj.config.dirPath + "/.session")
|
384
|
-
rmSync(configObj.config.dirPath + "/resets")
|
385
|
-
|
386
|
-
// clean __pycache__ folder
|
387
|
-
rmSync(configObj.config.dirPath + "/../__pycache__")
|
388
|
-
|
389
|
-
// clean the __pycache__ for each exercise it exists
|
390
|
-
if (configObj.exercises) {
|
391
|
-
for (const e of configObj.exercises) {
|
392
|
-
if (fs.existsSync(e.path + "/__pycache__")) {
|
393
|
-
rmSync(e.path + "/__pycache__")
|
394
|
-
}
|
395
|
-
}
|
396
|
-
}
|
397
|
-
|
398
|
-
// clean tag gz
|
399
|
-
if (fs.existsSync(configObj.config.dirPath + "/app.tar.gz"))
|
400
|
-
fs.unlinkSync(configObj.config.dirPath + "/app.tar.gz")
|
401
|
-
|
402
|
-
if (fs.existsSync(configObj.config.dirPath + "/config.json"))
|
403
|
-
fs.unlinkSync(configObj.config.dirPath + "/config.json")
|
404
|
-
|
405
|
-
if (fs.existsSync(configObj.config.dirPath + "/telemetry.json"))
|
406
|
-
fs.unlinkSync(configObj.config.dirPath + "/telemetry.json")
|
407
|
-
|
408
|
-
if (fs.existsSync(configObj.config.dirPath + "/vscode_queue.json"))
|
409
|
-
fs.unlinkSync(configObj.config.dirPath + "/vscode_queue.json")
|
410
|
-
}
|
411
|
-
},
|
412
|
-
getExercise: slug => {
|
413
|
-
Console.debug("ExercisePath Slug", slug)
|
414
|
-
const exercise = (configObj.exercises || []).find(
|
415
|
-
ex => ex.slug === slug
|
416
|
-
)
|
417
|
-
if (!exercise)
|
418
|
-
throw ValidationError(`Exercise ${slug} not found`)
|
419
|
-
|
420
|
-
return exercise
|
421
|
-
},
|
422
|
-
getAllExercises: () => {
|
423
|
-
return configObj.exercises
|
424
|
-
},
|
425
|
-
startExercise: function (slug: string) {
|
426
|
-
const exercise = this.getExercise(slug)
|
427
|
-
|
428
|
-
// set config.json with current exercise
|
429
|
-
configObj.currentExercise = exercise.slug
|
430
|
-
|
431
|
-
this.save()
|
432
|
-
|
433
|
-
// eslint-disable-next-line
|
434
|
-
exercise.files.forEach((f: IFile) => {
|
435
|
-
if (configObj.config) {
|
436
|
-
const _path = configObj.config.outputPath + "/" + f.name
|
437
|
-
if (f.hidden === false && fs.existsSync(_path))
|
438
|
-
fs.unlinkSync(_path)
|
439
|
-
}
|
440
|
-
})
|
441
|
-
|
442
|
-
return exercise
|
443
|
-
},
|
444
|
-
noCurrentExercise: function () {
|
445
|
-
configObj.currentExercise = null
|
446
|
-
this.save()
|
447
|
-
},
|
448
|
-
reset: slug => {
|
449
|
-
if (
|
450
|
-
configObj.config &&
|
451
|
-
!fs.existsSync(`${configObj.config.dirPath}/resets/` + slug)
|
452
|
-
)
|
453
|
-
throw ValidationError("Could not find the original files for " + slug)
|
454
|
-
|
455
|
-
const exercise = (configObj.exercises || []).find(
|
456
|
-
ex => ex.slug === slug
|
457
|
-
)
|
458
|
-
if (!exercise)
|
459
|
-
throw ValidationError(`Exercise ${slug} not found on the configuration`)
|
460
|
-
|
461
|
-
if (configObj.config) {
|
462
|
-
for (const fileName of fs.readdirSync(
|
463
|
-
`${configObj.config.dirPath}/resets/${slug}/`
|
464
|
-
)) {
|
465
|
-
const content = fs.readFileSync(
|
466
|
-
`${configObj.config?.dirPath}/resets/${slug}/${fileName}`
|
467
|
-
)
|
468
|
-
fs.writeFileSync(`${exercise.path}/${fileName}`, content)
|
469
|
-
}
|
470
|
-
}
|
471
|
-
},
|
472
|
-
buildIndex: function () {
|
473
|
-
Console.info("Building the exercise index...")
|
474
|
-
|
475
|
-
const isDirectory = (source: string) => {
|
476
|
-
const name = path.basename(source)
|
477
|
-
if (name === path.basename(configObj?.config?.dirPath || ""))
|
478
|
-
return false
|
479
|
-
// ignore folders that start with a dot
|
480
|
-
if (name.charAt(0) === "." || name.charAt(0) === "_")
|
481
|
-
return false
|
482
|
-
|
483
|
-
return fs.lstatSync(source).isDirectory()
|
484
|
-
}
|
485
|
-
|
486
|
-
const getDirectories = (source: string) =>
|
487
|
-
fs
|
488
|
-
.readdirSync(source)
|
489
|
-
.map(name => path.join(source, name))
|
490
|
-
.filter(isDirectory)
|
491
|
-
// add the .learn folder
|
492
|
-
if (!fs.existsSync(confPath.base))
|
493
|
-
fs.mkdirSync(confPath.base)
|
494
|
-
// add the outout folder where webpack will publish the the html/css/js files
|
495
|
-
if (
|
496
|
-
configObj.config &&
|
497
|
-
configObj.config.outputPath &&
|
498
|
-
!fs.existsSync(configObj.config.outputPath)
|
499
|
-
)
|
500
|
-
fs.mkdirSync(configObj.config.outputPath)
|
501
|
-
|
502
|
-
// TODO: we could use npm library front-mater to read the title of the exercises from the README.md
|
503
|
-
const grupedByDirectory = getDirectories(
|
504
|
-
configObj?.config?.exercisesPath || ""
|
505
|
-
)
|
506
|
-
configObj.exercises =
|
507
|
-
grupedByDirectory.length > 0 ?
|
508
|
-
grupedByDirectory.map((path, position) =>
|
509
|
-
exercise(path, position, configObj)
|
510
|
-
) :
|
511
|
-
[exercise(configObj?.config?.exercisesPath || "", 0, configObj)]
|
512
|
-
this.save()
|
513
|
-
},
|
514
|
-
watchIndex: function (onChange: (filename: string) => void) {
|
515
|
-
if (configObj.config && !configObj.config.exercisesPath)
|
516
|
-
throw ValidationError(
|
517
|
-
"No exercises directory to watch: " + configObj.config.exercisesPath
|
518
|
-
)
|
519
|
-
|
520
|
-
this.buildIndex()
|
521
|
-
|
522
|
-
watch(configObj?.config?.exercisesPath || "", onChange)
|
523
|
-
.then(() => {
|
524
|
-
Console.debug("Changes detected on your exercises")
|
525
|
-
this.buildIndex()
|
526
|
-
// if (onChange) onChange(filename);
|
527
|
-
})
|
528
|
-
.catch(error => {
|
529
|
-
throw error
|
530
|
-
})
|
531
|
-
},
|
532
|
-
|
533
|
-
save: () => {
|
534
|
-
Console.debug("Saving configuration with: ", configObj)
|
535
|
-
// remove the duplicates form the actions array
|
536
|
-
// configObj.config.actions = [...new Set(configObj.config.actions)];
|
537
|
-
if (configObj.config) {
|
538
|
-
configObj.config.translations = [
|
539
|
-
...new Set(configObj.config.translations),
|
540
|
-
]
|
541
|
-
fs.writeFileSync(
|
542
|
-
configObj.config.dirPath + "/config.json",
|
543
|
-
JSON.stringify(configObj, null, 4)
|
544
|
-
)
|
545
|
-
}
|
546
|
-
},
|
547
|
-
} as IConfigManager
|
548
|
-
}
|
549
|
-
|
550
|
-
function deepMerge(...sources: any): any {
|
551
|
-
let acc: any = {}
|
552
|
-
for (const source of sources) {
|
553
|
-
if (Array.isArray(source)) {
|
554
|
-
if (!Array.isArray(acc)) {
|
555
|
-
acc = []
|
556
|
-
}
|
557
|
-
|
558
|
-
acc = [...source]
|
559
|
-
} else if (source instanceof Object) {
|
560
|
-
// eslint-disable-next-line
|
561
|
-
for (let [key, value] of Object.entries(source)) {
|
562
|
-
if (value instanceof Object && key in acc) {
|
563
|
-
value = deepMerge(acc[key], value)
|
564
|
-
}
|
565
|
-
|
566
|
-
if (value !== undefined)
|
567
|
-
acc = { ...acc, [key]: value }
|
568
|
-
}
|
569
|
-
}
|
570
|
-
}
|
571
|
-
|
572
|
-
return acc
|
573
|
-
}
|
574
|
-
|
575
|
-
const buildAgentWarning = (current: TAgent, suggested: TAgent): string => {
|
576
|
-
const message = `# Agent mismatch!\n
|
577
|
-
|
578
|
-
In LearnPack, the agent is in charge of running the LearnPack interface.
|
579
|
-
|
580
|
-
You're currently using LearnPack through \`${current}\` but the suggested agent is \`${suggested}\`.
|
581
|
-
|
582
|
-
We recommend strongly recommend changing your agent.
|
583
|
-
|
584
|
-
${stepsToChangeAgent(suggested)}
|
585
|
-
`
|
586
|
-
|
587
|
-
return message
|
588
|
-
}
|
589
|
-
|
590
|
-
const stepsToChangeAgent = (agent: TAgent): string => {
|
591
|
-
if (agent === "vscode") {
|
592
|
-
return `
|
593
|
-
# Steps to Change Agent to VSCode
|
594
|
-
|
595
|
-
1. **Install VSCode**:
|
596
|
-
- Visit the [VSCode website](https://code.visualstudio.com/Download) and download the latest version.
|
597
|
-
- Follow the installation instructions for your operating system.
|
598
|
-
|
599
|
-
2. **Install LearnPack VSCode Extension**:
|
600
|
-
- Open VSCode.
|
601
|
-
- Go to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window or by pressing \`Ctrl+Shift+X\`.
|
602
|
-
- Search for "LearnPack" and click "Install".
|
603
|
-
- If the extension is already installed but disabled, enable it.
|
604
|
-
|
605
|
-
3. **Run LearnPack in VSCode**:
|
606
|
-
- Open your terminal in VSCode.
|
607
|
-
- Navigate to your LearnPack project directory.
|
608
|
-
- Run the following command:
|
609
|
-
\`\`\`sh
|
610
|
-
learnpack start
|
611
|
-
\`\`\`
|
612
|
-
|
613
|
-
We strongly recommend using VSCode for a better learning experience.
|
614
|
-
`
|
615
|
-
}
|
616
|
-
|
617
|
-
if (agent === "os") {
|
618
|
-
return `
|
619
|
-
# Steps to Change Agent to OS
|
620
|
-
|
621
|
-
This learning package was designed to run outside of VSCode. We strongly recommend closing VSCode and running the package independently.
|
622
|
-
|
623
|
-
1. **Close VSCode**:
|
624
|
-
- Save your work and close the VSCode application.
|
625
|
-
|
626
|
-
2. **Open a New Terminal**:
|
627
|
-
- Open a terminal or command prompt on your operating system.
|
628
|
-
|
629
|
-
3. **Navigate to Your LearnPack Project Directory**:
|
630
|
-
- Use the \`cd\` command to navigate to the directory where your LearnPack project is located.
|
631
|
-
|
632
|
-
4. **Run LearnPack**:
|
633
|
-
- Run the following command to start LearnPack:
|
634
|
-
\`\`\`sh
|
635
|
-
learnpack start
|
636
|
-
\`\`\`
|
637
|
-
|
638
|
-
We strongly recommend running the package independently for a better learning experience.
|
639
|
-
`
|
640
|
-
}
|
641
|
-
|
642
|
-
return ""
|
643
|
-
}
|
644
|
-
|
645
|
-
/**
|
646
|
-
* Checks if the 'code' command is available in the terminal.
|
647
|
-
*
|
648
|
-
* @returns {boolean} True if the 'code' command is available, false otherwise.
|
649
|
-
*/
|
650
|
-
const isCodeCommandAvailable = (): boolean => {
|
651
|
-
return shell.which("code") !== null
|
652
|
-
}
|
653
|
-
|
654
|
-
/**
|
655
|
-
* Checks if a specific VSCode extension is installed.
|
656
|
-
*
|
657
|
-
* @param {string} extensionName - The name of the extension to check.
|
658
|
-
* @returns {boolean} True if the extension is installed, false otherwise.
|
659
|
-
*/
|
660
|
-
const isExtensionInstalled = (extensionName: string): boolean => {
|
661
|
-
if (!isCodeCommandAvailable()) {
|
662
|
-
throw new Error(
|
663
|
-
"The 'code' command is not available in the terminal. Please ensure that VSCode is installed and the 'code' command is added to your PATH."
|
664
|
-
)
|
665
|
-
}
|
666
|
-
|
667
|
-
const result = shell.exec("code --list-extensions", { silent: true })
|
668
|
-
return result.stdout.split("\n").includes(extensionName)
|
669
|
-
}
|
670
|
-
|
671
|
-
const EXTENSION_INSTALLATION_STEPS = `
|
672
|
-
# Steps to Install LearnPack VSCode Extension
|
673
|
-
|
674
|
-
1. **Open VSCode**:
|
675
|
-
- Launch the Visual Studio Code application on your computer.
|
676
|
-
|
677
|
-
2. **Go to Extensions View**:
|
678
|
-
- Click on the Extensions icon in the Activity Bar on the side of the window.
|
679
|
-
- Alternatively, you can open the Extensions view by pressing \`Ctrl+Shift+X\`.
|
680
|
-
|
681
|
-
3. **Search for LearnPack**:
|
682
|
-
- In the Extensions view, type "LearnPack" into the search bar.
|
683
|
-
|
684
|
-
4. **Install the Extension**:
|
685
|
-
- Find the "LearnPack" extension in the search results and click the "Install" button.
|
686
|
-
- If the extension is already installed but disabled, click the "Enable" button.
|
687
|
-
|
688
|
-
5. **Verify Installation**:
|
689
|
-
- Once installed, you can verify the installation by running the following command in the terminal:
|
690
|
-
\`\`\`sh
|
691
|
-
code --list-extensions | grep learn-pack.learnpack-vscode
|
692
|
-
\`\`\`
|
693
|
-
- If the extension is listed, it means the installation was successful.
|
694
|
-
|
695
|
-
We strongly recommend using the LearnPack extension in VSCode for a better learning experience.
|
696
|
-
`
|
697
|
-
|
698
|
-
/**
|
699
|
-
* Installs the LearnPack VSCode extension if the 'code' command is available.
|
700
|
-
*
|
701
|
-
* @param {string} extensionName - The name of the extension to install.
|
702
|
-
* @returns {boolean} True if the installation was successful, false otherwise.
|
703
|
-
*/
|
704
|
-
const installExtension = (extensionName: string): boolean => {
|
705
|
-
if (!isCodeCommandAvailable()) {
|
706
|
-
throw new Error(
|
707
|
-
"The 'code' command is not available in the terminal. Please ensure that VSCode is installed and the 'code' command is added to your PATH."
|
708
|
-
)
|
709
|
-
}
|
710
|
-
|
711
|
-
const result = shell.exec(`code --install-extension ${extensionName}`, {
|
712
|
-
silent: true,
|
713
|
-
})
|
714
|
-
return result.code === 0
|
715
|
-
}
|
1
|
+
import * as path from "path"
|
2
|
+
import * as fs from "fs"
|
3
|
+
import * as shell from "shelljs"
|
4
|
+
import { exec } from "child_process"
|
5
|
+
import { promisify } from "util"
|
6
|
+
|
7
|
+
import Console from "../../utils/console"
|
8
|
+
import watch from "../../utils/watcher"
|
9
|
+
import {
|
10
|
+
ValidationError,
|
11
|
+
NotFoundError,
|
12
|
+
InternalError,
|
13
|
+
} from "../../utils/errors"
|
14
|
+
|
15
|
+
import defaults from "./defaults"
|
16
|
+
import { exercise } from "./exercise"
|
17
|
+
|
18
|
+
import { rmSync } from "../file"
|
19
|
+
import {
|
20
|
+
IConfigObj,
|
21
|
+
TConfigObjAttributes,
|
22
|
+
TMode,
|
23
|
+
TAgent,
|
24
|
+
} from "../../models/config"
|
25
|
+
import {
|
26
|
+
IConfigManagerAttributes,
|
27
|
+
IConfigManager,
|
28
|
+
} from "../../models/config-manager"
|
29
|
+
import { IFile } from "../../models/file"
|
30
|
+
|
31
|
+
/* exercise folder name standard */
|
32
|
+
const execAsync = promisify(exec)
|
33
|
+
|
34
|
+
// eslint-disable-next-line
|
35
|
+
const fetch = require("node-fetch")
|
36
|
+
// eslint-disable-next-line
|
37
|
+
const chalk = require("chalk")
|
38
|
+
|
39
|
+
/* exercise folder name standard */
|
40
|
+
|
41
|
+
/**
|
42
|
+
* Retrieves the configuration path for the learnpack package.
|
43
|
+
*
|
44
|
+
* @returns An object containing the configuration file path and the base directory.
|
45
|
+
* @throws NotFoundError if the learn.json file is not found in the current folder.
|
46
|
+
*/
|
47
|
+
const getConfigPath = () => {
|
48
|
+
const possibleFileNames = ["learn.json", ".learn/learn.json"]
|
49
|
+
const config = possibleFileNames.find(file => fs.existsSync(file)) || null
|
50
|
+
if (config && fs.existsSync(".breathecode"))
|
51
|
+
return { config, base: ".breathecode" }
|
52
|
+
if (config === null)
|
53
|
+
throw NotFoundError(
|
54
|
+
"learn.json file not found on current folder, is this a learnpack package?"
|
55
|
+
)
|
56
|
+
return { config, base: ".learn" }
|
57
|
+
}
|
58
|
+
|
59
|
+
const getExercisesPath = (base: string) => {
|
60
|
+
const possibleFileNames = ["./exercises", base + "/exercises", "./"]
|
61
|
+
return possibleFileNames.find(file => fs.existsSync(file)) || null
|
62
|
+
}
|
63
|
+
|
64
|
+
const getGitpodAddress = () => {
|
65
|
+
if (shell.exec("gp -h", { silent: true }).code === 0) {
|
66
|
+
return shell
|
67
|
+
.exec("gp url", { silent: true })
|
68
|
+
.stdout.replace(/(\r\n|\n|\r)/gm, "")
|
69
|
+
}
|
70
|
+
|
71
|
+
Console.debug("Gitpod command line tool not found")
|
72
|
+
return "http://localhost"
|
73
|
+
}
|
74
|
+
|
75
|
+
const getCodespacesNamespace = () => {
|
76
|
+
// Example: https://orange-rotary-phone-wxpg49q5gcg4rp-3000.app.github.dev
|
77
|
+
|
78
|
+
const codespace_name = shell
|
79
|
+
.exec("echo $CODESPACE_NAME", { silent: true })
|
80
|
+
.stdout.replace(/(\r\n|\n|\r)/gm, "")
|
81
|
+
|
82
|
+
if (
|
83
|
+
!codespace_name ||
|
84
|
+
codespace_name === "" ||
|
85
|
+
codespace_name === undefined ||
|
86
|
+
codespace_name === "$CODESPACE_NAME"
|
87
|
+
) {
|
88
|
+
return null
|
89
|
+
}
|
90
|
+
|
91
|
+
return codespace_name
|
92
|
+
}
|
93
|
+
|
94
|
+
export default async ({
|
95
|
+
grading,
|
96
|
+
mode,
|
97
|
+
disableGrading,
|
98
|
+
version,
|
99
|
+
}: IConfigManagerAttributes): Promise<IConfigManager> => {
|
100
|
+
const confPath = getConfigPath()
|
101
|
+
Console.debug("This is the config path: ", confPath)
|
102
|
+
|
103
|
+
let configObj: IConfigObj = {}
|
104
|
+
|
105
|
+
if (confPath) {
|
106
|
+
const learnJsonContent = fs.readFileSync(confPath.config)
|
107
|
+
let hiddenBcContent = {}
|
108
|
+
|
109
|
+
if (fs.existsSync(confPath.base + "/config.json")) {
|
110
|
+
hiddenBcContent = fs.readFileSync(confPath.base + "/config.json")
|
111
|
+
hiddenBcContent = JSON.parse(hiddenBcContent as string)
|
112
|
+
if (!hiddenBcContent)
|
113
|
+
throw new Error(
|
114
|
+
`Invalid ${confPath.base}/config.json syntax: Unable to parse.`
|
115
|
+
)
|
116
|
+
}
|
117
|
+
|
118
|
+
const jsonConfig = JSON.parse(`${learnJsonContent}`)
|
119
|
+
|
120
|
+
if (!jsonConfig)
|
121
|
+
throw new Error(`Invalid ${confPath.config} syntax: Unable to parse.`)
|
122
|
+
|
123
|
+
let session: number
|
124
|
+
|
125
|
+
// add using id to the installation
|
126
|
+
if (!jsonConfig.session) {
|
127
|
+
session = Math.floor(Math.random() * 10_000_000_000_000_000_000)
|
128
|
+
} else {
|
129
|
+
session = jsonConfig.session
|
130
|
+
delete jsonConfig.session
|
131
|
+
}
|
132
|
+
|
133
|
+
configObj = deepMerge(hiddenBcContent, {
|
134
|
+
config: jsonConfig,
|
135
|
+
session: session,
|
136
|
+
})
|
137
|
+
} else {
|
138
|
+
throw ValidationError(
|
139
|
+
"No learn.json file has been found, make sure you are in the correct directory. To start a new LearnPack package run: $ learnpack init my-course-name"
|
140
|
+
)
|
141
|
+
}
|
142
|
+
|
143
|
+
configObj = deepMerge(defaults || {}, configObj, {
|
144
|
+
config: {
|
145
|
+
grading: grading || configObj.config?.grading,
|
146
|
+
configPath: confPath.config,
|
147
|
+
},
|
148
|
+
})
|
149
|
+
if (!configObj.config)
|
150
|
+
throw InternalError("Config object not found")
|
151
|
+
|
152
|
+
configObj.config.outputPath = confPath.base + "/dist"
|
153
|
+
|
154
|
+
Console.debug("This is your configuration object: ", {
|
155
|
+
...configObj,
|
156
|
+
exercises: configObj.exercises ?
|
157
|
+
configObj.exercises.map(e => e.slug) :
|
158
|
+
[],
|
159
|
+
})
|
160
|
+
|
161
|
+
// auto detect agent (if possible)
|
162
|
+
const codespaces_workspace = getCodespacesNamespace()
|
163
|
+
Console.debug("This is the codespace namespace: ", codespaces_workspace)
|
164
|
+
|
165
|
+
if (!configObj.config.editor) {
|
166
|
+
configObj.config.editor = {}
|
167
|
+
}
|
168
|
+
|
169
|
+
Console.debug(
|
170
|
+
"This is the agent, and this should be null an the beginning: ",
|
171
|
+
configObj.config?.editor?.agent
|
172
|
+
)
|
173
|
+
|
174
|
+
if (configObj.config?.editor?.agent) {
|
175
|
+
if (configObj.config.suggestions) {
|
176
|
+
configObj.config.suggestions.agent = configObj.config.editor.agent
|
177
|
+
} else {
|
178
|
+
configObj.config.suggestions = { agent: configObj.config.editor.agent }
|
179
|
+
}
|
180
|
+
}
|
181
|
+
|
182
|
+
if (shell.which("gp") && configObj && configObj.config) {
|
183
|
+
Console.debug("Gitpod detected")
|
184
|
+
configObj.address = getGitpodAddress()
|
185
|
+
configObj.config.publicUrl = `https://${
|
186
|
+
configObj.config.port
|
187
|
+
}-${configObj.address?.slice(8)}`
|
188
|
+
configObj.config.editor.agent = "vscode"
|
189
|
+
} else if (configObj.config && Boolean(codespaces_workspace)) {
|
190
|
+
Console.debug("Codespaces detected: ", codespaces_workspace)
|
191
|
+
configObj.address = `https://${codespaces_workspace}.github.dev`
|
192
|
+
configObj.config.publicUrl = `https://${codespaces_workspace}-${configObj.config.port}.app.github.dev`
|
193
|
+
configObj.config.editor.agent = "vscode"
|
194
|
+
} else {
|
195
|
+
Console.debug("Neither Gitpod nor Codespaces detected, using localhost.")
|
196
|
+
configObj.address = `http://localhost:${configObj.config.port}`
|
197
|
+
configObj.config.publicUrl = `http://localhost:${configObj.config.port}`
|
198
|
+
configObj.config.editor.agent =
|
199
|
+
process.env.TERM_PROGRAM === "vscode" ? "vscode" : "os"
|
200
|
+
}
|
201
|
+
|
202
|
+
if (configObj.config.editor.agent === "vscode" && isCodeCommandAvailable()) {
|
203
|
+
const extensionName = "learn-pack.learnpack-vscode"
|
204
|
+
|
205
|
+
if (!isExtensionInstalled(extensionName)) {
|
206
|
+
Console.info(
|
207
|
+
"The LearnPack extension is not installed, trying to install it automatically."
|
208
|
+
)
|
209
|
+
|
210
|
+
if (!installExtension(extensionName)) {
|
211
|
+
configObj.config.warnings = {
|
212
|
+
extension: EXTENSION_INSTALLATION_STEPS,
|
213
|
+
}
|
214
|
+
Console.warning(
|
215
|
+
"The LearnPack extension is not installed and this tutorial is meant to be run inside VSCode. Please install the LearnPack extension."
|
216
|
+
)
|
217
|
+
}
|
218
|
+
}
|
219
|
+
}
|
220
|
+
|
221
|
+
if (
|
222
|
+
configObj.config.suggestions &&
|
223
|
+
configObj.config.editor &&
|
224
|
+
configObj.config.suggestions.agent !== null &&
|
225
|
+
configObj.config.suggestions.agent !== configObj.config.editor.agent
|
226
|
+
) {
|
227
|
+
Console.warning(
|
228
|
+
`The suggested agent "${configObj.config.suggestions.agent}" is different from the detected agent "${configObj.config.editor.agent}"`
|
229
|
+
)
|
230
|
+
|
231
|
+
try {
|
232
|
+
configObj.config.warnings = {
|
233
|
+
...configObj.config.warnings, // Ensure we don't overwrite other warnings
|
234
|
+
agent: buildAgentWarning(
|
235
|
+
configObj.config.editor.agent,
|
236
|
+
configObj.config.suggestions.agent
|
237
|
+
),
|
238
|
+
}
|
239
|
+
} catch {
|
240
|
+
Console.error("IMPOSSIBLE TO SET WARNING")
|
241
|
+
}
|
242
|
+
}
|
243
|
+
|
244
|
+
if (configObj.config && !configObj.config.publicUrl)
|
245
|
+
configObj.config.publicUrl = `${configObj.address}:${configObj.config.port}`
|
246
|
+
|
247
|
+
if (configObj.config && !configObj.config.editor.mode && mode) {
|
248
|
+
configObj.config.editor.mode = mode as TMode
|
249
|
+
}
|
250
|
+
|
251
|
+
configObj.config.editor.mode =
|
252
|
+
process.env.TERM_PROGRAM === "vscode" ? "extension" : "preview"
|
253
|
+
|
254
|
+
if (version)
|
255
|
+
configObj.config.editor.version = version
|
256
|
+
else if (configObj.config.editor.version === null) {
|
257
|
+
Console.debug("Config version not found, downloading default.")
|
258
|
+
const resp = await fetch(
|
259
|
+
"https://raw.githubusercontent.com/learnpack/ide/master/package.json"
|
260
|
+
)
|
261
|
+
const packageJSON = await resp.json()
|
262
|
+
configObj.config.editor.version = packageJSON.version || "4.0.2"
|
263
|
+
}
|
264
|
+
|
265
|
+
configObj.config.dirPath = "./" + confPath.base
|
266
|
+
configObj.config.exercisesPath = getExercisesPath(confPath.base) || "./"
|
267
|
+
|
268
|
+
if (configObj.config.variables) {
|
269
|
+
const allowedCommands = new Set(["ls", "pwd", "echo", "node", "python"])
|
270
|
+
|
271
|
+
const variableKeys = Object.keys(configObj.config.variables)
|
272
|
+
const promises = []
|
273
|
+
|
274
|
+
for (const v of variableKeys) {
|
275
|
+
if (Object.prototype.hasOwnProperty.call(configObj.config.variables, v)) {
|
276
|
+
const variable = configObj.config.variables[v]
|
277
|
+
|
278
|
+
if (typeof variable === "string") {
|
279
|
+
continue
|
280
|
+
}
|
281
|
+
|
282
|
+
const type = variable.type
|
283
|
+
|
284
|
+
if (type === "command") {
|
285
|
+
const promise = (async () => {
|
286
|
+
try {
|
287
|
+
// Validate the command
|
288
|
+
if (!allowedCommands.has(variable.source.split(" ")[0])) {
|
289
|
+
throw new Error("Command not allowed")
|
290
|
+
}
|
291
|
+
|
292
|
+
// Execute the code and replace the value
|
293
|
+
const { stdout } = await execAsync(variable.source)
|
294
|
+
if (!configObj.config || !configObj.config.variables)
|
295
|
+
return
|
296
|
+
|
297
|
+
configObj.config.variables[v] = stdout.trim()
|
298
|
+
} catch (error) {
|
299
|
+
console.error(`Error executing code: ${error}`)
|
300
|
+
}
|
301
|
+
})()
|
302
|
+
promises.push(promise)
|
303
|
+
} else if (type === "string") {
|
304
|
+
configObj.config.variables[v] = variable.source
|
305
|
+
}
|
306
|
+
}
|
307
|
+
}
|
308
|
+
|
309
|
+
await Promise.all(promises)
|
310
|
+
}
|
311
|
+
|
312
|
+
return {
|
313
|
+
validLanguages: {},
|
314
|
+
get: () => {
|
315
|
+
return configObj
|
316
|
+
},
|
317
|
+
validateEngine: function (language: string, server: any, socket: any) {
|
318
|
+
// eslint-disable-next-line
|
319
|
+
const alias = (_l: string) => {
|
320
|
+
const map: any = {
|
321
|
+
python3: "python",
|
322
|
+
}
|
323
|
+
if (map[_l])
|
324
|
+
return map[_l]
|
325
|
+
return _l
|
326
|
+
}
|
327
|
+
|
328
|
+
// decode aliases
|
329
|
+
language = alias(language)
|
330
|
+
|
331
|
+
if (this.validLanguages[language])
|
332
|
+
return true
|
333
|
+
|
334
|
+
Console.debug(`Validating engine for ${language} compilation`)
|
335
|
+
let result = shell.exec("learnpack plugins", { silent: true })
|
336
|
+
|
337
|
+
if (
|
338
|
+
result.code === 0 &&
|
339
|
+
result.stdout.includes(`@learnpack/${language}`)
|
340
|
+
) {
|
341
|
+
this.validLanguages[language] = true
|
342
|
+
return true
|
343
|
+
}
|
344
|
+
|
345
|
+
Console.info(`Language engine for ${language} not found, installing...`)
|
346
|
+
// Install the compiler in their new versions
|
347
|
+
result = shell.exec(`learnpack plugins:install @learnpack/${language}`, {
|
348
|
+
silent: true,
|
349
|
+
})
|
350
|
+
if (result.code === 0) {
|
351
|
+
socket.log(
|
352
|
+
"compiling",
|
353
|
+
"Installing the python compiler, you will have to reset the exercises after installation by writing on your terminal: $ learnpack run"
|
354
|
+
)
|
355
|
+
Console.info(
|
356
|
+
`Successfully installed the ${language} exercise engine, \n please start learnpack again by running the following command: \n ${chalk.white(
|
357
|
+
"$ learnpack start"
|
358
|
+
)}\n\n `
|
359
|
+
)
|
360
|
+
server.terminate()
|
361
|
+
return false
|
362
|
+
}
|
363
|
+
|
364
|
+
this.validLanguages[language] = false
|
365
|
+
socket.error(`Error installing ${language} exercise engine`)
|
366
|
+
Console.error(`Error installing ${language} exercise engine`)
|
367
|
+
Console.log(result.stdout)
|
368
|
+
throw InternalError(`Error installing ${language} exercise engine`)
|
369
|
+
},
|
370
|
+
logout: () => {
|
371
|
+
if (configObj.config) {
|
372
|
+
rmSync(configObj.config.dirPath + "/.session")
|
373
|
+
}
|
374
|
+
},
|
375
|
+
clean: () => {
|
376
|
+
if (configObj.config) {
|
377
|
+
if (configObj.config.outputPath) {
|
378
|
+
rmSync(configObj.config.outputPath)
|
379
|
+
}
|
380
|
+
|
381
|
+
rmSync(configObj.config.dirPath + "/_app")
|
382
|
+
rmSync(configObj.config.dirPath + "/reports")
|
383
|
+
rmSync(configObj.config.dirPath + "/.session")
|
384
|
+
rmSync(configObj.config.dirPath + "/resets")
|
385
|
+
|
386
|
+
// clean __pycache__ folder
|
387
|
+
rmSync(configObj.config.dirPath + "/../__pycache__")
|
388
|
+
|
389
|
+
// clean the __pycache__ for each exercise it exists
|
390
|
+
if (configObj.exercises) {
|
391
|
+
for (const e of configObj.exercises) {
|
392
|
+
if (fs.existsSync(e.path + "/__pycache__")) {
|
393
|
+
rmSync(e.path + "/__pycache__")
|
394
|
+
}
|
395
|
+
}
|
396
|
+
}
|
397
|
+
|
398
|
+
// clean tag gz
|
399
|
+
if (fs.existsSync(configObj.config.dirPath + "/app.tar.gz"))
|
400
|
+
fs.unlinkSync(configObj.config.dirPath + "/app.tar.gz")
|
401
|
+
|
402
|
+
if (fs.existsSync(configObj.config.dirPath + "/config.json"))
|
403
|
+
fs.unlinkSync(configObj.config.dirPath + "/config.json")
|
404
|
+
|
405
|
+
if (fs.existsSync(configObj.config.dirPath + "/telemetry.json"))
|
406
|
+
fs.unlinkSync(configObj.config.dirPath + "/telemetry.json")
|
407
|
+
|
408
|
+
if (fs.existsSync(configObj.config.dirPath + "/vscode_queue.json"))
|
409
|
+
fs.unlinkSync(configObj.config.dirPath + "/vscode_queue.json")
|
410
|
+
}
|
411
|
+
},
|
412
|
+
getExercise: slug => {
|
413
|
+
Console.debug("ExercisePath Slug", slug)
|
414
|
+
const exercise = (configObj.exercises || []).find(
|
415
|
+
ex => ex.slug === slug
|
416
|
+
)
|
417
|
+
if (!exercise)
|
418
|
+
throw ValidationError(`Exercise ${slug} not found`)
|
419
|
+
|
420
|
+
return exercise
|
421
|
+
},
|
422
|
+
getAllExercises: () => {
|
423
|
+
return configObj.exercises
|
424
|
+
},
|
425
|
+
startExercise: function (slug: string) {
|
426
|
+
const exercise = this.getExercise(slug)
|
427
|
+
|
428
|
+
// set config.json with current exercise
|
429
|
+
configObj.currentExercise = exercise.slug
|
430
|
+
|
431
|
+
this.save()
|
432
|
+
|
433
|
+
// eslint-disable-next-line
|
434
|
+
exercise.files.forEach((f: IFile) => {
|
435
|
+
if (configObj.config) {
|
436
|
+
const _path = configObj.config.outputPath + "/" + f.name
|
437
|
+
if (f.hidden === false && fs.existsSync(_path))
|
438
|
+
fs.unlinkSync(_path)
|
439
|
+
}
|
440
|
+
})
|
441
|
+
|
442
|
+
return exercise
|
443
|
+
},
|
444
|
+
noCurrentExercise: function () {
|
445
|
+
configObj.currentExercise = null
|
446
|
+
this.save()
|
447
|
+
},
|
448
|
+
reset: slug => {
|
449
|
+
if (
|
450
|
+
configObj.config &&
|
451
|
+
!fs.existsSync(`${configObj.config.dirPath}/resets/` + slug)
|
452
|
+
)
|
453
|
+
throw ValidationError("Could not find the original files for " + slug)
|
454
|
+
|
455
|
+
const exercise = (configObj.exercises || []).find(
|
456
|
+
ex => ex.slug === slug
|
457
|
+
)
|
458
|
+
if (!exercise)
|
459
|
+
throw ValidationError(`Exercise ${slug} not found on the configuration`)
|
460
|
+
|
461
|
+
if (configObj.config) {
|
462
|
+
for (const fileName of fs.readdirSync(
|
463
|
+
`${configObj.config.dirPath}/resets/${slug}/`
|
464
|
+
)) {
|
465
|
+
const content = fs.readFileSync(
|
466
|
+
`${configObj.config?.dirPath}/resets/${slug}/${fileName}`
|
467
|
+
)
|
468
|
+
fs.writeFileSync(`${exercise.path}/${fileName}`, content)
|
469
|
+
}
|
470
|
+
}
|
471
|
+
},
|
472
|
+
buildIndex: function () {
|
473
|
+
Console.info("Building the exercise index...")
|
474
|
+
|
475
|
+
const isDirectory = (source: string) => {
|
476
|
+
const name = path.basename(source)
|
477
|
+
if (name === path.basename(configObj?.config?.dirPath || ""))
|
478
|
+
return false
|
479
|
+
// ignore folders that start with a dot
|
480
|
+
if (name.charAt(0) === "." || name.charAt(0) === "_")
|
481
|
+
return false
|
482
|
+
|
483
|
+
return fs.lstatSync(source).isDirectory()
|
484
|
+
}
|
485
|
+
|
486
|
+
const getDirectories = (source: string) =>
|
487
|
+
fs
|
488
|
+
.readdirSync(source)
|
489
|
+
.map(name => path.join(source, name))
|
490
|
+
.filter(isDirectory)
|
491
|
+
// add the .learn folder
|
492
|
+
if (!fs.existsSync(confPath.base))
|
493
|
+
fs.mkdirSync(confPath.base)
|
494
|
+
// add the outout folder where webpack will publish the the html/css/js files
|
495
|
+
if (
|
496
|
+
configObj.config &&
|
497
|
+
configObj.config.outputPath &&
|
498
|
+
!fs.existsSync(configObj.config.outputPath)
|
499
|
+
)
|
500
|
+
fs.mkdirSync(configObj.config.outputPath)
|
501
|
+
|
502
|
+
// TODO: we could use npm library front-mater to read the title of the exercises from the README.md
|
503
|
+
const grupedByDirectory = getDirectories(
|
504
|
+
configObj?.config?.exercisesPath || ""
|
505
|
+
)
|
506
|
+
configObj.exercises =
|
507
|
+
grupedByDirectory.length > 0 ?
|
508
|
+
grupedByDirectory.map((path, position) =>
|
509
|
+
exercise(path, position, configObj)
|
510
|
+
) :
|
511
|
+
[exercise(configObj?.config?.exercisesPath || "", 0, configObj)]
|
512
|
+
this.save()
|
513
|
+
},
|
514
|
+
watchIndex: function (onChange: (filename: string) => void) {
|
515
|
+
if (configObj.config && !configObj.config.exercisesPath)
|
516
|
+
throw ValidationError(
|
517
|
+
"No exercises directory to watch: " + configObj.config.exercisesPath
|
518
|
+
)
|
519
|
+
|
520
|
+
this.buildIndex()
|
521
|
+
|
522
|
+
watch(configObj?.config?.exercisesPath || "", onChange)
|
523
|
+
.then(() => {
|
524
|
+
Console.debug("Changes detected on your exercises")
|
525
|
+
this.buildIndex()
|
526
|
+
// if (onChange) onChange(filename);
|
527
|
+
})
|
528
|
+
.catch(error => {
|
529
|
+
throw error
|
530
|
+
})
|
531
|
+
},
|
532
|
+
|
533
|
+
save: () => {
|
534
|
+
Console.debug("Saving configuration with: ", configObj)
|
535
|
+
// remove the duplicates form the actions array
|
536
|
+
// configObj.config.actions = [...new Set(configObj.config.actions)];
|
537
|
+
if (configObj.config) {
|
538
|
+
configObj.config.translations = [
|
539
|
+
...new Set(configObj.config.translations),
|
540
|
+
]
|
541
|
+
fs.writeFileSync(
|
542
|
+
configObj.config.dirPath + "/config.json",
|
543
|
+
JSON.stringify(configObj, null, 4)
|
544
|
+
)
|
545
|
+
}
|
546
|
+
},
|
547
|
+
} as IConfigManager
|
548
|
+
}
|
549
|
+
|
550
|
+
function deepMerge(...sources: any): any {
|
551
|
+
let acc: any = {}
|
552
|
+
for (const source of sources) {
|
553
|
+
if (Array.isArray(source)) {
|
554
|
+
if (!Array.isArray(acc)) {
|
555
|
+
acc = []
|
556
|
+
}
|
557
|
+
|
558
|
+
acc = [...source]
|
559
|
+
} else if (source instanceof Object) {
|
560
|
+
// eslint-disable-next-line
|
561
|
+
for (let [key, value] of Object.entries(source)) {
|
562
|
+
if (value instanceof Object && key in acc) {
|
563
|
+
value = deepMerge(acc[key], value)
|
564
|
+
}
|
565
|
+
|
566
|
+
if (value !== undefined)
|
567
|
+
acc = { ...acc, [key]: value }
|
568
|
+
}
|
569
|
+
}
|
570
|
+
}
|
571
|
+
|
572
|
+
return acc
|
573
|
+
}
|
574
|
+
|
575
|
+
const buildAgentWarning = (current: TAgent, suggested: TAgent): string => {
|
576
|
+
const message = `# Agent mismatch!\n
|
577
|
+
|
578
|
+
In LearnPack, the agent is in charge of running the LearnPack interface.
|
579
|
+
|
580
|
+
You're currently using LearnPack through \`${current}\` but the suggested agent is \`${suggested}\`.
|
581
|
+
|
582
|
+
We recommend strongly recommend changing your agent.
|
583
|
+
|
584
|
+
${stepsToChangeAgent(suggested)}
|
585
|
+
`
|
586
|
+
|
587
|
+
return message
|
588
|
+
}
|
589
|
+
|
590
|
+
const stepsToChangeAgent = (agent: TAgent): string => {
|
591
|
+
if (agent === "vscode") {
|
592
|
+
return `
|
593
|
+
# Steps to Change Agent to VSCode
|
594
|
+
|
595
|
+
1. **Install VSCode**:
|
596
|
+
- Visit the [VSCode website](https://code.visualstudio.com/Download) and download the latest version.
|
597
|
+
- Follow the installation instructions for your operating system.
|
598
|
+
|
599
|
+
2. **Install LearnPack VSCode Extension**:
|
600
|
+
- Open VSCode.
|
601
|
+
- Go to the Extensions view by clicking on the Extensions icon in the Activity Bar on the side of the window or by pressing \`Ctrl+Shift+X\`.
|
602
|
+
- Search for "LearnPack" and click "Install".
|
603
|
+
- If the extension is already installed but disabled, enable it.
|
604
|
+
|
605
|
+
3. **Run LearnPack in VSCode**:
|
606
|
+
- Open your terminal in VSCode.
|
607
|
+
- Navigate to your LearnPack project directory.
|
608
|
+
- Run the following command:
|
609
|
+
\`\`\`sh
|
610
|
+
learnpack start
|
611
|
+
\`\`\`
|
612
|
+
|
613
|
+
We strongly recommend using VSCode for a better learning experience.
|
614
|
+
`
|
615
|
+
}
|
616
|
+
|
617
|
+
if (agent === "os") {
|
618
|
+
return `
|
619
|
+
# Steps to Change Agent to OS
|
620
|
+
|
621
|
+
This learning package was designed to run outside of VSCode. We strongly recommend closing VSCode and running the package independently.
|
622
|
+
|
623
|
+
1. **Close VSCode**:
|
624
|
+
- Save your work and close the VSCode application.
|
625
|
+
|
626
|
+
2. **Open a New Terminal**:
|
627
|
+
- Open a terminal or command prompt on your operating system.
|
628
|
+
|
629
|
+
3. **Navigate to Your LearnPack Project Directory**:
|
630
|
+
- Use the \`cd\` command to navigate to the directory where your LearnPack project is located.
|
631
|
+
|
632
|
+
4. **Run LearnPack**:
|
633
|
+
- Run the following command to start LearnPack:
|
634
|
+
\`\`\`sh
|
635
|
+
learnpack start
|
636
|
+
\`\`\`
|
637
|
+
|
638
|
+
We strongly recommend running the package independently for a better learning experience.
|
639
|
+
`
|
640
|
+
}
|
641
|
+
|
642
|
+
return ""
|
643
|
+
}
|
644
|
+
|
645
|
+
/**
|
646
|
+
* Checks if the 'code' command is available in the terminal.
|
647
|
+
*
|
648
|
+
* @returns {boolean} True if the 'code' command is available, false otherwise.
|
649
|
+
*/
|
650
|
+
const isCodeCommandAvailable = (): boolean => {
|
651
|
+
return shell.which("code") !== null
|
652
|
+
}
|
653
|
+
|
654
|
+
/**
|
655
|
+
* Checks if a specific VSCode extension is installed.
|
656
|
+
*
|
657
|
+
* @param {string} extensionName - The name of the extension to check.
|
658
|
+
* @returns {boolean} True if the extension is installed, false otherwise.
|
659
|
+
*/
|
660
|
+
const isExtensionInstalled = (extensionName: string): boolean => {
|
661
|
+
if (!isCodeCommandAvailable()) {
|
662
|
+
throw new Error(
|
663
|
+
"The 'code' command is not available in the terminal. Please ensure that VSCode is installed and the 'code' command is added to your PATH."
|
664
|
+
)
|
665
|
+
}
|
666
|
+
|
667
|
+
const result = shell.exec("code --list-extensions", { silent: true })
|
668
|
+
return result.stdout.split("\n").includes(extensionName)
|
669
|
+
}
|
670
|
+
|
671
|
+
const EXTENSION_INSTALLATION_STEPS = `
|
672
|
+
# Steps to Install LearnPack VSCode Extension
|
673
|
+
|
674
|
+
1. **Open VSCode**:
|
675
|
+
- Launch the Visual Studio Code application on your computer.
|
676
|
+
|
677
|
+
2. **Go to Extensions View**:
|
678
|
+
- Click on the Extensions icon in the Activity Bar on the side of the window.
|
679
|
+
- Alternatively, you can open the Extensions view by pressing \`Ctrl+Shift+X\`.
|
680
|
+
|
681
|
+
3. **Search for LearnPack**:
|
682
|
+
- In the Extensions view, type "LearnPack" into the search bar.
|
683
|
+
|
684
|
+
4. **Install the Extension**:
|
685
|
+
- Find the "LearnPack" extension in the search results and click the "Install" button.
|
686
|
+
- If the extension is already installed but disabled, click the "Enable" button.
|
687
|
+
|
688
|
+
5. **Verify Installation**:
|
689
|
+
- Once installed, you can verify the installation by running the following command in the terminal:
|
690
|
+
\`\`\`sh
|
691
|
+
code --list-extensions | grep learn-pack.learnpack-vscode
|
692
|
+
\`\`\`
|
693
|
+
- If the extension is listed, it means the installation was successful.
|
694
|
+
|
695
|
+
We strongly recommend using the LearnPack extension in VSCode for a better learning experience.
|
696
|
+
`
|
697
|
+
|
698
|
+
/**
|
699
|
+
* Installs the LearnPack VSCode extension if the 'code' command is available.
|
700
|
+
*
|
701
|
+
* @param {string} extensionName - The name of the extension to install.
|
702
|
+
* @returns {boolean} True if the installation was successful, false otherwise.
|
703
|
+
*/
|
704
|
+
const installExtension = (extensionName: string): boolean => {
|
705
|
+
if (!isCodeCommandAvailable()) {
|
706
|
+
throw new Error(
|
707
|
+
"The 'code' command is not available in the terminal. Please ensure that VSCode is installed and the 'code' command is added to your PATH."
|
708
|
+
)
|
709
|
+
}
|
710
|
+
|
711
|
+
const result = shell.exec(`code --install-extension ${extensionName}`, {
|
712
|
+
silent: true,
|
713
|
+
})
|
714
|
+
return result.code === 0
|
715
|
+
}
|