forked from metacall/faas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
180 lines (155 loc) · 4.68 KB
/
utils.ts
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
import { exec } from 'child_process';
import * as fs from 'fs';
import { platform } from 'os';
import { join } from 'path';
import { LanguageId, MetaCallJSON } from '@metacall/protocol/deployment';
import { generatePackage, PackageError } from '@metacall/protocol/package';
import { NextFunction, Request, RequestHandler, Response } from 'express';
import {
createInstallDependenciesScript,
currentFile,
IAllApps
} from '../constants';
export const dirName = (gitUrl: string): string =>
String(gitUrl.split('/')[gitUrl.split('/').length - 1]).replace('.git', '');
// Create a proper hashmap that contains all the installation commands mapped to their runner name and shorten this function
export const installDependencies = async (): Promise<void> => {
if (!currentFile.runners) return;
for (const runner of currentFile.runners) {
if (runner == undefined) continue;
else {
await execPromise(
createInstallDependenciesScript(runner, currentFile.path)
);
}
}
};
//check if repo contains metacall-*.json if not create and calculate runners then install dependencies
export const calculatePackages = async (): Promise<void> => {
const data = await generatePackage(currentFile.path);
if (data.error == PackageError.Empty) throw PackageError.Empty;
// currentFile.jsons = JSON.parse(data.jsons.toString()); FIXME Fix this line
currentFile.runners = data.runners;
};
export const exists = (path: string): Promise<boolean> =>
fs.promises.stat(path).then(
() => true,
() => false
);
export const ensureFolderExists = async <Path extends string>(
path: Path
): Promise<Path> => (
(await exists(path)) ||
(await fs.promises.mkdir(path, { recursive: true })),
path
);
export const deleteRepoFolderIfExist = <Path extends string>(
path: Path,
url: string
): void => {
const folder = dirName(url);
const repoFilePath = join(path, folder);
fs.rmSync(repoFilePath, { recursive: true, force: true });
};
export const execPromise = (
command: string
): Promise<{
stdout: string;
stderr: string;
}> =>
new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
reject(error);
} else {
resolve({ stdout, stderr });
}
});
});
export const catchAsync = (
fn: (req: Request, res: Response, next: NextFunction) => Promise<void>
): RequestHandler => {
return (req: Request, res: Response, next: NextFunction) => {
fn(req, res, next).catch(err => next(err));
};
};
export const createMetacallJsonFile = (
jsons: MetaCallJSON[],
path: string
): string[] => {
const acc: string[] = [];
jsons.forEach(el => {
const filePath = `${path}/metacall-${el.language_id}.json`;
fs.writeFileSync(filePath, JSON.stringify(el));
acc.push(filePath);
});
return acc;
};
const missing = (name: string): string =>
`Missing ${name} environment variable! Unable to load config`;
export const configDir = (name: string): string =>
platform() === 'win32'
? process.env.APPDATA
? join(process.env.APPDATA, name)
: missing('APPDATA')
: process.env.HOME
? join(process.env.HOME, `.${name}`)
: missing('HOME');
export const getLangId = (input: string): LanguageId => {
const parts = input.split('-');
const extension = parts[parts.length - 1].split('.')[0];
return extension as LanguageId;
};
//eslint-disable-next-line
export const diff = (object1: any, object2: any): any => {
for (const key in object2) {
//eslint-disable-next-line
if (Array.isArray(object2[key])) {
//eslint-disable-next-line
object1[key] = object1[key].filter(
(
item: any // eslint-disable-line
) => !object2[key].find((i: any) => i.name === item.name) // eslint-disable-line
);
}
}
return object1; // eslint-disable-line
};
export function isIAllApps(data: unknown): data is IAllApps {
return typeof data === 'object' && data !== null;
}
export const listDirectoriesWithPrefix = (
searchString: string,
appsDir: string
): string[] => {
try {
const filteredDirectories = fs
.readdirSync(appsDir)
.filter(
file =>
fs.statSync(join(appsDir, file)).isDirectory() &&
file.startsWith(searchString)
);
return filteredDirectories;
} catch (err) {
console.error('Error reading directory:', err);
return [];
}
};
export const isArrEmpty = <T>(arr: T[]): boolean => arr.length === 0;
export const getCorrectNameWithVersion = (
appName: string,
appsWithSameName: string[]
): string => {
if (isArrEmpty(appsWithSameName)) {
return appName + '-v1';
}
const lastApp = appsWithSameName[appsWithSameName.length - 1];
const regex = /-v(\d+)$/;
const match = regex.exec(lastApp);
if (match) {
const versionNumber = parseInt(match[1]) + 1;
return currentFile.id + '-v' + versionNumber.toString();
}
return '';
};