mushroom-cli 1.1.0-alpha.2 → 1.1.0-alpha.20

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.
@@ -3,6 +3,7 @@ const path = require('path');
3
3
  var targz = require('targz');
4
4
  const javascriptDriverGenerator = require("./gen-js-driver");
5
5
  const typescriptDriverGenerator = require("./gen-ts-driver");
6
+ const package = require("./../package.json");
6
7
 
7
8
  function compressAsync(src, dest, folderName) {
8
9
  return new Promise((resolve, reject) => {
@@ -37,9 +38,18 @@ async function genJavascriptDriverTarball(args, projectName, project, alias, sou
37
38
  tarballName = tarballName.toLowerCase().replace(/[^a-z-]/g, "-");
38
39
 
39
40
  const dirPath = path.join(path.dirname(aliasProject.output), tarballName);
40
- //const mainFileName = path.basename(aliasProject.output);
41
- //const dtsFileName = mainFileName.replace(/\.js$/i, ".d.ts");
42
41
 
42
+ const versionGroup = package.version.match(/([^-]+)(-(\w+).*)?/);
43
+ const currentDistTag = versionGroup[3] ? versionGroup[3] : "latest";
44
+
45
+ const dependencies = [`"mushroomjs": "${currentDistTag}"`];
46
+ if (Array.isArray(aliasProject.features) && aliasProject.features.includes("auth")) {
47
+ dependencies.push(`"mushroomjs-auth": "${currentDistTag}"`);
48
+ }
49
+ if (Array.isArray(aliasProject.features) && aliasProject.features.includes("file")) {
50
+ dependencies.push(`"mushroomjs-file": "${currentDistTag}"`);
51
+ }
52
+
43
53
  const packageContent = `{
44
54
  "version": "1.0.${new Date().getTime()}",
45
55
  "name": "${tarballName}",
@@ -47,7 +57,7 @@ async function genJavascriptDriverTarball(args, projectName, project, alias, sou
47
57
  "main": "${tarballName}.js",
48
58
  "types": "${tarballName}.d.ts",
49
59
  "dependencies": {
50
- "mushroomjs": "^1.1.0-alpha.5"${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? ',\n "mushroomjs-auth": "^1.1.0-alpha.4"' : ""}${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? ',\n "mushroomjs-file": "^1.1.0-alpha.1"' : ""}
60
+ ${dependencies.join(',\n ')}
51
61
  }
52
62
  }`;
53
63
 
@@ -30,9 +30,40 @@ function genJavascriptDriverString(aliasProject, source) {
30
30
 
31
31
  const entities = common.getEntities(source, aliasProject.allowRoles);
32
32
 
33
- let code = `import mushroom, {defineAsyncResource} from "mushroomjs";
34
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? 'import { useAuth, AuthLocalStorage } from "mushroomjs-auth";' : ""}
35
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? 'import { useFile } from "mushroomjs-file";' : ""}
33
+ let extensionsImportLines = [];
34
+ let extensionsExportLines = [];
35
+ let extensionsCodeLines = [];
36
+
37
+ if (Array.isArray(aliasProject.features)) {
38
+ if (aliasProject.features.includes("auth")) {
39
+ extensionsImportLines.push('//import * as AuthExtension from "mushroomjs-auth";');
40
+ extensionsImportLines.push('var AuthExtension = require("mushroomjs-auth");');
41
+ extensionsExportLines.push('Auth: AuthExtension');
42
+ extensionsCodeLines.push("AuthExtension.useAuth(AuthExtension.AuthLocalStorage);");
43
+ }
44
+ if (aliasProject.features.includes("file")) {
45
+ extensionsImportLines.push('//import * as FileExtension from "mushroomjs-file";');
46
+ extensionsImportLines.push('var FileExtension = require("mushroomjs-file");');
47
+ extensionsExportLines.push('File: FileExtension');
48
+ extensionsCodeLines.push("FileExtension.useFile();");
49
+ }
50
+ }
51
+
52
+ let code = `//import mushroom, {defineAsyncResource} from "mushroomjs";
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ var mushroom_1 = require("mushroomjs");
55
+ var mushroom = mushroom_1.default;
56
+ var defineAsyncResource = mushroom_1.defineAsyncResource;
57
+
58
+ //export * from "mushroomjs";
59
+ for (var m in mushroom_1) exports[m] = mushroom_1[m];
60
+
61
+ ${extensionsImportLines.join("\n")}
62
+ //export const extensions = {
63
+ var extensions = {
64
+ ${extensionsExportLines.join(",\n ")}
65
+ };
66
+ exports.extensions = extensions;
36
67
 
37
68
  "use strict";
38
69
 
@@ -66,10 +97,10 @@ ${Array.isArray(aliasProject.features) && aliasProject.features.includes("file")
66
97
  code += `
67
98
  mushroom.$using(${JSON.stringify(common.getRootUrl(source))});
68
99
 
69
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "useAuth(AuthLocalStorage);" : ""}
70
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "useFile();" : ""}
100
+ ${extensionsCodeLines.join('\n')}
71
101
 
72
- export default mushroom;`;
102
+ //export default mushroom;
103
+ exports.default = mushroom;`;
73
104
 
74
105
  return code;
75
106
  }
@@ -38,7 +38,7 @@ function toTypeScriptClassName(str) {
38
38
  return "_";
39
39
  const name = toVietnameseNonTongue(str).replace(/\W/g, "_");
40
40
  const c = name.charAt(0);
41
- return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substr(1);
41
+ return ('0' <= c && c <= '9' ? '_' : "") + c.toUpperCase() + name.substring(1);
42
42
  }
43
43
 
44
44
  function getCSharpTypeFromMushroomType(type) {
@@ -104,9 +104,32 @@ function genTypescriptDriverString(aliasProject, source) {
104
104
 
105
105
  const entities = common.getEntities(source, aliasProject.allowRoles);
106
106
 
107
+ let extensionsImportLines = [];
108
+ let extensionsExportLines = [];
109
+ let extensionsTypes = [];
110
+ let extensionsCodeLines = [];
111
+
112
+ if (Array.isArray(aliasProject.features)) {
113
+ if (aliasProject.features.includes("auth")) {
114
+ extensionsImportLines.push('import * as AuthExtension from "mushroomjs-auth";');
115
+ extensionsExportLines.push('File: FileExtension');
116
+ extensionsTypes.push("AuthExtension.IMushroomAuth & ");
117
+ extensionsCodeLines.push("AuthExtension.useAuth(AuthExtension.AuthLocalStorage);");
118
+ }
119
+ if (aliasProject.features.includes("file")) {
120
+ extensionsImportLines.push('import * as FileExtension from "mushroomjs-file";');
121
+ extensionsExportLines.push('Auth: AuthExtension');
122
+ extensionsTypes.push("FileExtension.IMushroomFile & ");
123
+ extensionsCodeLines.push("FileExtension.useFile();");
124
+ }
125
+ }
126
+
107
127
  let code = `import mushroom, { defineAsyncResource, defineAsyncView, fireEvent, createRestfulAsyncFunction, IdType, IMushroom, Mushroom, MushroomRequest, MushroomRequestSetting, MushroomRestfulRequest, MushroomResponse, MushroomResourceBase, MushroomListResource, MushroomFindByIdResource, MushroomCreateResource, MushroomBatchCreateResource, MushroomUpdateResource, MushroomBatchUpdateResource, MushroomPartialUpdateResource, MushroomDeleteResource, MushroomBatchDeleteResource, MushroomExtensibleResource, MushroomViewFunction, MushroomError } from "mushroomjs";
108
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? 'import { IMushroomAuth, useAuth, AuthLocalStorage } from "mushroomjs-auth";' : ""}
109
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? 'import { IMushroomFile, useFile } from "mushroomjs-file";' : ""}
128
+ ${extensionsImportLines.join("\n")}
129
+ export * from "mushroomjs";
130
+ export const extensions = {
131
+ ${extensionsExportLines.join(",\n ")}
132
+ };
110
133
 
111
134
  export type ISODateValue = string | Date;
112
135
  export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoIncLong" ? "number" : "string"};
@@ -119,7 +142,7 @@ export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoI
119
142
 
120
143
  const entity = entities[entityName];
121
144
  const typescriptClassName = toTypeScriptClassName(entityName);
122
- code += `interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
145
+ code += `export interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
123
146
  `;
124
147
 
125
148
 
@@ -173,7 +196,7 @@ export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoI
173
196
  }
174
197
  default: {
175
198
  if (actionName.indexOf("_raw_http_method_") === 0) {
176
- customMethodCode += ` ${actionName.substr("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
199
+ customMethodCode += ` ${actionName.substring("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
177
200
  `;
178
201
  break;
179
202
  }
@@ -186,7 +209,7 @@ export type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoI
186
209
  }
187
210
 
188
211
  if (customMethodCode) {
189
- code += `interface ${typescriptClassName}$CustomMethodResource {
212
+ code += `export interface ${typescriptClassName}$CustomMethodResource {
190
213
  ${customMethodCode}}
191
214
  `;
192
215
  iApiClassBody += ` & ${typescriptClassName}$CustomMethodResource`;
@@ -204,7 +227,7 @@ ${customMethodCode}}
204
227
 
205
228
  const viewParameterTypes = viewRoles.map(view => {
206
229
  const type = `${typescriptClassName}$ViewsResource_${viewName}View_${view.grant === "*" ? "" : toTypeScriptClassName(view.grant)}Parameters`;
207
- code += `interface ${type} ${generateTypescriptClassFromViewParameters(view.parameters)};
230
+ code += `export interface ${type} ${generateTypescriptClassFromViewParameters(view.parameters)};
208
231
  `;
209
232
  return `MushroomViewFunction<any, ${type}>`;
210
233
  });
@@ -213,7 +236,7 @@ ${customMethodCode}}
213
236
  }
214
237
 
215
238
  if (viewCode) {
216
- code += `interface ${typescriptClassName}$ViewsResource {
239
+ code += `export interface ${typescriptClassName}$ViewsResource {
217
240
  views: {${viewCode}
218
241
  }
219
242
  }
@@ -230,14 +253,16 @@ ${customMethodCode}}
230
253
  }
231
254
 
232
255
  code += `
233
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "useAuth(AuthLocalStorage);" : ""}
234
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "useFile();" : ""}
235
256
  mushroom.$using(${JSON.stringify(common.getRootUrl(source))});
236
257
 
237
- interface IApi extends IMushroom {
258
+ (function(){
259
+ ${extensionsCodeLines.join('\n')}
260
+ })();
261
+
262
+ export interface IApi extends IMushroom {
238
263
  ${iApiClassBody}};
239
264
 
240
- type Api = ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "IMushroomAuth & " : ""}${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? "IMushroomFile & " : ""}IApi;
265
+ export type Api = ${extensionsTypes.join('')}IApi;
241
266
 
242
267
  export default mushroom as Api;`;
243
268
 
@@ -251,9 +276,29 @@ function genDtsString(aliasProject, source) {
251
276
 
252
277
  const entities = common.getEntities(source, aliasProject.allowRoles);
253
278
 
279
+ let extensionsImportLines = [];
280
+ let extensionsExportLines = [];
281
+ let extensionsTypes = [];
282
+
283
+ if (Array.isArray(aliasProject.features)) {
284
+ if (aliasProject.features.includes("auth")) {
285
+ extensionsImportLines.push('import * as AuthExtension from "mushroomjs-auth";');
286
+ extensionsExportLines.push('Auth: AuthExtension');
287
+ extensionsTypes.push("AuthExtension.IMushroomAuth & ");
288
+ }
289
+ if (aliasProject.features.includes("file")) {
290
+ extensionsImportLines.push('import * as FileExtension from "mushroomjs-file";');
291
+ extensionsExportLines.push('File: FileExtension');
292
+ extensionsTypes.push("FileExtension.IMushroomFile & ");
293
+ }
294
+ }
295
+
254
296
  let code = `import { IdType, IMushroom, Mushroom, MushroomRequest, MushroomRequestSetting, MushroomRestfulRequest, MushroomResponse, MushroomResourceBase, MushroomListResource, MushroomFindByIdResource, MushroomCreateResource, MushroomBatchCreateResource, MushroomUpdateResource, MushroomBatchUpdateResource, MushroomPartialUpdateResource, MushroomDeleteResource, MushroomBatchDeleteResource, MushroomExtensibleResource, MushroomViewFunction, MushroomError } from "mushroomjs";
255
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? 'import { IMushroomAuth } from "mushroomjs-auth";' : ""}
256
- ${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? 'import { IMushroomFile } from "mushroomjs-file";' : ""}
297
+ ${extensionsImportLines.join("\n")}
298
+ export * from "mushroomjs";
299
+ export declare const extensions = {
300
+ ${extensionsExportLines.join(",\n ")}
301
+ };
257
302
 
258
303
  export declare type ISODateValue = string | Date;
259
304
  export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType == "AutoIncLong" ? "number" : "string"};
@@ -266,7 +311,7 @@ export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType =
266
311
 
267
312
  const entity = entities[entityName];
268
313
  const typescriptClassName = toTypeScriptClassName(entityName);
269
- code += `interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
314
+ code += `export interface ${typescriptClassName} ${generateTypescriptClass(entity.fields)};
270
315
  `;
271
316
 
272
317
 
@@ -320,7 +365,7 @@ export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType =
320
365
  }
321
366
  default: {
322
367
  if (actionName.indexOf("_raw_http_method_") === 0) {
323
- customMethodCode += ` ${actionName.substr("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
368
+ customMethodCode += ` ${actionName.substring("_raw_http_method_".length)}Async: (rawRequest: MushroomRequest) => Promise<MushroomResponse<any>>,
324
369
  `;
325
370
  break;
326
371
  }
@@ -333,7 +378,7 @@ export declare type IdValue = ${source.idType == "AutoIncInt" || source.idType =
333
378
  }
334
379
 
335
380
  if (customMethodCode) {
336
- code += `interface ${typescriptClassName}$CustomMethodResource {
381
+ code += `export interface ${typescriptClassName}$CustomMethodResource {
337
382
  ${customMethodCode}}
338
383
  `;
339
384
  iApiClassBody += ` & ${typescriptClassName}$CustomMethodResource`;
@@ -351,7 +396,7 @@ ${customMethodCode}}
351
396
 
352
397
  const viewParameterTypes = viewRoles.map(view => {
353
398
  const type = `${typescriptClassName}$ViewsResource_${viewName}View_${view.grant === "*" ? "" : toTypeScriptClassName(view.grant)}Parameters`;
354
- code += `interface ${type} ${generateTypescriptClassFromViewParameters(view.parameters)};
399
+ code += `export interface ${type} ${generateTypescriptClassFromViewParameters(view.parameters)};
355
400
  `;
356
401
  return `MushroomViewFunction<any, ${type}>`;
357
402
  });
@@ -360,7 +405,7 @@ ${customMethodCode}}
360
405
  }
361
406
 
362
407
  if (viewCode) {
363
- code += `interface ${typescriptClassName}$ViewsResource {
408
+ code += `export interface ${typescriptClassName}$ViewsResource {
364
409
  views: {${viewCode}
365
410
  }
366
411
  }
@@ -373,10 +418,10 @@ ${customMethodCode}}
373
418
  }
374
419
 
375
420
  code += `
376
- interface IApi extends IMushroom {
421
+ export interface IApi extends IMushroom {
377
422
  ${iApiClassBody}};
378
423
 
379
- declare type Api = ${Array.isArray(aliasProject.features) && aliasProject.features.includes("auth") ? "IMushroomAuth & " : ""}${Array.isArray(aliasProject.features) && aliasProject.features.includes("file") ? "IMushroomFile & " : ""}IApi;
424
+ declare type Api = ${extensionsTypes.join('')}IApi;
380
425
  declare const _default: Api;
381
426
  export default _default;`;
382
427
 
package/gen.js CHANGED
@@ -24,8 +24,8 @@ async function gen(args) {
24
24
 
25
25
  const atIndex = projectName.indexOf("@");
26
26
  if (atIndex !== -1) {
27
- alias = projectName.substr(atIndex + 1);
28
- projectName = projectName.substr(0, atIndex);
27
+ alias = projectName.substring(atIndex + 1);
28
+ projectName = projectName.substring(0, atIndex);
29
29
  if (!projectName) {
30
30
  help(args);
31
31
  return;
package/help.js CHANGED
@@ -13,7 +13,7 @@ function help(key, wrong) {
13
13
  npx mr init json ./api/SampleProject.json [silent]
14
14
 
15
15
  Init a dotnet core project which pre-install Mushroom Server
16
- npx mr init netcore projectName [features file,auth,mail]
16
+ npx mr init netcore
17
17
 
18
18
  Add the mushroom json file into mushroom-config.json
19
19
  npx mr config add ./api/yourProjectName.json
@@ -0,0 +1,106 @@
1
+ const fs = require("fs");
2
+ const fetch = require('node-fetch');
3
+ const readlineSync = require("readline-sync");
4
+ const help = require("../help.js");
5
+ const common = require("../common.js");
6
+
7
+ function initJson(args) {
8
+ const path = args[2];
9
+ if (!path) {
10
+ help(args);
11
+ return;
12
+ }
13
+
14
+ if (fs.existsSync(path)){
15
+ console.error(`File ${path} is already existed`);
16
+ return;
17
+ }
18
+
19
+ if (args[3] === "silent") {
20
+ console.log("Fetch http://api.siten.vn/gen/template/default.json");
21
+ fetch("http://api.siten.vn/gen/template/default.json").then(res => res.text()).then(text => {
22
+ common.ensureFolder(path);
23
+
24
+ fs.writeFile(path, text, err => {
25
+ if (err)
26
+ throw err;
27
+ console.log(`Initialized json at ${path}`);
28
+ });
29
+ });
30
+ return;
31
+ }
32
+
33
+ console.log("Fetch http://api.siten.vn/gen/template/template-def.json");
34
+ fetch("http://api.siten.vn/gen/template/template-def.json").then(res => res.json()).then(templateConfig => {
35
+ const info = {};
36
+ templateConfig.fields.forEach(field => {
37
+ while (true)
38
+ {
39
+ let question = `${field.required ? "[Required] " : ""}${field.label || field.name}`;
40
+ if (Array.isArray(field.list)) {
41
+ question += "\n";
42
+ let i = 1;
43
+ field.list.forEach(item => { question += "\t" + i++ + ". " + item + "\n"; });
44
+ question += "Please choose";
45
+ }
46
+ if (field.defaultValue !== undefined) {
47
+ question += ` (default: '${field.defaultValue}')`;
48
+ }
49
+ question += ": ";
50
+ let choice = readlineSync.question(question);
51
+ if (choice === "") {
52
+ if (field.defaultValue != undefined)
53
+ choice = field.defaultValue;
54
+ }
55
+ else if (Array.isArray(field.list)) {
56
+ if (choice !== null && choice !== "" && !isNaN(choice))
57
+ choice = field.list[choice - 1];
58
+ else
59
+ choice = undefined;
60
+ if (choice === undefined) {
61
+ console.warn("Invalid input");
62
+ continue;
63
+ }
64
+ }
65
+
66
+ if (choice === "" || choice === undefined || choice == null) {
67
+ choice = "";
68
+
69
+ if (field.required) {
70
+ console.warn("Required input value");
71
+ continue;
72
+ }
73
+ }
74
+
75
+ if (choice !== "" && field.pattern) {
76
+ const re = new RegExp(field.pattern, field.patternFlags);
77
+ if (!re.test(choice)) {
78
+ console.warn("Input doesn't match with pattern " + field.pattern);
79
+ continue;
80
+ }
81
+ }
82
+
83
+ info[field.name] = choice;
84
+ break;
85
+ }
86
+ });
87
+ //console.log(info);
88
+
89
+ console.log(`Fetch ${templateConfig.templateUrl}`);
90
+ fetch(templateConfig.templateUrl).then(res => res.text()).then(json => {
91
+ json = json.replace(/\"\$\{([\w]+)\}\"/g, (s0, s1) => JSON.stringify(info[s1]));
92
+ json = json.replace(/\$\{([\w]+)\}/g, (s0, s1) => JSON.stringify(info[s1]).replace(/^\"|\"$/g, ""));
93
+
94
+ common.ensureFolder(path);
95
+ //console.log(json);
96
+
97
+ fs.writeFile(path, json, err => {
98
+ if (err)
99
+ throw err;
100
+ console.log(`Initialized json at ${path}`);
101
+ });
102
+ });
103
+ })
104
+ }
105
+
106
+ module.exports = initJson;
@@ -0,0 +1,32 @@
1
+ const fs = require("fs");
2
+ const { spawn } = require("child_process");
3
+ const common = require("../common.js");
4
+
5
+
6
+ function fetchFromGit() {
7
+ return new Promise((resolve, reject) => {
8
+ const git = spawn("git", ["clone", "https://tfs.siten.vn/tfs/Siten/CodeBase/_git/Mushroom", "-b", "full_extensions", "--single-branch"]);
9
+ git.stdout.on('data', (data) => {
10
+ console.log(`GIT: ${data}`);
11
+ });
12
+
13
+ git.stderr.on('data', (data) => {
14
+ console.error(`GIT: ${data}`);
15
+ });
16
+
17
+ git.on('close', (code) => {
18
+ if (code) {
19
+ reject(new Error(`GIT exited with code ${code}`));
20
+ return;
21
+ }
22
+ resolve();
23
+ });
24
+ })
25
+ }
26
+
27
+ async function initNetCore(args) {
28
+ await fetchFromGit();
29
+ common.processTemplate("Mushroom", "mushroom-template.json");
30
+ }
31
+
32
+ module.exports = initNetCore;
package/init.js CHANGED
@@ -1,120 +1,16 @@
1
- const fs = require("fs");
2
- const fetch = require('node-fetch');
3
- const readlineSync = require("readline-sync");
4
1
  const help = require("./help.js");
5
- const common = require("./common.js");
6
2
 
7
- function initJson(args) {
8
- const path = args[2];
9
- if (!path) {
10
- help(args);
11
- return;
12
- }
13
-
14
- if (fs.existsSync(path)){
15
- console.error(`File ${path} is already existed`);
16
- return;
17
- }
18
-
19
- if (args[3] === "silent") {
20
- console.log("Fetch http://api.siten.vn/gen/template/default.json");
21
- fetch("http://api.siten.vn/gen/template/default.json").then(res => res.text()).then(text => {
22
- common.ensureFolder(path);
23
-
24
- fs.writeFile(path, text, err => {
25
- if (err)
26
- throw err;
27
- console.log(`Initialized json at ${path}`);
28
- });
29
- });
30
- return;
31
- }
32
-
33
- console.log("Fetch http://api.siten.vn/gen/template/template-def.json");
34
- fetch("http://api.siten.vn/gen/template/template-def.json").then(res => res.json()).then(templateConfig => {
35
- const info = {};
36
- templateConfig.fields.forEach(field => {
37
- while (true)
38
- {
39
- let question = `${field.required ? "[Required] " : ""}${field.label || field.name}`;
40
- if (Array.isArray(field.list)) {
41
- question += "\n";
42
- let i = 1;
43
- field.list.forEach(item => { question += "\t" + i++ + ". " + item + "\n"; });
44
- question += "Please choose";
45
- }
46
- if (field.defaultValue !== undefined) {
47
- question += ` (default: '${field.defaultValue}')`;
48
- }
49
- question += ": ";
50
- let choice = readlineSync.question(question);
51
- if (choice === "") {
52
- if (field.defaultValue != undefined)
53
- choice = field.defaultValue;
54
- }
55
- else if (Array.isArray(field.list)) {
56
- if (choice !== null && choice !== "" && !isNaN(choice))
57
- choice = field.list[choice - 1];
58
- else
59
- choice = undefined;
60
- if (choice === undefined) {
61
- console.warn("Invalid input");
62
- continue;
63
- }
64
- }
65
-
66
- if (choice === "" || choice === undefined || choice == null) {
67
- choice = "";
68
-
69
- if (field.required) {
70
- console.warn("Required input value");
71
- continue;
72
- }
73
- }
74
-
75
- if (choice !== "" && field.pattern) {
76
- const re = new RegExp(field.pattern, field.patternFlags);
77
- if (!re.test(choice)) {
78
- console.warn("Input doesn't match with pattern " + field.pattern);
79
- continue;
80
- }
81
- }
82
-
83
- info[field.name] = choice;
84
- break;
85
- }
86
- });
87
- //console.log(info);
88
-
89
- console.log(`Fetch ${templateConfig.templateUrl}`);
90
- fetch(templateConfig.templateUrl).then(res => res.text()).then(json => {
91
- json = json.replace(/\"\$\{([\w]+)\}\"/g, (s0, s1) => JSON.stringify(info[s1]));
92
- json = json.replace(/\$\{([\w]+)\}/g, (s0, s1) => JSON.stringify(info[s1]).replace(/^\"|\"$/g, ""));
93
-
94
- common.ensureFolder(path);
95
- //console.log(json);
96
-
97
- fs.writeFile(path, json, err => {
98
- if (err)
99
- throw err;
100
- console.log(`Initialized json at ${path}`);
101
- });
102
- });
103
- })
104
- }
105
-
106
- function initNetCore(args) {
107
- console.log("init netcore is comming soon");
108
- }
3
+ const initJson = require("./init/init-json");
4
+ const initNetCore = require("./init/init-netcore");
109
5
 
110
- function init(args) {
6
+ async function init(args) {
111
7
  const configCommand = args[1];
112
8
  switch(configCommand) {
113
9
  case "json":
114
10
  initJson(args);
115
11
  break;
116
12
  case "netcore":
117
- initNetCore(args);
13
+ await initNetCore(args);
118
14
  break;
119
15
  case "":
120
16
  case undefined:
@@ -205,7 +205,7 @@ function processMasterFile(basePath, master) {
205
205
  action.defaultSortings = action.sorting.split(',').map(f => {
206
206
  const c = f.charAt(0);
207
207
  return {
208
- field: c === "+" || c === "-" ? f.substr(1) : f,
208
+ field: c === "+" || c === "-" ? f.substring(1) : f,
209
209
  type: c === "-" ? "Desc" : "Asc"
210
210
  }
211
211
  });
@@ -216,7 +216,7 @@ function processMasterFile(basePath, master) {
216
216
  action.allowSortings = action.allowSorting.split(',').map(f => {
217
217
  const c = f.charAt(0);
218
218
  return {
219
- field: c === "+" || c === "-" ? f.substr(1) : f,
219
+ field: c === "+" || c === "-" ? f.substring(1) : f,
220
220
  type: c === "-" ? "Desc" : c === "+" ? "Asc" : "Both"
221
221
  }
222
222
  });
package/mr.js CHANGED
@@ -3,11 +3,16 @@
3
3
  const init = require("./init.js");
4
4
  const config = require("./config.js");
5
5
  const gen = require("./gen.js");
6
+ const update = require("./update.js");
6
7
  const help = require("./help.js");
7
8
 
8
- const package = require("./package.json");
9
+ const pkg = require("./package.json");
9
10
  const checkUpdate = require("./check-update");
10
11
 
12
+ const versionGroup = pkg.version.match(/([^-]+)(-(\w+).*)?/);
13
+ const currentDistTag = versionGroup[3] ? versionGroup[3] : "latest";
14
+ console.log("Mushroom CLI version " + pkg.version);
15
+
11
16
  async function run(args) {
12
17
  let debugMode = false;
13
18
  if (args.indexOf("--debug") !== -1) {
@@ -15,10 +20,8 @@ async function run(args) {
15
20
  args = args.filter(arg => arg !== "--debug");
16
21
  }
17
22
 
18
- let noCheckUpdate = false;
19
23
  let checkUpdateTask;
20
24
  if (args.indexOf("--no-check-update") !== -1){
21
- noCheckUpdate = true;
22
25
  args = args.filter(arg => arg !== "--no-check-update");
23
26
  checkUpdateTask = null;
24
27
  }
@@ -38,6 +41,9 @@ async function run(args) {
38
41
  case "gen":
39
42
  await gen(args);
40
43
  break;
44
+ case "update":
45
+ await update(args);
46
+ break;
41
47
  case "":
42
48
  case undefined:
43
49
  console.log(`Mushroom CLI`);
@@ -59,8 +65,8 @@ async function run(args) {
59
65
  if (checkUpdateTask !== null)
60
66
  try {
61
67
  var data = await checkUpdateTask;
62
- if (data.version && data.version !== package.version) {
63
- console.warn("YOUR mushroom-cli VERSION IS NOT LATEST. PLEASE RUN: npm i mushroom-cli@" + data.version);
68
+ if (data["dist-tags"] && data["dist-tags"][currentDistTag] && data["dist-tags"][currentDistTag] !== pkg.version) {
69
+ console.warn(`YOUR mushroom-cli VERSION IS NOT LATEST (dist-tags: ${currentDistTag}). PLEASE RUN: npm i mushroom-cli@${data["dist-tags"][currentDistTag]}`);
64
70
  }
65
71
  }
66
72
  catch(e) {