-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathindex.ts
More file actions
264 lines (237 loc) · 6.74 KB
/
index.ts
File metadata and controls
264 lines (237 loc) · 6.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { StorageEngineConnectionConfig } from '@cloudgraph/sdk'
import boxen from 'boxen'
import CFonts from 'cfonts'
import chalk from 'chalk'
import { exec } from 'child_process'
import fs from 'fs'
import glob from 'glob'
import path from 'path'
import detect from 'detect-port'
import C, { DEFAULT_CONFIG, DGRAPH_CONTAINER_LABEL } from '../utils/constants'
export const getKeyByValue = (
object: Record<string, unknown>,
value: any
): string | undefined => {
return Object.keys(object).find(key => object[key] === value)
}
export function moduleIsAvailable(modulePath: string): boolean {
try {
require.resolve(modulePath)
return true
} catch (error) {
return false
}
}
export function getProviderDataFile(
dirPath: string,
provider: string
): string | void {
const fileGlob = `${dirPath}${provider}*.json`
const fileArray = glob.sync(fileGlob)
if (fileArray && fileArray.length > 0) {
return fileArray[0]
}
}
const mapFileNameToHumanReadable = (file: string): string => {
const fileNameParts = file.split('/')
const fileName = fileNameParts[fileNameParts.length - 1]
const [providerName, timestamp] = fileName.replace('.json', '').split('_')
return `${providerName} ${new Date(Number(timestamp)).toISOString()}`
}
// TODO: this could be refactored to go right to the correct version folder (avoid line 70)
// if we extracted the version part of the url and passed to this func
const findProviderFileLocation = (directory: string, file: string): string => {
const [providerName, date] = file.trim().split(' ')
const fileName = `${providerName}_${Date.parse(date)}`
const fileGlob = path.join(directory, `/version-*/${fileName}.json`)
const fileArray = glob.sync(fileGlob)
if (fileArray && fileArray.length > 0) {
return fileArray[0]
}
return ''
}
export function makeDirIfNotExists(dir: string): void {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true })
}
}
export function buildFixedPath(dir: string, provider?: string): string {
const dirArray = provider?.replace(/\\/g, '/').includes('/')
? provider?.replace(/\\/g, '/').split('/')
: []
return path.normalize(
`${dir}/${dirArray.slice(0, dirArray.length - 1).join('/')}`
)
}
export function writeGraphqlSchemaToFile(
dirPath: string,
schema: string,
provider?: string
): void {
makeDirIfNotExists(buildFixedPath(dirPath, provider))
fs.writeFileSync(
path.normalize(
path.join(
dirPath,
provider ? `/${provider}_schema.graphql` : '/schema.graphql'
)
),
schema
)
}
export function printWelcomeMessage(): void {
CFonts.say('Welcome to|CloudGraph!', {
font: 'grid',
colors: ['#666EE8', '#B8FFBD', '#B8FFBD'],
lineHight: 3,
align: 'center',
})
console.log(
boxen(chalk.italic.green('By AutoCloud'), {
borderColor: 'green',
align: 'center',
borderStyle: 'singleDouble',
float: 'center',
padding: 1,
})
)
}
export function printBoxMessage(msg: string): void {
console.log(
boxen(msg, {
borderColor: 'green',
})
)
}
export function getVersionFolders(
directory: string,
provider?: string
): { name: string; ctime: Date }[] {
const folderGlob = path.join(directory, '/version-*/')
const folders = glob.sync(folderGlob)
if (folders && folders.length > 0) {
return folders
.map((name: string) => ({ name, ctime: fs.statSync(name).ctime }))
.filter(({ name }: { name: string }) => {
if (provider) {
const filesInFolder = glob.sync(`${name}**/*`)
if (
filesInFolder.find((val: string) =>
val.includes(`${provider}_schema.graphql`)
)
) {
return true
}
return false
}
return true
})
.sort(
(a: { name: string; ctime: Date }, b: { name: string; ctime: Date }) =>
a.ctime.getTime() - b.ctime.getTime()
)
}
return []
}
export function deleteFolder(dirPath: string): void {
fs.rmSync(dirPath, { recursive: true })
}
export const getStoredSchema = (dirPath: string): string => {
try {
const schemaPath = path.normalize(`${dirPath}/cg/schema.graphql`)
const schema = fs.readFileSync(schemaPath, 'utf8')
return schema
} catch (error) {
// Return an empty string if a schema was not found
return ''
}
}
export const sleep = (ms: number): Promise<void> =>
new Promise(resolve => setTimeout(resolve, ms * 1000))
export const calculateBackoff = (n: number): number => {
const temp = Math.min(
C.BASE_BACKOFF_CONSTANT ** n + Math.random(),
C.MAX_BACKOFF_DELAY
)
return (
temp / C.BASE_BACKOFF_CONSTANT +
Math.min(0, (Math.random() * temp) / C.BASE_BACKOFF_CONSTANT)
)
}
export const getPort = (
hostname: string,
scheme: string,
port?: string
): string => {
if (hostname !== 'localhost' && !port) {
switch (scheme) {
case 'http':
return '80'
case 'https':
return '443'
default:
return '80'
}
}
if (port) {
return port
}
return DEFAULT_CONFIG.port
}
export const getDefaultStorageEngineConnectionConfig =
(): typeof DEFAULT_CONFIG => DEFAULT_CONFIG
export const getDefaultEndpoint = (): string =>
`${DEFAULT_CONFIG.scheme}://${DEFAULT_CONFIG.host}:${DEFAULT_CONFIG.port}`
export const getStorageEngineConnectionConfig = (
fullUrl: string = getDefaultEndpoint()
): StorageEngineConnectionConfig => {
const { hostname: host, port, protocol } = new URL(fullUrl)
const scheme = protocol.split(':')[0]
return {
host,
port: getPort(host, protocol, port),
scheme,
}
}
export const execCommand = (cmd: string): Promise<void> => {
return new Promise((resolve, reject) => {
exec(cmd, (error: any, stdout: any, stderr: any) => {
if (error) {
reject(error)
}
resolve(stdout || stderr)
})
})
}
export const findExistingDGraphContainerId = async (
statusFilter: string
): Promise<string> => {
let result: string
let stdout: any
stdout = await execCommand(
`docker ps --filter label=${DGRAPH_CONTAINER_LABEL} --filter status=${statusFilter} --quiet`
)
result = stdout.trim()
if (!result) {
stdout = await execCommand(
`docker ps --filter name=dgraph --filter status=${statusFilter} --quiet`
)
result = stdout.trim()
}
return result
}
export const fileUtils = {
mapFileNameToHumanReadable,
makeDirIfNotExists,
writeGraphqlSchemaToFile,
getVersionFolders,
findProviderFileLocation,
getProviderDataFile,
deleteFolder,
}
export const getNextPort = async (port: number): Promise<string> => {
const availablePort = await detect(port)
return String(availablePort)
}
export const cleanString = (dirtyString: string): string =>
dirtyString.replace(/(\r\n|\n|\r)/gm, '').replace(/\s+/g, '')