eitri-cli 1.4.0 → 1.5.0

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/index.js CHANGED
@@ -77,6 +77,7 @@ const run = async () => {
77
77
  )
78
78
  .option("-l, --local", "Aponta para o servidor local")
79
79
  .option("-v, --verbose", "Exibe mais logs")
80
+ .option("-r, --release", "Gera uma nova release baseado nos commits. Um arquivo CHANGELOG.md será gerado automaticamente.")
80
81
  .option(
81
82
  "-c, --components",
82
83
  "Publica o Eitri-App como biblioteca de components"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "eitri-cli",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "Command Line Interface to make \"Eitri-App\" with code and fire.",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -57,6 +57,7 @@
57
57
  "semver": "^7.1.3",
58
58
  "slugify": "^1.4.0",
59
59
  "socket.io-client": "^4.5.2",
60
+ "standard-version": "^9.5.0",
60
61
  "temp-dir": "^2.0.0",
61
62
  "tmp": "^0.1.0",
62
63
  "tough-cookie": "^3.0.1",
@@ -77,7 +78,7 @@
77
78
  "lint-staged": "^9.5.0",
78
79
  "nock": "^13.3.0",
79
80
  "puppeteer": "^21.4.1",
80
- "semantic-release": "^22.0.5"
81
+ "semantic-release": "^22.0.8"
81
82
  },
82
83
  "resolutions": {
83
84
  "lodash": "4.17.21",
@@ -8,14 +8,17 @@ const config = require('../service/ConfigService')
8
8
  const TargetService = require('../service/TargetService')
9
9
  const inquirer = require('inquirer')
10
10
  const TrackingEitriAnalytics = require('../service/TrackingEitriAnalytics')
11
- const VegvisirService = require('../modules/vegvisir/VegvisirService')
12
- const getWorkspace = require('../util/getWorkspace')
13
11
  const UserLocalCredential = require('../util/UserLocalCredential')
14
-
12
+ const VegvisirService = require('../modules/vegvisir/VegvisirService')
13
+ const {randomUUID} = require('crypto')
14
+ const childProcess = require('child_process')
15
15
  const blindGuardian = workspace.blindGuardian
16
16
  const trackingService = new TrackingService(blindGuardian)
17
17
  const targetService = new TargetService(workspace)
18
18
  const vegvisirService = new VegvisirService()
19
+ const standardVersion = require('standard-version')
20
+ const releaseService = require('../service/ReleaseService')
21
+ const {isGitRepo} = require('../util/GenericUtils')
19
22
 
20
23
  module.exports = async function pushVersion(cmdObj) {
21
24
  try {
@@ -26,6 +29,8 @@ module.exports = async function pushVersion(cmdObj) {
26
29
  return
27
30
  }
28
31
 
32
+ const separator = '======================================================================='
33
+
29
34
  try {
30
35
  await validator.assertPushVersionMessage(cmdObj.message)
31
36
  await validator.assertCommandNotRunning('push-version')
@@ -39,7 +44,62 @@ module.exports = async function pushVersion(cmdObj) {
39
44
  }
40
45
  workspace.publishing = true
41
46
  const miniConf = workspace.getMiniConf()
42
- await vegvisirService.check(miniConf.slug)
47
+
48
+ if (cmdObj?.release) {
49
+ if (!isGitRepo()) {
50
+ const emptyGitRepoMessages = [
51
+ "Este projeto não tem um repositório git. Processo interrompido.",
52
+ "Por favor, inicialize o git neste repositório antes de",
53
+ "realizar [push-version --release]"
54
+ ]
55
+ console.log(`\x1b[1m\x1b[31m${emptyGitRepoMessages?.join("\n")}\x1b[0m`);
56
+ return
57
+ }
58
+
59
+ const currentBranch = childProcess.execSync("git branch --show-current", {encoding: 'utf-8'}).trim();
60
+ const allowedBranchs = ["main", "master"]
61
+ const isAllowedFlow = allowedBranchs?.includes(currentBranch)
62
+ if(!isAllowedFlow){
63
+ const warningMessages = [
64
+ '\n\n',
65
+ separator,
66
+ 'Aviso: As condições obrigatórias não foram contempladas.',
67
+ '\n',
68
+ 'Por favor, certifique-se de:',
69
+ '- Informar o comando "release" ao executar o script.',
70
+ '- Estar na branch "master" ou "main".',
71
+ ` - Branch atual: [${currentBranch}]`,
72
+ '\n',
73
+ 'Nenhuma versão foi gerada e enviada.',
74
+ separator,
75
+ '\n\n',
76
+ ]
77
+
78
+ console.log(`\x1b[1m\x1b[33m${warningMessages?.join("\n")}\x1b[0m`);
79
+
80
+ return
81
+ }
82
+
83
+ console.log("Iniciando geração de versão com CI")
84
+ try {
85
+ await releaseService()
86
+ const lastTag = childProcess.execSync('git describe --tags --abbrev=0').toString().trim();
87
+ const newVersion = lastTag?.replace(/^v/, "");
88
+ console.log(`Nova versão preparada: ${newVersion}`)
89
+
90
+ miniConf.version = newVersion
91
+ const newMiniConf = {
92
+ ...miniConf,
93
+ version: newVersion
94
+ }
95
+ workspace.setMiniConf(newMiniConf)
96
+
97
+ const miniConfUpdated = workspace.getMiniConf()
98
+ console.log(`Versão [${miniConfUpdated?.version}] atualizada no eitri-app.conf.js`)
99
+ } catch (error) {
100
+ console.error("Erro ao gerar a nova versão: ", error?.message)
101
+ }
102
+ }
43
103
 
44
104
  let validateResult = checkErros(miniConf)
45
105
 
@@ -78,13 +138,15 @@ ${await targetService.getAppConfExampleSnippet()}
78
138
 
79
139
  return
80
140
  }
81
- const separator = '======================================================================='
82
141
  blindGuardian.readConf()
83
142
  workspace.setServerUrl(config.get('workspace').url)
84
143
  console.log('Conectando ao Eitri...')
85
- await workspace.init()
86
- const userWorkspace = await getWorkspace()
87
- await miniLog.connect(userWorkspace.id)
144
+
145
+ const tempWorkspaceId = randomUUID()
146
+ vegvisirService.setWorkspaceId(tempWorkspaceId)
147
+ await workspace.initPushVersion(tempWorkspaceId)
148
+
149
+ await miniLog.connect(tempWorkspaceId)
88
150
  console.log(separator)
89
151
  console.log("Analisando versões...");
90
152
 
package/src/cmd/start.js CHANGED
@@ -10,7 +10,6 @@ const handleStartServer = require('../service/StarterService')
10
10
  const inquirer = require('inquirer')
11
11
  const TrackingEitriAnalytics = require('../service/TrackingEitriAnalytics')
12
12
  const VegvisirService = require('../modules/vegvisir/VegvisirService')
13
- const getWorkspace = require('../util/getWorkspace')
14
13
  const UserLocalCredential = require('../util/UserLocalCredential')
15
14
 
16
15
  const blindGuardian = workspace.blindGuardian
@@ -71,7 +70,7 @@ module.exports = async function start(args) {
71
70
  workspace.setQrCodeUrl(qrCodeUrl)
72
71
  await workspace.init()
73
72
  const silentOnConnect = args.verbose ? false : true
74
- const userWorkspace = await getWorkspace()
73
+ const userWorkspace = await vegvisirService.getWorkspace()
75
74
  await miniLog.connect(userWorkspace.id, silentOnConnect)
76
75
 
77
76
  console.log("Construindo...");
@@ -18,6 +18,10 @@ module.exports = function VegvisirCommand() {
18
18
  "--local",
19
19
  "Seleciona um workspace para um diretório de Eitri-App específico"
20
20
  )
21
+ .option(
22
+ "--name <workspace-name>",
23
+ "Permite selecionar um workspace previamente criado pelo nome"
24
+ )
21
25
  .action(async (cmdObj) => {
22
26
  require("./cmd/use.js")(cmdObj);
23
27
  });
@@ -2,14 +2,26 @@ const { default: axios } = require("../../../node_modules/axios/index");
2
2
  const BlindGuardian = require("../../service/BlindGuardian");
3
3
  const Http = require("../../service/Http");
4
4
  const configService = require("../../service/ConfigService");
5
- const getWorkspace = require("../../util/getWorkspace");
6
5
  const writeGlobalWorkspaceConfig = require("./utils/writeGlobalWorkspaceConfig");
7
-
6
+ const { readFile } = require("fs/promises");
7
+ const os = require("os");
8
+ const {validateUUID} = require("../../util/GenericUtils");
9
+ const path = require("path");
10
+ const fs = require('fs')
8
11
  module.exports = class VegvisirService {
9
12
  constructor() {
10
13
  const blindGuardian = new BlindGuardian();
11
14
  this.http = new Http(blindGuardian);
12
15
  this.config = configService.get("vegvisir");
16
+ this.workspaceId = "";
17
+ }
18
+
19
+ getWorkspaceId() {
20
+ return this.workspaceId;
21
+ }
22
+
23
+ setWorkspaceId(id) {
24
+ this.workspaceId = id;
13
25
  }
14
26
 
15
27
  async listMyWorkspaces() {
@@ -44,7 +56,7 @@ module.exports = class VegvisirService {
44
56
 
45
57
  async check(slug) {
46
58
  try {
47
- let workspace = await getWorkspace()
59
+ let workspace = await this.getWorkspace()
48
60
  if(!workspace) {
49
61
  const workspaces = await this.listMyWorkspaces();
50
62
  const defaultWorkspace = await workspaces.find(w => w.name === 'DEFAULT')
@@ -78,4 +90,40 @@ module.exports = class VegvisirService {
78
90
  }
79
91
 
80
92
  }
93
+
94
+ async getWorkspace() {
95
+ try {
96
+ const workspaceEitriAppProjectPath = path.resolve(
97
+ process.cwd(),
98
+ ".workspaces",
99
+ "workspace"
100
+ );
101
+
102
+ if (fs.existsSync(workspaceEitriAppProjectPath)) {
103
+ const fileContent = await readFile(
104
+ workspaceEitriAppProjectPath,
105
+ "utf8"
106
+ );
107
+ const workspace = JSON.parse(fileContent);
108
+ return workspace;
109
+ }
110
+ const workspaceGlobalPath = path.resolve(
111
+ os.homedir(),
112
+ ".eitri",
113
+ "workspaces",
114
+ "workspace"
115
+ );
116
+ const fileContent = await readFile(workspaceGlobalPath, "utf8");
117
+ const workspace = JSON.parse(fileContent);
118
+ console.log("Consutrindo de ", workspace.id)
119
+ workspace.id = validateUUID(this.workspaceId) ? this.workspaceId : workspace.id;
120
+ return workspace;
121
+ } catch (error) {
122
+ if(error.code === "ENOENT") {
123
+ return;
124
+ }
125
+ console.error("Ocorreu um erro inesperado ao tentar ler o workspace atual.", error?.message)
126
+ return process.exit(1)
127
+ }
128
+ };
81
129
  };
@@ -1,8 +1,9 @@
1
- const getWorkspace = require("../../../util/getWorkspace");
1
+ const VegvisirService = require("../../vegvisir/VegvisirService");
2
+ const vegvisirService = new VegvisirService()
2
3
 
3
4
  module.exports = async function current(cmdObj) {
4
5
  try {
5
- const workspace = await getWorkspace()
6
+ const workspace = await vegvisirService.getWorkspace()
6
7
  if(!workspace) {
7
8
  console.log("Você não possui workspace selecionado para desenvolvimento.")
8
9
  return;
@@ -11,18 +11,28 @@ module.exports = async function use(cmdArgs) {
11
11
  const workspaces = await vegvisirService.listMyWorkspaces();
12
12
  if (!workspaces) return;
13
13
 
14
- const { workspaceName } = await inquirer.prompt([
15
- {
16
- name: "workspaceName",
17
- type: "rawlist",
18
- message: "Selecione qual workspace você deseja utilizar:",
19
- choices: workspaces,
20
- },
21
- ]);
14
+ let workspaceNameSelected = cmdArgs?.name
15
+
16
+ if(!cmdArgs?.name){
17
+ const { workspaceName } = await inquirer.prompt([
18
+ {
19
+ name: "workspaceName",
20
+ type: "rawlist",
21
+ message: "Selecione qual workspace você deseja utilizar:",
22
+ choices: workspaces,
23
+ },
24
+ ]);
25
+ workspaceNameSelected = workspaceName
26
+ }
22
27
 
23
28
  const selectedWorkspace = workspaces.find(
24
- (work) => work.name === workspaceName
29
+ (work) => work?.name === workspaceNameSelected
25
30
  );
31
+ if(!selectedWorkspace){
32
+ const workspacesNames = Array.isArray(workspaces) && workspaces?.length > 0 ? workspaces?.map(w => w.name) : [];
33
+ console.warn(`O workspace [${cmdArgs?.name}] não existe. Workspaces existentes: `, JSON.stringify(workspacesNames));
34
+ return;
35
+ };
26
36
 
27
37
  if (cmdArgs.local) {
28
38
  await writeLocalWorkspaceConfig(selectedWorkspace);
@@ -5,12 +5,11 @@ const CookieJar = require('tough-cookie').CookieJar
5
5
  const os = require('os')
6
6
  const path = require('path')
7
7
  const getCliVersion = require('../util/getCliVersion')
8
- const getWorkspace = require('../util/getWorkspace')
9
8
  const { randomUUID } = require('crypto')
9
+ const getWorkspace = require('../util/getWorkspace')
10
10
 
11
11
  const filePath = path.join(os.homedir(), './.eitri.cookie.json')
12
12
  const jar = new CookieJar(new FileCookieStore(filePath))
13
-
14
13
  const axios = require('axios').create({ withCredentials: true, jar })
15
14
 
16
15
  axiosCookieJarSupport(axios)
@@ -38,6 +37,7 @@ class Http {
38
37
  constructor(tokenFactory) {
39
38
  this.tokenFactory = tokenFactory
40
39
  this.newTokenAttempt = 0
40
+ this.workspaceId = ""
41
41
  }
42
42
 
43
43
  setTokenFactory(tokenFactory) {
@@ -48,6 +48,10 @@ class Http {
48
48
  this.token = token
49
49
  }
50
50
 
51
+ setWorkspaceId(id){
52
+ this.workspaceId = id
53
+ }
54
+
51
55
  getCookieSession(url) {
52
56
  return new Promise((resolve, reject) => {
53
57
  jar.getCookies(url, { allPaths: true }, function (err, cookies) {
@@ -87,7 +91,7 @@ class Http {
87
91
  'App-Tools-Version': getCliVersion()
88
92
  }
89
93
  if (url.includes("foundry") || url.includes("runes-foundry")) {
90
- headers["Workspace-Id"] = (await getWorkspace()).id;
94
+ headers["Workspace-Id"] = this.workspaceId ? this.workspaceId : (await getWorkspace()).id;
91
95
  }
92
96
 
93
97
  return headers
@@ -0,0 +1,126 @@
1
+ const path = require('path')
2
+ const fs = require('fs')
3
+ const childProcess = require('child_process')
4
+ const rimraf = require('rimraf');
5
+
6
+ const TEMP_FOLDER_NAME = "temp_eitri_ci"
7
+ const TEMP_CHANGELOG_FILE_NAME = "CHANGELOG_TEMP"
8
+ const CHANGELOG_FILE_NAME = "CHANGELOG.md"
9
+
10
+ module.exports = async function releaseService() {
11
+ _printLog(`\x1b[1m\x1b[32mIniciando Geração Automática de Versão\x1b[0m`)
12
+ await _factoryTempFolder()
13
+ await _factoryReleaseConfig()
14
+ await _downloadDependencies()
15
+ await _installDependencies()
16
+ await _updateChangeLog()
17
+ await _clearResources()
18
+ }
19
+
20
+ async function _factoryTempFolder() {
21
+ try {
22
+ fs.mkdirSync(TEMP_FOLDER_NAME, {recursive: true})
23
+ } catch (error) {
24
+ _throwError("Erro ao gerar pasta temporária", error?.message)
25
+ }
26
+ }
27
+
28
+ async function _factoryReleaseConfig() {
29
+ try {
30
+ const releasercContent = {
31
+ "branches": [
32
+ "main",
33
+ "master",
34
+ ],
35
+ "plugins": [
36
+ "@semantic-release/commit-analyzer",
37
+ "@semantic-release/release-notes-generator",
38
+ [
39
+ "@semantic-release/changelog",
40
+ {
41
+ "changelogFile": `${TEMP_CHANGELOG_FILE_NAME}.md`
42
+ }
43
+ ],
44
+ [
45
+ "@semantic-release/git",
46
+ {
47
+ "assets": [
48
+ `${CHANGELOG_FILE_NAME}`,
49
+ "eitri-app.conf.js",
50
+ `!${TEMP_FOLDER_NAME}`
51
+ ],
52
+ "message": "chore(release): ${nextRelease.version}[skip ci]\n\n${nextRelease.notes}"
53
+ }
54
+ ]
55
+ ]
56
+ };
57
+
58
+ const releasercFilePath = path.join(TEMP_FOLDER_NAME, '.releaserc.json');
59
+ fs.writeFileSync(releasercFilePath, JSON.stringify(releasercContent, null, 2));
60
+ } catch (error) {
61
+ _throwError("Erro ao criar o arquivo de configuração da release", error?.message)
62
+ }
63
+ }
64
+
65
+ async function _downloadDependencies() {
66
+ _printLog("Baixando as configurações. Este processo pode demorar alguns segundos.")
67
+ childProcess.execSync(`cd ${TEMP_FOLDER_NAME}/ && npm i semantic-release @semantic-release/git @semantic-release/changelog`)
68
+ }
69
+
70
+ async function _installDependencies() {
71
+ _printLog("Instalando configuração temporária de CI. Este processo pode demorar alguns segundos.")
72
+ childProcess.execSync(`cd ${TEMP_FOLDER_NAME}/ && npx semantic-release --no-ci --no-npm-publish --no-github-publish --working-directory=${TEMP_FOLDER_NAME} --skip-verify-conditions`)
73
+ _printLog("Configuração de CI instalada", TEMP_CHANGELOG_FILE_NAME)
74
+ }
75
+
76
+ async function _updateChangeLog() {
77
+ const hasTempChangelog = fs.existsSync(`${TEMP_FOLDER_NAME}/${TEMP_CHANGELOG_FILE_NAME}.md`)
78
+ if (hasTempChangelog) {
79
+ _printLog(`Iniciando atualização do ${CHANGELOG_FILE_NAME}`)
80
+ const contentNewChangelog = fs.readFileSync(`${TEMP_FOLDER_NAME}/${TEMP_CHANGELOG_FILE_NAME}.md`, "utf-8");
81
+ const newPath = path.join(`${CHANGELOG_FILE_NAME}`)
82
+
83
+ if (!fs.existsSync(newPath)) {
84
+ await _createChangeLogMd()
85
+ }
86
+
87
+ const contentOriginalChangelog = fs.readFileSync(newPath, "utf-8")
88
+ const newContent = contentNewChangelog + "\n\n" + contentOriginalChangelog
89
+ fs.writeFileSync(newPath, newContent)
90
+
91
+ _printLog(`Arquivo ${CHANGELOG_FILE_NAME} atualizado`)
92
+ return
93
+ }
94
+
95
+ _throwError("Arquivo temporário de Changelog não gerado", {hasTempChangelog})
96
+ }
97
+
98
+ async function _clearResources() {
99
+ rimraf(TEMP_FOLDER_NAME, (error) => {
100
+ if (error) {
101
+ _throwError(`Erro ao remover a pasta ${TEMP_FOLDER_NAME}:`, error?.message)
102
+ } else {
103
+ _printLog(`Limpando pasta temporária ${TEMP_FOLDER_NAME}`);
104
+ }
105
+ });
106
+ }
107
+
108
+ async function _createChangeLogMd(newPath) {
109
+ _printLog(`Arquivo de ${CHANGELOG_FILE_NAME} inexistente. [Changelog: ${newPath}]`)
110
+ _printLog("Criando arquivo")
111
+ fs.writeFileSync(`${CHANGELOG_FILE_NAME}`, "");
112
+ }
113
+
114
+ function _printLog(text = "", isError = false) {
115
+ if (isError) {
116
+ console.error("\n" + text)
117
+ } else {
118
+ console.log("\n" + text)
119
+ }
120
+ }
121
+
122
+ function _throwError(text = "", errorMessage = "") {
123
+ const error = `${text} [message: ${errorMessage}]`
124
+ _printLog(error, !!error)
125
+ throw new Error(error)
126
+ }
@@ -23,8 +23,9 @@ const Buffer = require("buffer");
23
23
  const DEFAULT_ENV = "dev";
24
24
  const cliProgress = require("cli-progress");
25
25
  const EitriAppManager = require("./EitriAppManager");
26
- const getWorkspace = require("../util/getWorkspace");
27
26
  const EitriAppService = require("./EitriAppService");
27
+ const VegvisirService = require("../modules/vegvisir/VegvisirService");
28
+ const vegvisirService = new VegvisirService()
28
29
 
29
30
  class Workspace {
30
31
 
@@ -96,6 +97,7 @@ class Workspace {
96
97
  return this.resourceFolders2watch;
97
98
  }
98
99
 
100
+
99
101
  async getTargetConfig(id, target) {
100
102
  try {
101
103
  const configs = await this.getAllTargetConfigs(target);
@@ -152,6 +154,11 @@ class Workspace {
152
154
  this.userEmail = token.email;
153
155
  }
154
156
 
157
+ async initPushVersion(workspaceId = "") {
158
+ this.http.setWorkspaceId(workspaceId);
159
+ this.init()
160
+ }
161
+
155
162
  getMiniConf() {
156
163
  if (!this._miniConf) {
157
164
  const eitriAppConfPath = path.resolve(
@@ -182,22 +189,41 @@ class Workspace {
182
189
  setMiniConf(miniConf) {
183
190
  this._miniConf = miniConf;
184
191
  return new Promise((resolve, reject) => {
185
- const miniAppConfPath = path.resolve(
192
+ const eitriAppConfPath = path.resolve(
186
193
  this.folder2watch,
187
- "../miniapp.conf.js"
194
+ "../eitri-app.conf.js"
188
195
  );
189
- const jsonContent = JSON.stringify(miniConf, null, 4);
190
- fs.writeFile(
191
- miniAppConfPath,
192
- `module.exports = ${jsonContent}`,
193
- (err) => {
194
- if (err) {
195
- console.log(err);
196
- return reject(err);
196
+ if (fs.existsSync(eitriAppConfPath)) {
197
+ const jsonContent = JSON.stringify(miniConf, null, 4);
198
+ fs.writeFile(
199
+ eitriAppConfPath,
200
+ `module.exports = ${jsonContent}`,
201
+ (err) => {
202
+ if (err) {
203
+ console.log(err);
204
+ return reject(err);
205
+ }
206
+ resolve();
197
207
  }
198
- resolve();
199
- }
200
- );
208
+ );
209
+ } else {
210
+ const miniAppConfPath = path.resolve(
211
+ this.folder2watch,
212
+ "../miniapp.conf.js"
213
+ );
214
+ const jsonContent = JSON.stringify(miniConf, null, 4);
215
+ fs.writeFile(
216
+ miniAppConfPath,
217
+ `module.exports = ${jsonContent}`,
218
+ (err) => {
219
+ if (err) {
220
+ console.log(err);
221
+ return reject(err);
222
+ }
223
+ resolve();
224
+ }
225
+ );
226
+ }
201
227
  });
202
228
  }
203
229
 
@@ -364,7 +390,7 @@ class Workspace {
364
390
  let miniAppUrl = `${this.getBootstrapURL(
365
391
  targetConfig.bootstrapBaseUrl
366
392
  )}/${this.config.basePath || "workspace"
367
- }/user/${(await getWorkspace()).id}/${viewHtml}?data=${encodedData}${paramOrderId}${paramShareId}&devmode=true`;
393
+ }/user/${(await vegvisirService.getWorkspace()).id}/${viewHtml}?data=${encodedData}${paramOrderId}${paramShareId}&devmode=true`;
368
394
 
369
395
  if (cid) {
370
396
  miniAppUrl = miniAppUrl + "&cid=" + cid;
@@ -1043,6 +1069,7 @@ class Workspace {
1043
1069
  toBase64(content) {
1044
1070
  return Buffer.from(content).toString("base64");
1045
1071
  }
1072
+
1046
1073
  }
1047
1074
 
1048
1075
  module.exports = {
@@ -1,3 +1,4 @@
1
+ const childProcess = require('child_process')
1
2
  class GenericUtils {
2
3
 
3
4
  static formatQrCodeCurrentDateTime = () => {
@@ -14,6 +15,21 @@ class GenericUtils {
14
15
  return formattedDateTime;
15
16
  }
16
17
 
18
+ static validateUUID = (uuid = "") => {
19
+ const regexExp = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi;
20
+ return uuid && typeof uuid === "string" && regexExp.test(uuid)
21
+ }
22
+
23
+ static isGitRepo() {
24
+ try {
25
+ const gitCommand = "git branch --show-current";
26
+ const res = childProcess.execSync(gitCommand, {encoding: 'utf-8'}).trim();
27
+ return !!res
28
+ } catch (error) {
29
+ return false;
30
+ }
31
+ }
32
+
17
33
  }
18
34
 
19
35
  module.exports = GenericUtils
@@ -1,5 +1,5 @@
1
- const { existsSync } = require("fs");
2
- const { readFile } = require("fs/promises");
1
+ const {existsSync} = require("fs");
2
+ const {readFile} = require("fs/promises");
3
3
  const path = require("path");
4
4
  const os = require("os");
5
5
  module.exports = async function getWorkspace() {
@@ -9,7 +9,7 @@ module.exports = async function getWorkspace() {
9
9
  ".workspaces",
10
10
  "workspace"
11
11
  );
12
-
12
+
13
13
  if (existsSync(workspaceEitriAppProjectPath)) {
14
14
  const fileContent = await readFile(
15
15
  workspaceEitriAppProjectPath,
@@ -28,10 +28,10 @@ module.exports = async function getWorkspace() {
28
28
  const workspace = JSON.parse(fileContent);
29
29
  return workspace;
30
30
  } catch (error) {
31
- if(error.code === "ENOENT") {
31
+ if (error.code === "ENOENT") {
32
32
  return;
33
33
  }
34
34
  console.error("Houve um erro inesperado ao tentar ler o workspace atual.")
35
35
  return process.exit(1)
36
36
  }
37
- };
37
+ };
package/test/Executor.js CHANGED
@@ -20,7 +20,7 @@ class Executor {
20
20
  });
21
21
  this.child.stderr.on('data', (lines) => {
22
22
  if (lines && lines.includes('Error:')) {
23
- reject(lines);
23
+ throw new Error(lines)
24
24
  }
25
25
  });
26
26
  return this
@@ -9,6 +9,7 @@ const Helper = require("../Helper.js");
9
9
  const ConfigService = require("../../src/service/ConfigService.js");
10
10
  const Http = require("../../src/service/Http.js");
11
11
  const BlindGuardian = require("../../src/service/BlindGuardian.js");
12
+ const childProcess = require('child_process')
12
13
 
13
14
  describe("eitri-cli", () => {
14
15
  const EITRI_WORK_DIR = path.join(__dirname, "..", "..", "developer-folder");
@@ -117,7 +118,7 @@ describe("eitri-cli", () => {
117
118
  inputPassword.type(String(loginVars.EITRI_TEST_LOGIN_PASSWORD));
118
119
 
119
120
  const buttonElement = await page.waitForXPath(
120
- "/html/body/div/div/div[2]/div[2]/div/div/div/form/div/button"
121
+ '//*[@id="root"]/div/div/div[2]/div/div/div/form/div/button'
121
122
  );
122
123
  console.log("Clicando no botão");
123
124
  buttonElement.click();
@@ -190,6 +191,27 @@ describe("eitri-cli", () => {
190
191
  2 * minutes
191
192
  );
192
193
 
194
+ it(
195
+ "should select workspace by name",
196
+ async () => {
197
+ try {
198
+ await execAsync(
199
+ `cd ${EITRI_WORK_DIR} && rm -rf ./eitri-test-*`,
200
+ { env: process.env }
201
+ );
202
+
203
+ const executor = new Executor({ env: devEnv });
204
+ await executor
205
+ .exec("eitri workspace use --name DEFAULT")
206
+ .waitFor(/Workspace configurado com sucesso!/);
207
+ } catch (e) {
208
+ console.error(e);
209
+ throw e;
210
+ }
211
+ },
212
+ 2 * minutes
213
+ );
214
+
193
215
  const getPublishedVersion = async (version, eitriAppId) => {
194
216
  const blindGuardian = new BlindGuardian();
195
217
  const http = new Http(blindGuardian);
@@ -1,5 +1,6 @@
1
- const getWorkspace = require("../../src/util/getWorkspace");
1
+ const VegvisirService = require("../../src/modules/vegvisir/VegvisirService");
2
2
  const fs = require('fs/promises')
3
+ const vegvisirService = new VegvisirService()
3
4
 
4
5
 
5
6
  jest.mock('fs', () => ({
@@ -9,7 +10,7 @@ jest.mock('fs', () => ({
9
10
  describe('Get WorkspaceID Tests', () => {
10
11
 
11
12
  it('should return error if workspace file not found', async () => {
12
- const promise = getWorkspace()
13
+ const promise = vegvisirService.getWorkspace()
13
14
  await expect(promise).rejects.toThrow("Você não tem nenhum workspace definido para desenvolvimento, execute o comando 'eitri workspace use' para definir um workspace.")
14
15
  });
15
16