eitri-cli 1.38.0-beta.9 → 1.39.0-beta.1

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.
Files changed (95) hide show
  1. package/.husky/pre-commit +0 -0
  2. package/eitri-cli-v2/eitri-cli-v2.darwin-arm64.node +0 -0
  3. package/eitri-cli-v2/eitri-cli-v2.darwin-x64.node +0 -0
  4. package/eitri-cli-v2/eitri-cli-v2.linux-x64-gnu.node +0 -0
  5. package/eitri-cli-v2/eitri-cli-v2.win32-x64-msvc.node +0 -0
  6. package/eitri-cli-v2/index.d.ts +11 -1
  7. package/index.js +4 -21
  8. package/package.json +3 -49
  9. package/src/modules/app/AppCommand.js +1 -1
  10. package/src/modules/vegvisir/VegvisirCommand.js +7 -13
  11. package/.eslintrc.json +0 -26
  12. package/.prettierrc +0 -6
  13. package/src/cmd/clean.js +0 -144
  14. package/src/cmd/create.js +0 -332
  15. package/src/cmd/credentials.js +0 -105
  16. package/src/cmd/doctor.js +0 -70
  17. package/src/cmd/invite.js +0 -87
  18. package/src/cmd/list.js +0 -36
  19. package/src/cmd/login.js +0 -70
  20. package/src/cmd/loginV2.js +0 -89
  21. package/src/cmd/manage-env.js +0 -129
  22. package/src/cmd/open-share.js +0 -6
  23. package/src/cmd/order-details.js +0 -6
  24. package/src/cmd/push-version.js +0 -260
  25. package/src/cmd/show-message-if-outdated-package.js +0 -32
  26. package/src/cmd/signup.js +0 -71
  27. package/src/cmd/start.js +0 -181
  28. package/src/cmd/tail-logs.js +0 -26
  29. package/src/cmd/test-initialization-params.js +0 -6
  30. package/src/cmd/validate.js +0 -164
  31. package/src/cmd/version.js +0 -18
  32. package/src/enum/WatcherOpts.js +0 -3
  33. package/src/enum/target.js +0 -6
  34. package/src/helpers/request-listener-helper.js +0 -55
  35. package/src/model/EitriAppType.js +0 -4
  36. package/src/model/Payload.js +0 -45
  37. package/src/model/Target.js +0 -61
  38. package/src/model/User.js +0 -11
  39. package/src/service/AuthConfig.js +0 -85
  40. package/src/service/BlindGuardian.js +0 -131
  41. package/src/service/CliLogin.js +0 -52
  42. package/src/service/ConfigService.js +0 -9
  43. package/src/service/CredentialsService.js +0 -47
  44. package/src/service/EitriAppManager.js +0 -32
  45. package/src/service/EitriAppService.js +0 -49
  46. package/src/service/Emulator/AndroidEmulatorService.js +0 -132
  47. package/src/service/Emulator/IOSEmulatorService.js +0 -71
  48. package/src/service/EmulatorService.js +0 -17
  49. package/src/service/GATrackingStrategy.js +0 -16
  50. package/src/service/HashFolder.js +0 -79
  51. package/src/service/Http.js +0 -300
  52. package/src/service/HuginService.js +0 -38
  53. package/src/service/InviteService.js +0 -45
  54. package/src/service/LibsService.js +0 -191
  55. package/src/service/ManageEnvService.js +0 -10
  56. package/src/service/MiniLog.js +0 -166
  57. package/src/service/PrerequisitesValidator.js +0 -99
  58. package/src/service/QRCodeFactory.js +0 -81
  59. package/src/service/ReleaseService.js +0 -126
  60. package/src/service/Server.js +0 -220
  61. package/src/service/StarterService.js +0 -31
  62. package/src/service/TagTree.js +0 -101
  63. package/src/service/TargetService.js +0 -97
  64. package/src/service/TrackService.js +0 -11
  65. package/src/service/TrackingEitriAnalytics.js +0 -26
  66. package/src/service/TrackingService.js +0 -183
  67. package/src/service/ValidateResult.js +0 -57
  68. package/src/service/Watcher.js +0 -118
  69. package/src/service/Workspace.js +0 -1045
  70. package/src/service/WorkspaceManager.js +0 -76
  71. package/src/service/factories/DoubtsStarterFactory.js +0 -25
  72. package/src/service/factories/MiniWebAppFactory.js +0 -44
  73. package/src/service/factories/QRCodeStarterFactory.js +0 -154
  74. package/src/service/factories/WebStarterFactory.js +0 -88
  75. package/src/service/factories/WoodCoffeeFactory.js +0 -292
  76. package/src/util/AboutTemplate.jsx +0 -14
  77. package/src/util/FileUtils.js +0 -25
  78. package/src/util/GenericUtils.js +0 -41
  79. package/src/util/LibUtil.js +0 -32
  80. package/src/util/LogUtil.js +0 -14
  81. package/src/util/UrlUtils.js +0 -12
  82. package/src/util/UserLocalCredential.js +0 -128
  83. package/src/util/convertKeysToCamelCase.js +0 -26
  84. package/src/util/error-messages/error-messages.js +0 -24
  85. package/src/util/error-messages/invite/invite-error-messages.js +0 -14
  86. package/src/util/getCliVersion.js +0 -13
  87. package/src/util/getCreateFactory.js +0 -9
  88. package/src/util/getWorkspace.js +0 -37
  89. package/src/util/ipv4.js +0 -19
  90. package/src/util/manage-env.js +0 -65
  91. package/src/util/open-docs.js +0 -7
  92. package/src/util/os.js +0 -39
  93. package/src/util/server-url.js +0 -15
  94. package/src/util/template-utils.js +0 -21
  95. package/src/view/index.html +0 -19
@@ -1,131 +0,0 @@
1
- const os = require('os')
2
- const path = require('path')
3
- const axios = require('axios')
4
- const configService = require('../service/ConfigService')
5
- const { exit } = require('process')
6
- const UserLocalCredential = require('../util/UserLocalCredential')
7
-
8
- const DEFAULT_ENV = 'hml'
9
-
10
- class BlindGuardian {
11
- constructor() {
12
- this.blindGuardianUrl = configService.get('blindGuardian').url
13
- }
14
-
15
- /**
16
- * @deprecated Use UserLocalCredential._getConfigPath
17
- */
18
- getConfPath() {
19
- let configPath = path.resolve(
20
- os.homedir(),
21
- configService.get('signup').get('configFilePath')
22
- )
23
-
24
- return configPath
25
- }
26
-
27
- readConf() {
28
- if (
29
- process.env.EITRI_CLI_CLIENT_ID &&
30
- process.env.EITRI_CLI_CLIENT_SECRET
31
- ) {
32
- return {
33
- devUser: process.env.EITRI_CLI_CLIENT_ID,
34
- devKey: process.env.EITRI_CLI_CLIENT_SECRET,
35
- }
36
- }
37
- return new UserLocalCredential()._getNewConfigPath()
38
- }
39
-
40
- readClientCredentials() {
41
- const credentialConfig = this.readConf()
42
- let data
43
- if (this._isOldProfileVersion(credentialConfig)) {
44
- data = {
45
- client_id: credentialConfig.devUser,
46
- client_secret: credentialConfig.devKey,
47
- grant_type: 'client_credentials',
48
- }
49
- } else {
50
- const env = process.env.NODE_ENV || DEFAULT_ENV
51
- try {
52
- data = {
53
- client_id: credentialConfig[env].devUser,
54
- client_secret: credentialConfig[env].devKey,
55
- grant_type: 'client_credentials',
56
- }
57
- } catch (e) {
58
- const errorMessage = `Configurações do ambiente (NODE_ENV=${env}) não definidas`
59
- if (process.env.LOG_LEVEL === 'full') {
60
- console.error(errorMessage, e)
61
- } else {
62
- console.error(errorMessage)
63
- }
64
-
65
- exit(1)
66
- }
67
- }
68
-
69
- return data
70
- }
71
-
72
- async getToken() {
73
- if (this.token) return this.token
74
-
75
- const clientCredentials = this.readClientCredentials()
76
- try {
77
- const url = `${this.blindGuardianUrl}/v2/o/auth`
78
- const options = {
79
- headers: {
80
- 'User-Agent': configService.get('userAgent'),
81
- },
82
- }
83
- const auth = await axios.post(url, clientCredentials, options)
84
- this.token = auth.data
85
- return this.token
86
- } catch (e) {
87
- if (this.verbose) {
88
- console.log(e)
89
- }
90
- if (e.isAxiosError) {
91
- if (e.response && e.response.status === 403) {
92
- throw new Error('Credencial inválida')
93
- }
94
- throw new Error('AuthError: Por favor tente novamente mais tarde.')
95
- }
96
- }
97
- }
98
-
99
-
100
- async createUser(userVo) {
101
- try {
102
- const url = `${this.blindGuardianUrl}/v1/o/users`
103
- const options = {
104
- headers: {
105
- 'User-Agent': configService.get('userAgent'),
106
- },
107
- }
108
- const auth = await axios.post(url, userVo, options)
109
- return auth.data
110
- } catch (e) {
111
- if (process.env.LOG_LEVEL) {
112
- console.log(e)
113
- }
114
- if (e.isAxiosError) {
115
- if (e.response && e.response.status === 403) {
116
- throw new Error('Credencial inválida')
117
- }
118
- throw new Error('Por favor tente novamente mais tarde.')
119
- }
120
- }
121
- }
122
-
123
-
124
- _isOldProfileVersion(credentialConfig) {
125
- return credentialConfig.devKey || credentialConfig.devUser
126
- ? true
127
- : false
128
- }
129
- }
130
-
131
- module.exports = BlindGuardian
@@ -1,52 +0,0 @@
1
- const TrackingEitriAnalytics = require('./TrackingEitriAnalytics')
2
- const UserLocalCredential = require('../util/UserLocalCredential')
3
-
4
- class CliLogin {
5
-
6
- async saveCredentials({email, credential}) {
7
-
8
- let devUser = "", devKey = ""
9
-
10
- try {
11
- const developerKeyDecodec = atob(credential || "")
12
- const developerKeyParsed = JSON.parse(developerKeyDecodec)
13
-
14
- if (!developerKeyParsed?.clientId || !developerKeyParsed?.clientSecret) {
15
- throw new Error("invalid_credential_format")
16
- }
17
-
18
- devUser = developerKeyParsed?.clientId
19
- devKey = developerKeyParsed?.clientSecret
20
- TrackingEitriAnalytics.sendEvent({
21
- eventName: 'login',
22
- userId: email,
23
- data: {}
24
- })
25
- } catch (error) {
26
- console.error("\n", "Não foi possível realizar o seu login. Por favor, verique as credenciais.")
27
- TrackingEitriAnalytics.sendEvent({
28
- eventName: "login.error",
29
- userId: email,
30
- data: {
31
- errorMessage: error?.message ?? ""
32
- }
33
- })
34
- process.exit(1)
35
- }
36
-
37
- await new UserLocalCredential().asyncSaveContent({devUser, devKey})
38
- TrackingEitriAnalytics.sendEvent({
39
- eventName: "login",
40
- userId: email,
41
- data: {
42
- email,
43
- devUser
44
- }
45
- })
46
- console.log("\n", `✔ Credencial gerada! Você está logado como ${email}.`)
47
- process.exit(0)
48
- }
49
-
50
- }
51
-
52
- module.exports = CliLogin
@@ -1,9 +0,0 @@
1
- const config = require('config')
2
-
3
- class ConfigService {
4
- constructor() {
5
- this.configuration = config
6
- }
7
- }
8
-
9
- module.exports = new ConfigService().configuration
@@ -1,47 +0,0 @@
1
- const configService = require('./ConfigService')
2
-
3
- class CredentialsService {
4
-
5
- constructor(workspace) {
6
- this.workspace = workspace
7
- this.conf = configService.get('workspace')
8
- }
9
-
10
- async upsert(args) {
11
- const credential = args.credential
12
-
13
- if (!credential) {
14
- throw new Error('Nao foram fornecidas credenciais.')
15
- }
16
- if (!credential.clientId) {
17
- throw new Error('Nao foi fornecido client_id')
18
- }
19
- if (!credential.clientSecret) {
20
- throw new Error('Nao foi fornecido client_secret')
21
- }
22
-
23
- credential.grantType = this.conf.credentials.defaultGrantType
24
-
25
- let publicKey = this.workspace.getMiniConf()['public-key']
26
- let ultimatePath = this.conf.credentials.upsertUrlPath.replace(':publicKey', publicKey)
27
- let url = `${this.conf.url}/${ultimatePath}`
28
-
29
- await this.workspace.http.put(url, credential)
30
- }
31
-
32
- async createApproval(args) {
33
- const approver = args.generate
34
-
35
- if (!approver) {
36
- throw new Error('Nao foi fornecido aprovador')
37
- }
38
-
39
- let publicKey = this.workspace.getMiniConf()['public-key']
40
- let ultimatePath = this.conf.credentials.approvalUrlPath
41
- let url = `${this.conf.url}/${ultimatePath}`
42
- await this.workspace.http.post(url, { approver, publicKey })
43
- }
44
-
45
- }
46
-
47
- module.exports = CredentialsService
@@ -1,32 +0,0 @@
1
- const configService = require('./ConfigService')
2
- const Http = require("./Http")
3
-
4
- class EitriAppManager {
5
- constructor(blindGuardian) {
6
- this.http = new Http(blindGuardian)
7
- this.config = configService.get('eitriManager')
8
- this.managerBaseURL = this.config.url
9
- }
10
-
11
- async findAllApplications() {
12
- const url = `${this.managerBaseURL}/p/users/self/targets`
13
- return await this.http.get(url)
14
- }
15
-
16
- async findApplicationById(applicationId) {
17
- const url = `${this.managerBaseURL}/applications/${applicationId}`
18
- return await this.http.get(url)
19
- }
20
-
21
- async create(eitriApp) {
22
- const url = `${this.managerBaseURL}/eitri-apps`
23
- try {
24
- const res = await this.http.post(url, { ...eitriApp, publicKey: '', secretKey: '', status: 'ACTIVE' })
25
- return res.data
26
- } catch (e) {
27
- Http.printLeanLogAxiosError(e)
28
- }
29
- }
30
- }
31
-
32
- module.exports = EitriAppManager
@@ -1,49 +0,0 @@
1
- const { writeFile, rename } = require("fs/promises");
2
- const chalk = require("chalk");
3
- const path = require('path')
4
- const {existsSync} = require('fs')
5
- module.exports = class EitriAppService {
6
- validEitriConf(eitriConf) {
7
- const requiredFields = ["id", "applicationId", "organizationId"];
8
- let isValid = true;
9
- for (const field of requiredFields) {
10
- if (!eitriConf[field]) isValid = false;
11
- }
12
- return isValid;
13
- }
14
-
15
- async writeEitriConf(remoteEitriConf, localEitriConf, folder2WatchPath) {
16
- if (!remoteEitriConf) return;
17
-
18
- const eitriAppConfPath = path.resolve(
19
- folder2WatchPath,
20
- "../eitri-app.conf.js"
21
- );
22
-
23
- if (!existsSync(eitriAppConfPath)) {
24
- console.warn(
25
- chalk.yellow.underline.bold(
26
- "Renomeando arquivo de configuração de miniapp.conf.js -> eitri-app.conf.js",
27
- )
28
- );
29
- const miniAppConfPath = path.resolve(
30
- folder2WatchPath,
31
- "../miniapp.conf.js"
32
- );
33
- await rename(miniAppConfPath, eitriAppConfPath);
34
- }
35
-
36
- let updatedEitriConf = {
37
- ...localEitriConf,
38
- ...remoteEitriConf,
39
- };
40
-
41
- const eitriConf = `module.exports = ${JSON.stringify(
42
- updatedEitriConf,
43
- null,
44
- '\t'
45
- )}`;
46
-
47
- await writeFile(eitriAppConfPath, eitriConf, "utf8");
48
- }
49
- }
@@ -1,132 +0,0 @@
1
- const util = require('util');
2
- const inquirer = require("inquirer");
3
- const GenericUtils = require('../../util/GenericUtils');
4
- const exec = util.promisify(require("child_process").exec)
5
- const debug = require('debug')('eitri:AndroidEmulatorService')
6
-
7
- module.exports = class AndroidEmulatorService {
8
-
9
- static async open(deepLink) {
10
- await this.checkHasInstalledAdb()
11
- const serialNumber = await this.selectDevice()
12
- const cmd = `adb -s ${serialNumber} shell am start -a android.intent.action.VIEW -d ${deepLink}`
13
- const opened = await this.openDeepLink(cmd)
14
- if (opened) return;
15
- }
16
-
17
- static async checkHasInstalledAdb() {
18
- try {
19
- console.log("Verificando instalação do ABD",)
20
- const command = "adb --version"
21
- const {stdout} = await exec(command)
22
- console.log("ADB Instalado. Continuando...\n");
23
-
24
- debug('checkHasInstalledAdb (adb --version):', stdout)
25
- } catch (error) {
26
- console.error("checkHasInstalledAdb: Comando 'adb --version' não executado. Iniciando fallback. \n")
27
- await this.checkHasInstalledAdbFallback(error)
28
- }
29
- }
30
-
31
- static async checkHasInstalledAdbFallback(firstError = {}) {
32
- try {
33
- console.log("Verificação novamente instalação do ADB...");
34
-
35
- const command = "adb devices"
36
- const {stdout} = await exec(command)
37
- console.log("ADB Instalado. Continuando...\n");
38
-
39
- debug('checkHasInstalledAdb (adb devices):', stdout)
40
- } catch (fallbackError) {
41
- console.error("checkHasInstalledAdb: Comando 'adb devices' não executado. \n")
42
- console.error("\n\ncheckHasInstalledAdb error: 'adb --version': \n", {message: firstError?.message || "", error: firstError})
43
- console.error("\n\ncheckHasInstalledAdb error: 'adb devices': \n", {message: fallbackError?.message || "", error: fallbackError})
44
-
45
- throw new Error('"adb" não instalado. Saiba mais em https://developer.android.com/tools/adb')
46
- }
47
- }
48
-
49
- static async selectDevice() {
50
- const devices = await this.checkAttachedDevices()
51
-
52
- if (devices.length === 0) {
53
- throw new Error('Dipositivo não selecionado')
54
- }
55
-
56
- if (devices.length === 1) {
57
- return GenericUtils.getSerialNumberFromAdb(devices[0])
58
- }
59
-
60
- const res = await inquirer.prompt([
61
- {
62
- name: "accepted",
63
- type: "list",
64
- message:
65
- "Selecione o Android que deseja se conectar",
66
- choices: devices,
67
- pageSize: devices.length + 2,
68
- },
69
- ]);
70
-
71
- if (res.accepted && typeof res.accepted === "string") {
72
- console.log("Dispositivo selecionado: ", res.accepted, "\n")
73
- return GenericUtils.getSerialNumberFromAdb(res.accepted)
74
- }
75
-
76
- }
77
-
78
- static async checkAttachedDevices() {
79
- console.log("Verificando dispositivos ADB conectados")
80
- const devices = await this.getListAdbDevices()
81
- if (!devices.length) {
82
- throw new Error('Nenhum dispositivo/emulador encontrado')
83
- }
84
-
85
- return devices
86
- }
87
-
88
- static async openDeepLink(cmd) {
89
- try {
90
- const { stderr } = await exec(cmd)
91
- return !(stderr);
92
- } catch (error) {
93
- console.log(`Houve um erro ao tentar abrir o Eitri-App via deep link`)
94
- console.log(error)
95
- return process.exit(1)
96
- }
97
- }
98
-
99
- static async getListAdbDevices() {
100
-
101
- return new Promise((resolve, _reject) => {
102
- exec('adb devices -l', (error, stdout, _stderr) => {
103
- if (error) {
104
- console.error(`Erro ao executar o comando: ${error}`);
105
- resolve([]);
106
- return;
107
- }
108
-
109
- if(!stdout || stdout.trim() === ""){
110
- console.error(`'adb devices -l' vazio ou nulo: ${error}`);
111
- resolve([]);
112
- return;
113
- }
114
-
115
- const adbDevices = []
116
- const devicesList = stdout?.split('\n');
117
- const devices = devicesList?.slice(1, -2);
118
-
119
- devices?.forEach(device => {
120
- adbDevices.push(device)
121
- });
122
- resolve(adbDevices)
123
- });
124
-
125
- })
126
- }
127
-
128
-
129
-
130
- }
131
-
132
-
@@ -1,71 +0,0 @@
1
- const util = require('util');
2
- const exec = util.promisify(require("child_process").exec)
3
- const inquirer = require("inquirer");
4
-
5
- module.exports = class IOSEmulatorService {
6
-
7
- static async open(deepLink) {
8
- await this.checkHasInstalledXcode()
9
-
10
- const cmd = `xcrun simctl openurl booted ${deepLink}`
11
- const opened = await this.openDeepLink(cmd)
12
- if (opened) return;
13
-
14
- }
15
-
16
- static async openDeepLink(cmd) {
17
- try {
18
- const {stderr} = await exec(cmd)
19
- return !(stderr);
20
- } catch (error) {
21
- console.log(`Houve um erro ao tentar abrir o Eitri-App via deep link`)
22
- console.log(error)
23
- return process.exit(1)
24
- }
25
- }
26
-
27
- static async checkHasInstalledXcode(){
28
- try {
29
- console.log("Verificando instalação do Xcode.")
30
- const command = "xcode-select -p"
31
- await exec(command)
32
- console.log("Xcode instalado")
33
- } catch (error) {
34
- throw new Error('"Xcode" não encontrado. Saiba mais em https://developer.apple.com/xcode/')
35
- }
36
- }
37
-
38
- /**
39
- * TODO implementar seleção de iPhone
40
- */
41
- static async selectDevice(){
42
- const devices = this.getListIphones()
43
- const res = await inquirer.prompt([
44
- {
45
- name: "accepted",
46
- type: "list",
47
- message:
48
- "Selecione o iPhone que deseja se conectar",
49
- choices: devices,
50
- pageSize: devices.length + 2,
51
- },
52
- ]);
53
-
54
- if (res.accepted && typeof res.accepted === "string") {
55
- console.log("iPhone selecionado: ", res.accepted, "\n")
56
- return GenericUtils.getSerialNumberFromAdb(res.accepted)
57
- }
58
-
59
- }
60
- /**
61
- * TODO implementar lista de iPhones
62
- */
63
- static async getListIphones(){
64
- console.log("Verificando dispositivos Apple conectados")
65
- const command = 'xcrun simctl list devices | grep -i "iphone"'
66
- await exec(command)
67
- }
68
-
69
- }
70
-
71
-
@@ -1,17 +0,0 @@
1
- const AndroidEmulatorService = require('./Emulator/AndroidEmulatorService');
2
- const IOSEmulatorService = require('./Emulator/IOSEmulatorService');
3
-
4
- module.exports = class EmulatorService {
5
-
6
- static async openSimulator(emulator, deeplink) {
7
- try {
8
- const emulatorService = emulator === "ios" ? IOSEmulatorService : AndroidEmulatorService;
9
- await emulatorService.open(deeplink)
10
- } catch (error) {
11
- throw {message: error.message}
12
- }
13
- }
14
-
15
- }
16
-
17
-
@@ -1,16 +0,0 @@
1
- const { workspace } = require('./Workspace')
2
-
3
- const mobile = workspace.getKnownAvailableTargets()[0].code
4
-
5
- const setMobileLibs2GA = (miniConf) => {
6
- return {
7
- superClientVersion: miniConf['eitri-app-client'],
8
- componentsVersion: miniConf['eitri-app-components']
9
- }
10
- }
11
-
12
- const MINIAPP_TARGET = {
13
- [mobile]: setMobileLibs2GA
14
- }
15
-
16
- module.exports = MINIAPP_TARGET
@@ -1,79 +0,0 @@
1
- const fs = require('fs')
2
- const path = require('path')
3
- const {hashElement} = require('folder-hash')
4
-
5
- class HashFolder {
6
- async calculate() {
7
- const options = {
8
- folders: {exclude: ['.*', 'node_modules', 'test_coverage']},
9
- files: {
10
- include: [
11
- '*.js',
12
- '*.jsx',
13
- '*.json',
14
- '*.svg',
15
- '*.png',
16
- '*.jpg',
17
- '*.jpeg',
18
- '*.gif',
19
- '*.txt',
20
- ],
21
- },
22
- }
23
- // let start = new Date().getTime();
24
- const result = await hashElement(path.join(process.cwd(), 'src'), options)
25
- // console.log(`${new Date().getTime() - start}ms`);
26
- return result
27
- }
28
-
29
- writeHashFile(oldContent, content) {
30
- return new Promise((resolve, reject) => {
31
- fs.writeFile(
32
- path.join(process.cwd(), 'src/folder.hash'),
33
- `${oldContent}\n${content}`,
34
- (err) => {
35
- if (err) {
36
- console.log(err)
37
- return reject(err)
38
- }
39
- resolve()
40
- },
41
- )
42
- })
43
- }
44
-
45
- readHashFile() {
46
- return new Promise((resolve, reject) => {
47
- const fileName = path.join(process.cwd(), 'src/folder.hash')
48
- if (!fs.existsSync(fileName)) {
49
- resolve(null)
50
- return
51
- }
52
- fs.readFile(fileName, 'utf8', (err, data) => {
53
- if (err) {
54
- reject(err)
55
- return
56
- }
57
- resolve(data)
58
- })
59
- })
60
- }
61
-
62
- async readCurrentHash() {
63
- const current = await this.readHashFile()
64
- if (!current) {
65
- return null
66
- }
67
- return current.split('\n').pop()
68
- }
69
-
70
- async updateHashFile() {
71
- const res = await this.calculate()
72
- const current = await this.readCurrentHash()
73
- if (current !== res['hash']) {
74
- await this.writeHashFile(current, res['hash'])
75
- }
76
- }
77
- }
78
-
79
- module.exports = HashFolder