@learnpack/learnpack 2.1.57 → 4.0.0

Sign up to get free protection for your applications and to get access to all the features.
package/README.md CHANGED
@@ -21,7 +21,7 @@ $ npm install -g @learnpack/learnpack
21
21
  $ learnpack COMMAND
22
22
  running command...
23
23
  $ learnpack (-v|--version|version)
24
- @learnpack/learnpack/2.1.57 win32-x64 node-v20.10.0
24
+ @learnpack/learnpack/4.0.0 win32-x64 node-v20.10.0
25
25
  $ learnpack --help [COMMAND]
26
26
  USAGE
27
27
  $ learnpack COMMAND
@@ -74,7 +74,7 @@ DESCRIPTION
74
74
  12. If there is a file within the exercises folder but not inside of any particular exercise's folder. (Warning)
75
75
  ```
76
76
 
77
- _See code: [src\commands\audit.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.57/src\commands\audit.ts)_
77
+ _See code: [src\commands\audit.ts](https://github.com/learnpack/learnpack-cli/blob/v4.0.0/src\commands\audit.ts)_
78
78
 
79
79
  ## `learnpack clean`
80
80
 
@@ -89,7 +89,7 @@ DESCRIPTION
89
89
  Extra documentation goes here
90
90
  ```
91
91
 
92
- _See code: [src\commands\clean.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.57/src\commands\clean.ts)_
92
+ _See code: [src\commands\clean.ts](https://github.com/learnpack/learnpack-cli/blob/v4.0.0/src\commands\clean.ts)_
93
93
 
94
94
  ## `learnpack download [PACKAGE]`
95
95
 
@@ -107,7 +107,7 @@ DESCRIPTION
107
107
  Extra documentation goes here
108
108
  ```
109
109
 
110
- _See code: [src\commands\download.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.57/src\commands\download.ts)_
110
+ _See code: [src\commands\download.ts](https://github.com/learnpack/learnpack-cli/blob/v4.0.0/src\commands\download.ts)_
111
111
 
112
112
  ## `learnpack help [COMMAND]`
113
113
 
@@ -138,7 +138,7 @@ OPTIONS
138
138
  -h, --grading show CLI help
139
139
  ```
140
140
 
141
- _See code: [src\commands\init.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.57/src\commands\init.ts)_
141
+ _See code: [src\commands\init.ts](https://github.com/learnpack/learnpack-cli/blob/v4.0.0/src\commands\init.ts)_
142
142
 
143
143
  ## `learnpack login [PACKAGE]`
144
144
 
@@ -156,7 +156,7 @@ DESCRIPTION
156
156
  Extra documentation goes here
157
157
  ```
158
158
 
159
- _See code: [src\commands\login.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.57/src\commands\login.ts)_
159
+ _See code: [src\commands\login.ts](https://github.com/learnpack/learnpack-cli/blob/v4.0.0/src\commands\login.ts)_
160
160
 
161
161
  ## `learnpack logout [PACKAGE]`
162
162
 
@@ -174,7 +174,7 @@ DESCRIPTION
174
174
  Extra documentation goes here
175
175
  ```
176
176
 
177
- _See code: [src\commands\logout.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.57/src\commands\logout.ts)_
177
+ _See code: [src\commands\logout.ts](https://github.com/learnpack/learnpack-cli/blob/v4.0.0/src\commands\logout.ts)_
178
178
 
179
179
  ## `learnpack plugins`
180
180
 
@@ -309,7 +309,7 @@ DESCRIPTION
309
309
  Extra documentation goes here
310
310
  ```
311
311
 
312
- _See code: [src\commands\publish.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.57/src\commands\publish.ts)_
312
+ _See code: [src\commands\publish.ts](https://github.com/learnpack/learnpack-cli/blob/v4.0.0/src\commands\publish.ts)_
313
313
 
314
314
  ## `learnpack start`
315
315
 
@@ -330,7 +330,7 @@ OPTIONS
330
330
  -w, --watch Watch for file changes
331
331
  ```
332
332
 
333
- _See code: [src\commands\start.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.57/src\commands\start.ts)_
333
+ _See code: [src\commands\start.ts](https://github.com/learnpack/learnpack-cli/blob/v4.0.0/src\commands\start.ts)_
334
334
 
335
335
  ## `learnpack test [EXERCISESLUG]`
336
336
 
@@ -344,7 +344,7 @@ ARGUMENTS
344
344
  EXERCISESLUG The name of the exercise to test
345
345
  ```
346
346
 
347
- _See code: [src\commands\test.ts](https://github.com/learnpack/learnpack-cli/blob/v2.1.57/src\commands\test.ts)_
347
+ _See code: [src\commands\test.ts](https://github.com/learnpack/learnpack-cli/blob/v4.0.0/src\commands\test.ts)_
348
348
  <!-- commandsstop -->
349
349
 
350
350
  > > > > > > > 0cb3e56d84c197f9d008836bb573eade212b7e57
@@ -37,5 +37,6 @@ declare const _default: {
37
37
  exercises: never[];
38
38
  bugsLink: null;
39
39
  videoSolutions: boolean;
40
+ localhostOnly: boolean;
40
41
  };
41
42
  export default _default;
@@ -41,4 +41,5 @@ exports.default = {
41
41
  exercises: [],
42
42
  bugsLink: null,
43
43
  videoSolutions: false,
44
+ localhostOnly: false,
44
45
  };
@@ -145,12 +145,12 @@ exports.default = async ({ grading, mode, disableGrading, version, }) => {
145
145
  console_1.default.debug("Config version not found, downloading default.");
146
146
  const resp = await fetch("https://raw.githubusercontent.com/learnpack/ide/master/package.json");
147
147
  const packageJSON = await resp.json();
148
- configObj.config.editor.version = packageJSON.version || "3.1.23";
148
+ configObj.config.editor.version = packageJSON.version || "4.0.0";
149
149
  }
150
150
  configObj.config.dirPath = "./" + confPath.base;
151
151
  configObj.config.exercisesPath = getExercisesPath(confPath.base) || "./";
152
- const allowedCommands = new Set(["ls", "pwd", "echo", "node", "python"]);
153
152
  if (configObj.config.variables) {
153
+ const allowedCommands = new Set(["ls", "pwd", "echo", "node", "python"]);
154
154
  const variableKeys = Object.keys(configObj.config.variables);
155
155
  const promises = [];
156
156
  for (const v of variableKeys) {
@@ -28,22 +28,32 @@ exports.decompress = (sourcePath, destinationPath) => new Promise((resolve, reje
28
28
  });
29
29
  });
30
30
  exports.downloadEditor = async (version, destination) => {
31
- // https://raw.githubusercontent.com/learnpack/coding-ide/master/dist/app.tar.gz
32
- // if(versions[version] === undefined) throw new Error(`Invalid editor version ${version}`)
33
31
  if (!version) {
34
32
  const res = await fetch("https://raw.githubusercontent.com/learnpack/ide/master/package.json");
35
33
  const json = await res.json();
36
- version = json.version;
34
+ version = json.version || "4.0.0";
37
35
  if (!version)
38
36
  throw errors_1.InternalError(`Coding Editor version was not found on learnpack repository, check the config.editor.version property on learn.json`);
39
37
  }
40
- const versionNumber = parseInt(version.split(".")[0]);
41
- let url = `https://github.com/learnpack/coding-ide/blob/${version}/dist`;
38
+ const [major, minor] = version.split(".");
39
+ const versionPrefix = `${major}.${minor}`;
40
+ const tagsRes = await fetch("https://api.github.com/repos/learnpack/ide/contents/bin");
41
+ const tags = await tagsRes.json();
42
+ const matchingTags = tags
43
+ .filter((tag) => tag.name.includes(versionPrefix))
44
+ .sort((a, b) => b.name.localeCompare(a.name, undefined, { numeric: true }));
45
+ if (matchingTags.length === 0)
46
+ throw errors_1.InternalError(`No matching version found for prefix ${versionPrefix} in the learnpack repository`);
47
+ const latestVersion = matchingTags[0].name
48
+ .replace("learnpack-", "")
49
+ .replace(".tar.gz", "");
50
+ const versionNumber = parseInt(latestVersion.split(".")[0]);
51
+ let url = `https://github.com/learnpack/coding-ide/blob/${latestVersion}/dist`;
42
52
  if (versionNumber > 2)
43
- url = `https://github.com/learnpack/ide/blob/master/bin/learnpack-${version}.tar.gz`;
53
+ url = `https://github.com/learnpack/ide/blob/master/bin/learnpack-${latestVersion}.tar.gz`;
44
54
  const resp2 = await fetch(url, { method: "HEAD" });
45
55
  if (!resp2.ok)
46
- throw errors_1.InternalError(`Coding Editor ${version} was not found on learnpack repository, check the config.editor.version property on learn.json`);
56
+ throw errors_1.InternalError(`Coding Editor ${latestVersion} was not found on learnpack repository, check the config.editor.version property on learn.json`);
47
57
  console_1.default.info("Downloading the LearnPack coding UI, this may take a minute...");
48
58
  url += versionNumber > 2 ? `?raw=true` : `/app.tar.gz?raw=true`;
49
59
  return exports.download(url, destination);
@@ -1 +1 @@
1
- {"version":"2.1.57","commands":{"audit":{"id":"audit","description":"learnpack audit is the command in charge of creating an auditory of the repository\n...\nlearnpack audit checks for the following information in a repository:\n 1. The configuration object has slug, repository and description. (Error)\n 2. The command learnpack clean has been run. (Error)\n 3. If a markdown or test file doesn't have any content. (Error)\n 4. The links are accessing to valid servers. (Error)\n 5. The relative images are working (If they have the shortest path to the image or if the images exists in the assets). (Error)\n 6. The external images are working (If they are pointing to a valid server). (Error)\n 7. The exercises directory names are valid. (Error)\n 8. If an exercise doesn't have a README file. (Error)\n 9. The exercises array (Of the config file) has content. (Error)\n 10. The exercses have the same translations. (Warning)\n 11. The .gitignore file exists. (Warning)\n 12. If there is a file within the exercises folder but not inside of any particular exercise's folder. (Warning)\n","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[]},"clean":{"id":"clean","description":"Clean the configuration object\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[]},"download":{"id":"download","description":"Describe the command here\n...\nExtra documentation goes here\n","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"init":{"id":"init","description":"Create a new learning package: Book, Tutorial or Exercise","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{"grading":{"name":"grading","type":"boolean","char":"h","description":"show CLI help","allowNo":false}},"args":[]},"login":{"id":"login","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"logout":{"id":"logout","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"publish":{"id":"publish","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"start":{"id":"start","description":"Runs a small server with all the exercise instructions","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{"port":{"name":"port","type":"option","char":"p","description":"server port"},"host":{"name":"host","type":"option","char":"h","description":"server host"},"disableGrading":{"name":"disableGrading","type":"boolean","char":"D","description":"disble grading functionality","allowNo":false},"watch":{"name":"watch","type":"boolean","char":"w","description":"Watch for file changes","allowNo":false},"editor":{"name":"editor","type":"option","char":"e","description":"[preview, extension]","options":["extension","preview"]},"version":{"name":"version","type":"option","char":"v","description":"E.g: 1.0.1"},"grading":{"name":"grading","type":"option","char":"g","description":"[isolated, incremental]","options":["isolated","incremental"]},"debug":{"name":"debug","type":"boolean","char":"d","description":"debugger mode for more verbage","allowNo":false}},"args":[]},"test":{"id":"test","description":"Test exercises","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"exerciseSlug","description":"The name of the exercise to test","required":false,"hidden":false}]}}}
1
+ {"version":"4.0.0","commands":{"audit":{"id":"audit","description":"learnpack audit is the command in charge of creating an auditory of the repository\n...\nlearnpack audit checks for the following information in a repository:\n 1. The configuration object has slug, repository and description. (Error)\n 2. The command learnpack clean has been run. (Error)\n 3. If a markdown or test file doesn't have any content. (Error)\n 4. The links are accessing to valid servers. (Error)\n 5. The relative images are working (If they have the shortest path to the image or if the images exists in the assets). (Error)\n 6. The external images are working (If they are pointing to a valid server). (Error)\n 7. The exercises directory names are valid. (Error)\n 8. If an exercise doesn't have a README file. (Error)\n 9. The exercises array (Of the config file) has content. (Error)\n 10. The exercses have the same translations. (Warning)\n 11. The .gitignore file exists. (Warning)\n 12. If there is a file within the exercises folder but not inside of any particular exercise's folder. (Warning)\n","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[]},"clean":{"id":"clean","description":"Clean the configuration object\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[]},"download":{"id":"download","description":"Describe the command here\n...\nExtra documentation goes here\n","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"init":{"id":"init","description":"Create a new learning package: Book, Tutorial or Exercise","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{"grading":{"name":"grading","type":"boolean","char":"h","description":"show CLI help","allowNo":false}},"args":[]},"login":{"id":"login","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"logout":{"id":"logout","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"publish":{"id":"publish","description":"Describe the command here\n ...\n Extra documentation goes here\n ","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"package","description":"The unique string that identifies this package on learnpack","required":false,"hidden":false}]},"start":{"id":"start","description":"Runs a small server with all the exercise instructions","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{"port":{"name":"port","type":"option","char":"p","description":"server port"},"host":{"name":"host","type":"option","char":"h","description":"server host"},"disableGrading":{"name":"disableGrading","type":"boolean","char":"D","description":"disble grading functionality","allowNo":false},"watch":{"name":"watch","type":"boolean","char":"w","description":"Watch for file changes","allowNo":false},"editor":{"name":"editor","type":"option","char":"e","description":"[preview, extension]","options":["extension","preview"]},"version":{"name":"version","type":"option","char":"v","description":"E.g: 1.0.1"},"grading":{"name":"grading","type":"option","char":"g","description":"[isolated, incremental]","options":["isolated","incremental"]},"debug":{"name":"debug","type":"boolean","char":"d","description":"debugger mode for more verbage","allowNo":false}},"args":[]},"test":{"id":"test","description":"Test exercises","pluginName":"@learnpack/learnpack","pluginType":"core","aliases":[],"flags":{},"args":[{"name":"exerciseSlug","description":"The name of the exercise to test","required":false,"hidden":false}]}}}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@learnpack/learnpack",
3
3
  "description": "Create, sell or download and take learning amazing learning packages",
4
- "version": "2.1.57",
4
+ "version": "4.0.0",
5
5
  "author": "Alejandro Sanchez @alesanchezr",
6
6
  "contributors": [
7
7
  {
@@ -39,4 +39,5 @@ export default {
39
39
  exercises: [],
40
40
  bugsLink: null,
41
41
  videoSolutions: false,
42
+ localhostOnly: false, // if true, the exercise should not run on gitpod or codespaces but show an error message encouraging the user to run locally
42
43
  }
@@ -28,9 +28,9 @@ import { IFile } from "../../models/file"
28
28
  /* exercise folder name standard */
29
29
 
30
30
  // eslint-disable-next-line
31
- const fetch = require("node-fetch");
31
+ const fetch = require("node-fetch")
32
32
  // eslint-disable-next-line
33
- const chalk = require("chalk");
33
+ const chalk = require("chalk")
34
34
 
35
35
  /* exercise folder name standard */
36
36
 
@@ -206,15 +206,15 @@ configObj.config.editor.version = version
206
206
  "https://raw.githubusercontent.com/learnpack/ide/master/package.json"
207
207
  )
208
208
  const packageJSON = await resp.json()
209
- configObj.config.editor.version = packageJSON.version || "3.1.23"
209
+ configObj.config.editor.version = packageJSON.version || "4.0.0"
210
210
  }
211
211
 
212
212
  configObj.config.dirPath = "./" + confPath.base
213
213
  configObj.config.exercisesPath = getExercisesPath(confPath.base) || "./"
214
214
 
215
- const allowedCommands = new Set(["ls", "pwd", "echo", "node", "python"])
216
-
217
215
  if (configObj.config.variables) {
216
+ const allowedCommands = new Set(["ls", "pwd", "echo", "node", "python"])
217
+
218
218
  const variableKeys = Object.keys(configObj.config.variables)
219
219
  const promises = []
220
220
 
@@ -384,9 +384,7 @@ fs.unlinkSync(_path)
384
384
  ex => ex.slug === slug
385
385
  )
386
386
  if (!exercise)
387
- throw ValidationError(
388
- `Exercise ${slug} not found on the configuration`
389
- )
387
+ throw ValidationError(`Exercise ${slug} not found on the configuration`)
390
388
 
391
389
  if (configObj.config) {
392
390
  for (const fileName of fs.readdirSync(
@@ -1,196 +1,212 @@
1
- import * as fs from "fs"
2
- import * as p from "path"
3
- import * as shell from "shelljs"
4
- import { cli } from "cli-ux"
5
- import * as targz from "targz"
6
- import Console from "../utils/console"
7
- import * as https from "https"
8
- import { InternalError } from "../utils/errors"
9
-
10
- // eslint-disable-next-line
11
- const fetch = require("node-fetch");
12
-
13
- export const decompress = (sourcePath: string, destinationPath: string) =>
14
- new Promise((resolve, reject) => {
15
- Console.debug("Decompressing " + sourcePath)
16
- targz.decompress(
17
- {
18
- src: sourcePath,
19
- dest: destinationPath,
20
- },
21
- function (err: string | Error | null) {
22
- if (err) {
23
- Console.error("Error when trying to decompress")
24
- reject(err)
25
- } else {
26
- Console.info("Decompression finished successfully")
27
- resolve(/* */ "")
28
- }
29
- }
30
- )
31
- })
32
-
33
- export const downloadEditor = async (
34
- version: string | undefined,
35
- destination: string
36
- ) => {
37
- // https://raw.githubusercontent.com/learnpack/coding-ide/master/dist/app.tar.gz
38
- // if(versions[version] === undefined) throw new Error(`Invalid editor version ${version}`)
39
-
40
- if (!version) {
41
- const res = await fetch(
42
- "https://raw.githubusercontent.com/learnpack/ide/master/package.json"
43
- )
44
- const json = await res.json()
45
- version = json.version
46
-
47
- if (!version)
48
- throw InternalError(
49
- `Coding Editor version was not found on learnpack repository, check the config.editor.version property on learn.json`
50
- )
51
- }
52
-
53
- const versionNumber = parseInt(version.split(".")[0])
54
-
55
- let url = `https://github.com/learnpack/coding-ide/blob/${version}/dist`
56
-
57
- if (versionNumber > 2)
58
- url = `https://github.com/learnpack/ide/blob/master/bin/learnpack-${version}.tar.gz`
59
-
60
- const resp2 = await fetch(url, { method: "HEAD" })
61
- if (!resp2.ok)
62
- throw InternalError(
63
- `Coding Editor ${version} was not found on learnpack repository, check the config.editor.version property on learn.json`
64
- )
65
-
66
- Console.info(
67
- "Downloading the LearnPack coding UI, this may take a minute..."
68
- )
69
-
70
- url += versionNumber > 2 ? `?raw=true` : `/app.tar.gz?raw=true`
71
-
72
- return download(url, destination)
73
- }
74
-
75
- export const download = (url: string, dest: string) => {
76
- Console.debug("Downloading " + url)
77
- return new Promise((resolve, reject) => {
78
- const request = https.get(url, response => {
79
- if (response.statusCode === 200) {
80
- const file = fs.createWriteStream(dest, { flags: "wx" })
81
- file.on("finish", () => {
82
- resolve(true)
83
- })
84
- file.on("error", err => {
85
- file.close()
86
- if (err.code === "EEXIST") {
87
- Console.debug("File already exists")
88
- resolve("File already exists")
89
- } else {
90
- Console.debug("Error ", err.message)
91
- fs.unlink(dest, () => reject(err.message)) // Delete temp file
92
- }
93
- })
94
- response.pipe(file)
95
- } else if (response.statusCode === 302 || response.statusCode === 301) {
96
- // Console.debug("Servers redirected to "+response.headers.location)
97
- // Recursively follow redirects, only a 200 will resolve.
98
- if (response.headers.location) {
99
- download(response.headers.location, dest)
100
- .then(() => resolve(/* */ ""))
101
- .catch(error => {
102
- Console.error(error)
103
- reject(error)
104
- })
105
- }
106
- } else {
107
- Console.debug(
108
- `Server responded with ${response.statusCode}: ${response.statusMessage}`
109
- )
110
- reject(
111
- `Server responded with ${response.statusCode}: ${response.statusMessage}`
112
- )
113
- }
114
- })
115
-
116
- request.on("error", err => {
117
- reject(err.message)
118
- })
119
- })
120
- }
121
-
122
- export const clone = (repository = "", folder = "./") =>
123
- new Promise((resolve, reject) => {
124
- if (!repository) {
125
- reject("Missing repository url for this package")
126
- // return false
127
- }
128
-
129
- cli.action.start("Verifying GIT...")
130
- if (!shell.which("git")) {
131
- reject("Sorry, this script requires git")
132
- // return false
133
- }
134
-
135
- cli.action.stop()
136
-
137
- let fileName = p.basename(repository)
138
- if (!fileName) {
139
- reject("Invalid repository information on package: " + repository)
140
- // return false
141
- }
142
-
143
- fileName = fileName.split(".")[0]
144
- if (fs.existsSync("./" + fileName)) {
145
- reject(
146
- `Directory ${fileName} already exists; Did you download this package already?`
147
- )
148
- // return false
149
- }
150
-
151
- cli.action.start(`Cloning repository ${repository}...`)
152
- if (shell.exec(`git clone ${repository}`).code !== 0) {
153
- reject("Error: Installation failed")
154
- }
155
-
156
- cli.action.stop()
157
-
158
- cli.action.start("Cleaning installation...")
159
- if (shell.exec(`rm -R -f ${folder}${fileName}/.git`).code !== 0) {
160
- reject("Error: removing .git directory")
161
- }
162
-
163
- cli.action.stop()
164
-
165
- resolve("Done")
166
- })
167
-
168
- export const rmSync = function (path: string) {
169
- let files = []
170
- if (fs.existsSync(path)) {
171
- files = fs.readdirSync(path)
172
- for (const [, file] of files.entries()) {
173
- const curPath = path + "/" + file
174
- if (fs.lstatSync(curPath).isDirectory()) {
175
- // recurse
176
- rmSync(curPath)
177
- } else {
178
- // delete file
179
- fs.unlinkSync(curPath)
180
- }
181
- }
182
-
183
- fs.rmdirSync(path)
184
- }
185
- }
186
-
187
- export const checkIfDirectoryExists = (path: string) => {
188
- const fs = require("fs")
189
- if (fs.existsSync(path)) {
190
- return true
191
- }
192
-
193
- return false
194
- }
195
-
196
- export default { download, decompress, downloadEditor, clone, rmSync }
1
+ import * as fs from "fs"
2
+ import * as p from "path"
3
+ import * as shell from "shelljs"
4
+ import { cli } from "cli-ux"
5
+ import * as targz from "targz"
6
+ import Console from "../utils/console"
7
+ import * as https from "https"
8
+ import { InternalError } from "../utils/errors"
9
+
10
+ // eslint-disable-next-line
11
+ const fetch = require("node-fetch")
12
+
13
+ export const decompress = (sourcePath: string, destinationPath: string) =>
14
+ new Promise((resolve, reject) => {
15
+ Console.debug("Decompressing " + sourcePath)
16
+ targz.decompress(
17
+ {
18
+ src: sourcePath,
19
+ dest: destinationPath,
20
+ },
21
+ function (err: string | Error | null) {
22
+ if (err) {
23
+ Console.error("Error when trying to decompress")
24
+ reject(err)
25
+ } else {
26
+ Console.info("Decompression finished successfully")
27
+ resolve(/* */ "")
28
+ }
29
+ }
30
+ )
31
+ })
32
+
33
+ export const downloadEditor = async (
34
+ version: string | undefined,
35
+ destination: string
36
+ ) => {
37
+ if (!version) {
38
+ const res = await fetch(
39
+ "https://raw.githubusercontent.com/learnpack/ide/master/package.json"
40
+ )
41
+ const json = await res.json()
42
+ version = json.version || "4.0.0"
43
+
44
+ if (!version)
45
+ throw InternalError(
46
+ `Coding Editor version was not found on learnpack repository, check the config.editor.version property on learn.json`
47
+ )
48
+ }
49
+
50
+ const [major, minor] = version.split(".")
51
+ const versionPrefix = `${major}.${minor}`
52
+
53
+ const tagsRes = await fetch(
54
+ "https://api.github.com/repos/learnpack/ide/contents/bin"
55
+ )
56
+ const tags = await tagsRes.json()
57
+ const matchingTags = tags
58
+ .filter((tag: any) => tag.name.includes(versionPrefix))
59
+ .sort((a: any, b: any) =>
60
+ b.name.localeCompare(a.name, undefined, { numeric: true })
61
+ )
62
+
63
+ if (matchingTags.length === 0)
64
+ throw InternalError(
65
+ `No matching version found for prefix ${versionPrefix} in the learnpack repository`
66
+ )
67
+
68
+ const latestVersion = matchingTags[0].name
69
+ .replace("learnpack-", "")
70
+ .replace(".tar.gz", "")
71
+ const versionNumber = parseInt(latestVersion.split(".")[0])
72
+
73
+ let url = `https://github.com/learnpack/coding-ide/blob/${latestVersion}/dist`
74
+
75
+ if (versionNumber > 2)
76
+ url = `https://github.com/learnpack/ide/blob/master/bin/learnpack-${latestVersion}.tar.gz`
77
+
78
+ const resp2 = await fetch(url, { method: "HEAD" })
79
+ if (!resp2.ok)
80
+ throw InternalError(
81
+ `Coding Editor ${latestVersion} was not found on learnpack repository, check the config.editor.version property on learn.json`
82
+ )
83
+
84
+ Console.info("Downloading the LearnPack coding UI, this may take a minute...")
85
+
86
+ url += versionNumber > 2 ? `?raw=true` : `/app.tar.gz?raw=true`
87
+
88
+ return download(url, destination)
89
+ }
90
+
91
+ export const download = (url: string, dest: string) => {
92
+ Console.debug("Downloading " + url)
93
+ return new Promise((resolve, reject) => {
94
+ const request = https.get(url, response => {
95
+ if (response.statusCode === 200) {
96
+ const file = fs.createWriteStream(dest, { flags: "wx" })
97
+ file.on("finish", () => {
98
+ resolve(true)
99
+ })
100
+ file.on("error", err => {
101
+ file.close()
102
+ if (err.code === "EEXIST") {
103
+ Console.debug("File already exists")
104
+ resolve("File already exists")
105
+ } else {
106
+ Console.debug("Error ", err.message)
107
+ fs.unlink(dest, () => reject(err.message)) // Delete temp file
108
+ }
109
+ })
110
+ response.pipe(file)
111
+ } else if (response.statusCode === 302 || response.statusCode === 301) {
112
+ // Console.debug("Servers redirected to "+response.headers.location)
113
+ // Recursively follow redirects, only a 200 will resolve.
114
+ if (response.headers.location) {
115
+ download(response.headers.location, dest)
116
+ .then(() => resolve(/* */ ""))
117
+ .catch(error => {
118
+ Console.error(error)
119
+ reject(error)
120
+ })
121
+ }
122
+ } else {
123
+ Console.debug(
124
+ `Server responded with ${response.statusCode}: ${response.statusMessage}`
125
+ )
126
+ reject(
127
+ `Server responded with ${response.statusCode}: ${response.statusMessage}`
128
+ )
129
+ }
130
+ })
131
+
132
+ request.on("error", err => {
133
+ reject(err.message)
134
+ })
135
+ })
136
+ }
137
+
138
+ export const clone = (repository = "", folder = "./") =>
139
+ new Promise((resolve, reject) => {
140
+ if (!repository) {
141
+ reject("Missing repository url for this package")
142
+ // return false
143
+ }
144
+
145
+ cli.action.start("Verifying GIT...")
146
+ if (!shell.which("git")) {
147
+ reject("Sorry, this script requires git")
148
+ // return false
149
+ }
150
+
151
+ cli.action.stop()
152
+
153
+ let fileName = p.basename(repository)
154
+ if (!fileName) {
155
+ reject("Invalid repository information on package: " + repository)
156
+ // return false
157
+ }
158
+
159
+ fileName = fileName.split(".")[0]
160
+ if (fs.existsSync("./" + fileName)) {
161
+ reject(
162
+ `Directory ${fileName} already exists; Did you download this package already?`
163
+ )
164
+ // return false
165
+ }
166
+
167
+ cli.action.start(`Cloning repository ${repository}...`)
168
+ if (shell.exec(`git clone ${repository}`).code !== 0) {
169
+ reject("Error: Installation failed")
170
+ }
171
+
172
+ cli.action.stop()
173
+
174
+ cli.action.start("Cleaning installation...")
175
+ if (shell.exec(`rm -R -f ${folder}${fileName}/.git`).code !== 0) {
176
+ reject("Error: removing .git directory")
177
+ }
178
+
179
+ cli.action.stop()
180
+
181
+ resolve("Done")
182
+ })
183
+
184
+ export const rmSync = function (path: string) {
185
+ let files = []
186
+ if (fs.existsSync(path)) {
187
+ files = fs.readdirSync(path)
188
+ for (const [, file] of files.entries()) {
189
+ const curPath = path + "/" + file
190
+ if (fs.lstatSync(curPath).isDirectory()) {
191
+ // recurse
192
+ rmSync(curPath)
193
+ } else {
194
+ // delete file
195
+ fs.unlinkSync(curPath)
196
+ }
197
+ }
198
+
199
+ fs.rmdirSync(path)
200
+ }
201
+ }
202
+
203
+ export const checkIfDirectoryExists = (path: string) => {
204
+ const fs = require("fs")
205
+ if (fs.existsSync(path)) {
206
+ return true
207
+ }
208
+
209
+ return false
210
+ }
211
+
212
+ export default { download, decompress, downloadEditor, clone, rmSync }